// NoteSelectionModal.jsx - Modal for selecting notes to add to chat context
function NoteSelectionModal({ token, onSelect, onClose, t }) {
    const [notes, setNotes] = useState([]);
    const [selectedNoteIds, setSelectedNoteIds] = useState([]);
    const [searchQuery, setSearchQuery] = useState('');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetchNotes();
    }, []);

    const fetchNotes = async () => {
        try {
            setLoading(true);
            const response = await fetch(`${API_URL}/notes`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setNotes(data.notes || []);
        } catch (error) {
            console.error('Failed to fetch notes:', error);
        } finally {
            setLoading(false);
        }
    };

    const filteredNotes = searchQuery
        ? notes.filter(note =>
            note.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
            (note.subject && note.subject.toLowerCase().includes(searchQuery.toLowerCase()))
        )
        : notes;

    const toggleNote = (noteId) => {
        setSelectedNoteIds(prev =>
            prev.includes(noteId)
                ? prev.filter(id => id !== noteId)
                : [...prev, noteId]
        );
    };

    const handleCreate = () => {
        onSelect(selectedNoteIds);
    };

    return (
        <div
            style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: 'rgba(0, 0, 0, 0.6)',
                backdropFilter: 'blur(4px)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 1000,
                padding: '1rem'
            }}
            onClick={onClose}
        >
            <div
                onClick={(e) => e.stopPropagation()}
                style={{
                    background: 'white',
                    borderRadius: '20px',
                    width: '100%',
                    maxWidth: '700px',
                    maxHeight: '80vh',
                    display: 'flex',
                    flexDirection: 'column',
                    boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)',
                    overflow: 'hidden'
                }}
            >
                {/* Header */}
                <div style={{
                    padding: '1.5rem 2rem',
                    borderBottom: '1px solid #e2e8f0',
                    background: 'linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1))'
                }}>
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        marginBottom: '1rem'
                    }}>
                        <h2 style={{
                            fontSize: '1.5rem',
                            fontWeight: '700',
                            color: '#1e293b',
                            margin: 0
                        }}>
                            {t('ask.selectNotes') || 'Select Notes'}
                        </h2>
                        <button
                            onClick={onClose}
                            style={{
                                background: 'none',
                                border: 'none',
                                fontSize: '1.5rem',
                                cursor: 'pointer',
                                color: '#64748b',
                                transition: 'color 0.2s'
                            }}
                            onMouseEnter={e => e.currentTarget.style.color = '#ef4444'}
                            onMouseLeave={e => e.currentTarget.style.color = '#64748b'}
                        >
                            ×
                        </button>
                    </div>

                    {/* Search */}
                    <input
                        type="text"
                        placeholder={t('ask.searchNotes') || 'Search notes...'}
                        value={searchQuery}
                        onChange={e => setSearchQuery(e.target.value)}
                        style={{
                            width: '100%',
                            padding: '0.75rem 1rem',
                            borderRadius: '12px',
                            border: '2px solid #e2e8f0',
                            fontSize: '0.9375rem',
                            outline: 'none',
                            transition: 'border-color 0.2s'
                        }}
                        onFocus={e => e.target.style.borderColor = '#667eea'}
                        onBlur={e => e.target.style.borderColor = '#e2e8f0'}
                    />
                </div>

                {/* Notes List */}
                <div style={{
                    flex: 1,
                    overflowY: 'auto',
                    padding: '1.5rem 2rem'
                }}>
                    {loading ? (
                        <div style={{ textAlign: 'center', padding: '3rem', color: '#94a3b8' }}>
                            <div className="loading"></div>
                            <p style={{ marginTop: '1rem' }}>{t('common.loading') || 'Loading...'}</p>
                        </div>
                    ) : filteredNotes.length === 0 ? (
                        <div style={{
                            textAlign: 'center',
                            padding: '3rem',
                            color: '#94a3b8'
                        }}>
                            <div style={{ fontSize: '3rem', marginBottom: '1rem', opacity: 0.5 }}>📝</div>
                            <p>{searchQuery ? (t('ask.noNotesFound') || 'No notes found') : (t('ask.noNotesAvailable') || 'No notes available')}</p>
                        </div>
                    ) : (
                        <div style={{ display: 'grid', gap: '0.75rem' }}>
                            {filteredNotes.map(note => (
                                <SelectableNoteCard
                                    key={note.id}
                                    note={note}
                                    isSelected={selectedNoteIds.includes(note.id)}
                                    onToggle={() => toggleNote(note.id)}
                                />
                            ))}
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div style={{
                    padding: '1.25rem 2rem',
                    borderTop: '1px solid #e2e8f0',
                    background: '#f8fafc',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between'
                }}>
                    <div style={{
                        fontSize: '0.875rem',
                        color: '#64748b',
                        fontWeight: '600'
                    }}>
                        {selectedNoteIds.length > 0 && (
                            <span style={{
                                background: 'linear-gradient(135deg, #667eea, #764ba2)',
                                color: 'white',
                                padding: '0.375rem 0.75rem',
                                borderRadius: '8px'
                            }}>
                                {selectedNoteIds.length} selected
                            </span>
                        )}
                    </div>
                    <div style={{ display: 'flex', gap: '0.75rem' }}>
                        <button
                            onClick={onClose}
                            style={{
                                padding: '0.75rem 1.5rem',
                                borderRadius: '12px',
                                border: '2px solid #e2e8f0',
                                background: 'white',
                                color: '#64748b',
                                fontWeight: '600',
                                cursor: 'pointer',
                                transition: 'all 0.2s'
                            }}
                            onMouseEnter={e => e.currentTarget.style.borderColor = '#cbd5e1'}
                            onMouseLeave={e => e.currentTarget.style.borderColor = '#e2e8f0'}
                        >
                            {t('common.cancel') || 'Cancel'}
                        </button>
                        <button
                            onClick={handleCreate}
                            disabled={selectedNoteIds.length === 0}
                            style={{
                                padding: '0.75rem 1.5rem',
                                borderRadius: '12px',
                                border: 'none',
                                background: selectedNoteIds.length > 0
                                    ? 'linear-gradient(135deg, #667eea, #764ba2)'
                                    : '#e2e8f0',
                                color: 'white',
                                fontWeight: '600',
                                cursor: selectedNoteIds.length > 0 ? 'pointer' : 'not-allowed',
                                boxShadow: selectedNoteIds.length > 0 ? '0 4px 15px rgba(102, 126, 234, 0.4)' : 'none',
                                transition: 'all 0.3s'
                            }}
                            onMouseEnter={e => {
                                if (selectedNoteIds.length > 0) {
                                    e.currentTarget.style.transform = 'translateY(-2px)';
                                    e.currentTarget.style.boxShadow = '0 6px 20px rgba(102, 126, 234, 0.5)';
                                }
                            }}
                            onMouseLeave={e => {
                                e.currentTarget.style.transform = 'translateY(0)';
                                e.currentTarget.style.boxShadow = selectedNoteIds.length > 0 ? '0 4px 15px rgba(102, 126, 234, 0.4)' : 'none';
                            }}
                        >
                            {t('ask.createChat') || 'Create Chat'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}

// Selectable Note Card
function SelectableNoteCard({ note, isSelected, onToggle }) {
    const [isHovered, setIsHovered] = useState(false);

    return (
        <div
            onClick={onToggle}
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            style={{
                padding: '1rem 1.25rem',
                borderRadius: '12px',
                border: `2px solid ${isSelected ? '#667eea' : '#e2e8f0'}`,
                background: isSelected
                    ? 'rgba(102, 126, 234, 0.05)'
                    : isHovered
                        ? '#f8fafc'
                        : 'white',
                cursor: 'pointer',
                transition: 'all 0.2s',
                position: 'relative'
            }}
        >
            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                {/* Checkbox */}
                <div style={{
                    width: '20px',
                    height: '20px',
                    borderRadius: '6px',
                    border: `2px solid ${isSelected ? '#667eea' : '#cbd5e1'}`,
                    background: isSelected ? 'linear-gradient(135deg, #667eea, #764ba2)' : 'white',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexShrink: 0,
                    transition: 'all 0.2s'
                }}>
                    {isSelected && (
                        <span style={{ color: 'white', fontSize: '0.875rem', fontWeight: '700' }}>✓</span>
                    )}
                </div>

                {/* Note Info */}
                <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                        fontSize: '0.9375rem',
                        fontWeight: '600',
                        color: '#1e293b',
                        marginBottom: '0.25rem',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                    }}>
                        {note.title}
                    </div>
                    <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
                        {note.subject && (
                            <span style={{
                                fontSize: '0.7rem',
                                fontWeight: '600',
                                color: '#667eea',
                                background: 'rgba(102, 126, 234, 0.1)',
                                padding: '0.125rem 0.5rem',
                                borderRadius: '4px'
                            }}>
                                {note.subject}
                            </span>
                        )}
                        {note.block_count > 0 && (
                            <span style={{ fontSize: '0.7rem', color: '#94a3b8' }}>
                                📝 {note.block_count} blocks
                            </span>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}

window.NoteSelectionModal = NoteSelectionModal;
