// FeedbackModal Component
// Modal for collecting user feedback

function FeedbackModal({ t, onClose }) {
    const [rating, setRating] = useState(0);
    const [category, setCategory] = useState('');
    const [feedbackText, setFeedbackText] = useState('');
    const [submitted, setSubmitted] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            // Get token from localStorage
            const token = localStorage.getItem('token');

            // Submit to backend
            const response = await fetch(API_URL + '/feedback/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    rating,
                    category,
                    feedback_text: feedbackText
                })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.detail || 'Failed to submit feedback');
            }

            console.log('✅ Feedback submitted:', data);
            setSubmitted(true);

            setTimeout(() => {
                onClose();
            }, 2000);

        } catch (error) {
            console.error('❌ Error submitting feedback:', error);
            alert('Failed to submit feedback. Please try again.');
        }
    };

    const categories = [
        { value: 'bug', label: '🐛 Bug Report', icon: '🐛' },
        { value: 'feature', label: '✨ Feature Request', icon: '✨' },
        { value: 'ui', label: '🎨 UI/UX Feedback', icon: '🎨' },
        { value: 'performance', label: '⚡ Performance', icon: '⚡' },
        { value: 'other', label: '💬 General', icon: '💬' }
    ];

    return (
        <div
            onClick={(e) => e.target === e.currentTarget && onClose()}
            style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: 'rgba(0, 0, 0, 0.7)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 9999,
                padding: '20px'
            }}
        >
            <div
                className="card"
                style={{
                    maxWidth: '700px',
                    width: '100%',
                    maxHeight: '90vh',
                    overflowY: 'auto',
                    background: 'var(--bg-primary)',
                    borderRadius: '16px',
                    padding: '0',
                    boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)'
                }}
            >
                <div style={{
                    background: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
                    padding: '24px',
                    borderRadius: '16px 16px 0 0',
                    color: 'white'
                }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                        <h2 style={{ fontSize: '24px', fontWeight: '700', margin: 0 }}>
                            💬 {t('common.feedback') || 'Share Your Feedback'}
                        </h2>
                        <button
                            onClick={onClose}
                            style={{
                                background: 'rgba(255, 255, 255, 0.2)',
                                border: 'none',
                                borderRadius: '50%',
                                width: '36px',
                                height: '36px',
                                cursor: 'pointer',
                                fontSize: '20px',
                                color: 'white',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}
                        >
                            ×
                        </button>
                    </div>
                    <p style={{ fontSize: '14px', opacity: 0.9, margin: 0 }}>
                        Help us improve NoteVerse by sharing your thoughts
                    </p>
                </div>

                {!submitted ? (
                    <form onSubmit={handleSubmit} style={{ padding: '24px' }}>
                        <div style={{ marginBottom: '24px' }}>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: 'var(--text-primary)',
                                marginBottom: '12px'
                            }}>
                                How would you rate your experience? *
                            </label>
                            <div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
                                {[1, 2, 3, 4, 5].map(star => (
                                    <button
                                        key={star}
                                        type="button"
                                        onClick={() => setRating(star)}
                                        style={{
                                            background: 'none',
                                            border: 'none',
                                            fontSize: '40px',
                                            cursor: 'pointer',
                                            transition: 'transform 0.2s',
                                            padding: '8px'
                                        }}
                                        onMouseEnter={(e) => e.target.style.transform = 'scale(1.2)'}
                                        onMouseLeave={(e) => e.target.style.transform = 'scale(1)'}
                                    >
                                        {star <= rating ? '⭐' : '☆'}
                                    </button>
                                ))}
                            </div>
                            {rating > 0 && (
                                <div style={{
                                    textAlign: 'center',
                                    marginTop: '8px',
                                    fontSize: '14px',
                                    color: 'var(--text-secondary)'
                                }}>
                                    {rating === 5 ? '🎉 Amazing!' : rating === 4 ? '👍 Great!' : rating === 3 ? '😊 Good' : rating === 2 ? '😐 Okay' : '😞 Needs Work'}
                                </div>
                            )}
                        </div>

                        <div style={{ marginBottom: '24px' }}>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: 'var(--text-primary)',
                                marginBottom: '12px'
                            }}>
                                What's this about? *
                            </label>
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: '12px' }}>
                                {categories.map(cat => (
                                    <button
                                        key={cat.value}
                                        type="button"
                                        onClick={() => setCategory(cat.value)}
                                        style={{
                                            padding: '12px 16px',
                                            border: `2px solid ${category === cat.value ? '#4A90E2' : 'var(--border-color)'}`,
                                            background: category === cat.value ? 'rgba(74, 144, 226, 0.1)' : 'var(--bg-secondary)',
                                            borderRadius: '8px',
                                            cursor: 'pointer',
                                            fontSize: '13px',
                                            fontWeight: category === cat.value ? '600' : '500',
                                            color: 'var(--text-primary)',
                                            transition: 'all 0.2s',
                                            textAlign: 'left'
                                        }}
                                    >
                                        <div>{cat.icon}</div>
                                        <div style={{ marginTop: '4px', fontSize: '12px' }}>
                                            {cat.label.split(' ').slice(1).join(' ')}
                                        </div>
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div style={{ marginBottom: '24px' }}>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: 'var(--text-primary)',
                                marginBottom: '12px'
                            }}>
                                Tell us more *
                            </label>
                            <textarea
                                value={feedbackText}
                                onChange={(e) => setFeedbackText(e.target.value)}
                                placeholder="Share your thoughts, suggestions, or report issues..."
                                required
                                style={{
                                    width: '100%',
                                    minHeight: '120px',
                                    padding: '12px',
                                    border: '1px solid var(--border-color)',
                                    borderRadius: '8px',
                                    fontSize: '14px',
                                    fontFamily: 'inherit',
                                    resize: 'vertical',
                                    background: 'var(--bg-secondary)',
                                    color: 'var(--text-primary)'
                                }}
                            />
                        </div>

                        <div style={{ display: 'flex', gap: '12px', marginTop: '24px' }}>
                            <button
                                type="button"
                                onClick={onClose}
                                className="btn btn-secondary"
                                style={{ flex: 1 }}
                            >
                                Cancel
                            </button>
                            <button
                                type="submit"
                                className="btn btn-primary"
                                style={{
                                    flex: 1,
                                    background: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
                                    opacity: (!rating || !category || !feedbackText) ? 0.5 : 1,
                                    cursor: (!rating || !category || !feedbackText) ? 'not-allowed' : 'pointer'
                                }}
                                disabled={!rating || !category || !feedbackText}
                            >
                                Submit Feedback
                            </button>
                        </div>
                    </form>
                ) : (
                    <div style={{ padding: '48px 24px', textAlign: 'center' }}>
                        <div style={{ fontSize: '64px', marginBottom: '16px' }}>🎉</div>
                        <h3 style={{ fontSize: '24px', fontWeight: '700', color: 'var(--text-primary)', marginBottom: '8px' }}>
                            Thank You!
                        </h3>
                        <p style={{ color: 'var(--text-secondary)', fontSize: '14px' }}>
                            Your feedback helps us make NoteVerse better for everyone.
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
}

// Export to global scope
window.FeedbackModal = FeedbackModal;
