function AdvancedNotes({ user, token, actionParams, setActionParams }) {
    const [view, setView] = useState('list');
    const [notes, setNotes] = useState([]);
    const [currentNote, setCurrentNote] = useState(null);
    const [loading, setLoading] = useState(false);
    const [metadata, setMetadata] = useState({ tags: [], subjects: [], groups: [] });
    const [settings, setSettings] = useState({ store_original_files: true });
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [showEditModal, setShowEditModal] = useState(false);
    const [editingNote, setEditingNote] = useState(null);
    const [newNoteData, setNewNoteData] = useState({
        title: '', subject: '', tags: [], note_group: '', canvas_enabled: false
    });
    const [showSubjectInput, setShowSubjectInput] = useState(false);
    const [showGroupInput, setShowGroupInput] = useState(false);
    const [newSubjectInput, setNewSubjectInput] = useState('');
    const [newGroupInput, setNewGroupInput] = useState('');
    const [openNoteId, setOpenNoteId] = useState(null);
    const [viewMode, setViewMode] = useState('list'); // 'list' or 'canvas'
    const [activeFilters, setActiveFilters] = useState({ subject: null, group: null, timeline: null });
    const [showFilters, setShowFilters] = useState(false);

    useEffect(() => {
        loadNotes();
        loadMetadata();
        loadSettings();
    }, [activeFilters]);

    useEffect(() => {
        if (actionParams?.action === 'create') {
            setShowCreateModal(true);
            if (setActionParams) setActionParams(null);
        }
    }, [actionParams]);

    const loadNotes = async () => {
        try {
            // Build query string from active filters
            const params = new URLSearchParams();
            if (activeFilters.subject) params.append('subject', activeFilters.subject);
            if (activeFilters.group) params.append('group', activeFilters.group);
            if (activeFilters.timeline) params.append('date_filter', activeFilters.timeline);

            const queryString = params.toString();
            const url = `${API_URL}/notes${queryString ? '?' + queryString : ''}`;

            const response = await fetch(url, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setNotes(data.notes || []);
        } catch (err) {
            console.error('Failed to load notes:', err);
        }
    };

    const loadMetadata = async () => {
        try {
            const [tags, subjects, groups] = await Promise.all([
                fetch(`${API_URL}/metadata/tags`, { headers: { 'Authorization': `Bearer ${token}` } }).then(r => r.json()),
                fetch(`${API_URL}/metadata/subjects`, { headers: { 'Authorization': `Bearer ${token}` } }).then(r => r.json()),
                fetch(`${API_URL}/metadata/groups`, { headers: { 'Authorization': `Bearer ${token}` } }).then(r => r.json())
            ]);
            setMetadata({
                tags: tags.tags || [],
                subjects: subjects.subjects || [],
                groups: groups.groups || []
            });
        } catch (err) {
            console.error('Failed to load metadata:', err);
        }
    };

    const loadSettings = async () => {
        try {
            const response = await fetch(`${API_URL}/settings`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setSettings(data);
        } catch (err) {
            console.error('Failed to load settings:', err);
        }
    };

    const createNote = async () => {
        if (!newNoteData.subject && newNoteData.tags.length === 0 && !newNoteData.note_group) {
            alert('Please provide at least one of: Subject, Tag, or Group');
            return;
        }

        try {
            setLoading(true);
            const response = await fetch(`${API_URL}/notes/create`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                body: JSON.stringify(newNoteData)
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.detail);

            await loadNotes();
            setShowCreateModal(false);
            setNewNoteData({ title: '', subject: '', tags: [], note_group: '', canvas_enabled: false });
            openNote(data.note_id);
        } catch (err) {
            alert(`Failed to create note: ${err.message}`);
        } finally {
            setLoading(false);
        }
    };

    const openNote = async (noteId) => {
        try {
            const response = await fetch(`${API_URL}/notes/${noteId}`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setCurrentNote(data);
            setView('canvas');
        } catch (err) {
            alert('Failed to load note');
        }
    };

    const deleteNote = async (noteId) => {
        if (!confirm('Are you sure you want to delete this note?')) return;
        try {
            await fetch(`${API_URL}/notes/${noteId}`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            await loadNotes();
        } catch (err) {
            alert('Failed to delete note');
        }
    };

    const extractNote = async (noteId) => {
        try {
            await fetch(`${API_URL}/notes/${noteId}/extract`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                body: JSON.stringify({ extract_now: true })
            });
            alert('Extraction started!');
            await loadNotes();
        } catch (err) {
            alert('Failed to extract note');
        }
    };

    const editMetadata = (note) => {
        setEditingNote({ ...note, subject: note.subject || '', note_group: note.note_group || '' });
        setShowEditModal(true);
    };

    const changeSubject = async (note) => {
        const newSubject = prompt(`Change subject for "${note.title}"\nCurrent: ${note.subject || 'None'}\n\nEnter new subject:`, note.subject || '');
        if (newSubject !== null && newSubject.trim() !== note.subject) {
            try {
                const response = await fetch(`${API_URL}/notes/${note.id}`, {
                    method: 'PATCH',
                    headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                    body: JSON.stringify({ subject: newSubject.trim() || null })
                });
                if (response.ok) {
                    await loadNotes(); // Refresh to show updated subject
                } else {
                    alert('Failed to update subject');
                }
            } catch (err) {
                alert('Failed to update subject');
            }
        }
    };

    const changeGroup = async (note) => {
        const newGroup = prompt(`Change group for "${note.title}"\nCurrent: ${note.note_group || 'None'}\n\nEnter new group:`, note.note_group || '');
        if (newGroup !== null && newGroup.trim() !== note.note_group) {
            try {
                const response = await fetch(`${API_URL}/notes/${note.id}`, {
                    method: 'PATCH',
                    headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                    body: JSON.stringify({ note_group: newGroup.trim() || null })
                });
                if (response.ok) {
                    await loadNotes(); // Refresh to show updated group
                } else {
                    alert('Failed to update group');
                }
            } catch (err) {
                alert('Failed to update group');
            }
        }
    };

    const archiveNote = async (noteId) => {
        if (!confirm('Archive this note?')) return;
        try {
            const response = await fetch(`${API_URL}/notes/${noteId}`, {
                method: 'PATCH',
                headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                body: JSON.stringify({ archived: true })
            });
            if (response.ok) {
                await loadNotes();
            } else {
                alert('Failed to archive note');
            }
        } catch (err) {
            alert('Failed to archive note');
        }
    };

    const groupNotesByDate = (notes) => {
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        const grouped = { today: [], yesterday: [], older: [] };

        notes.forEach(note => {
            const noteDate = new Date(note.created_at);
            if (noteDate.toDateString() === today.toDateString()) {
                grouped.today.push(note);
            } else if (noteDate.toDateString() === yesterday.toDateString()) {
                grouped.yesterday.push(note);
            } else {
                grouped.older.push(note);
            }
        });
        return grouped;
    };

    if (view === 'canvas' && currentNote) {
        return <NoteCanvas note={currentNote} token={token} settings={settings} onBack={() => { setView('list'); setCurrentNote(null); loadNotes(); }} />;
    }

    const groupedNotes = groupNotesByDate(notes);
    return (
        <div style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
                <h1 style={{ fontSize: '2rem', fontWeight: '700' }}>📝 My Notes</h1>
                <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
                    <button
                        onClick={() => setShowFilters(!showFilters)}
                        className="btn btn-secondary"
                        style={{ padding: '0.75rem 1rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}
                    >
                        🔍
                        {Object.values(activeFilters).filter(Boolean).length > 0 && (
                            <span style={{
                                background: 'var(--primary)',
                                color: 'white',
                                borderRadius: '50%',
                                width: '20px',
                                height: '20px',
                                display: 'inline-flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: '0.75rem',
                                fontWeight: '600'
                            }}>
                                {Object.values(activeFilters).filter(Boolean).length}
                            </span>
                        )}
                    </button>
                    <button
                        onClick={() => setShowCreateModal(true)}
                        className="btn btn-primary"
                        style={{ padding: '0.75rem 1.5rem' }}
                    >
                        ✏️ New Note
                    </button>
                </div>
            </div>

            {/* Filter Component */}
            {showFilters && (
                <NotesSearchFilter
                    metadata={metadata}
                    activeFilters={activeFilters}
                    onFilterChange={(filters) => setActiveFilters(filters)}
                />
            )}

            {showCreateModal && (
                <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }} onClick={() => setShowCreateModal(false)}>
                    <div style={{ background: 'var(--bg-primary)', padding: '2rem', borderRadius: '12px', maxWidth: '500px', width: '90%' }} onClick={(e) => e.stopPropagation()}>
                        <h2 style={{ marginBottom: '1.5rem' }}>Create New Note</h2>
                        <div className="form-group">
                            <label className="form-label">Title *</label>
                            <input type="text" className="form-input" value={newNoteData.title} onChange={(e) => setNewNoteData({ ...newNoteData, title: e.target.value })} placeholder="Enter note title" />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Subject</label>
                            {showSubjectInput ? (
                                <div style={{ display: 'flex', gap: '0.5rem' }}>
                                    <input
                                        type="text"
                                        className="form-input"
                                        value={newSubjectInput}
                                        onChange={(e) => setNewSubjectInput(e.target.value)}
                                        placeholder="Enter new subject name"
                                        autoFocus
                                    />
                                    <button onClick={async () => {
                                        if (newSubjectInput.trim()) {
                                            try {
                                                await fetch(`${API_URL}/metadata/subjects`, {
                                                    method: 'POST',
                                                    headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                                                    body: JSON.stringify({ name: newSubjectInput.trim() })
                                                });
                                                await loadMetadata();
                                                setNewNoteData({ ...newNoteData, subject: newSubjectInput.trim() });
                                                setNewSubjectInput('');
                                                setShowSubjectInput(false);
                                            } catch (err) {
                                                alert('Failed to create subject');
                                            }
                                        }
                                    }} className="btn btn-primary" style={{ padding: '0.5rem 1rem' }}>Add</button>
                                    <button onClick={() => { setShowSubjectInput(false); setNewSubjectInput(''); }} className="btn btn-secondary" style={{ padding: '0.5rem 1rem' }}>✕</button>
                                </div>
                            ) : (
                                <select className="form-input" value={newNoteData.subject} onChange={(e) => {
                                    if (e.target.value === '__CREATE_NEW__') {
                                        setShowSubjectInput(true);
                                    } else {
                                        setNewNoteData({ ...newNoteData, subject: e.target.value });
                                    }
                                }}>
                                    <option value="">Select subject</option>
                                    {metadata.subjects.map(s => <option key={s} value={s}>{s}</option>)}
                                    <option value="__CREATE_NEW__">+ Create New Subject</option>
                                </select>
                            )}
                        </div>
                        <div className="form-group">
                            <label className="form-label">Group</label>
                            {showGroupInput ? (
                                <div style={{ display: 'flex', gap: '0.5rem' }}>
                                    <input
                                        type="text"
                                        className="form-input"
                                        value={newGroupInput}
                                        onChange={(e) => setNewGroupInput(e.target.value)}
                                        placeholder="Enter new group name"
                                        autoFocus
                                    />
                                    <button onClick={async () => {
                                        if (newGroupInput.trim()) {
                                            try {
                                                await fetch(`${API_URL}/metadata/groups`, {
                                                    method: 'POST',
                                                    headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                                                    body: JSON.stringify({ name: newGroupInput.trim() })
                                                });
                                                await loadMetadata();
                                                setNewNoteData({ ...newNoteData, note_group: newGroupInput.trim() });
                                                setNewGroupInput('');
                                                setShowGroupInput(false);
                                            } catch (err) {
                                                alert('Failed to create group');
                                            }
                                        }
                                    }} className="btn btn-primary" style={{ padding: '0.5rem 1rem' }}>Add</button>
                                    <button onClick={() => { setShowGroupInput(false); setNewGroupInput(''); }} className="btn btn-secondary" style={{ padding: '0.5rem 1rem' }}>✕</button>
                                </div>
                            ) : (
                                <select className="form-input" value={newNoteData.note_group} onChange={(e) => {
                                    if (e.target.value === '__CREATE_NEW__') {
                                        setShowGroupInput(true);
                                    } else {
                                        setNewNoteData({ ...newNoteData, note_group: e.target.value });
                                    }
                                }}>
                                    <option value="">Select group</option>
                                    {metadata.groups.map(g => <option key={g} value={g}>{g}</option>)}
                                    <option value="__CREATE_NEW__">+ Create New Group</option>
                                </select>
                            )}
                        </div>
                        <div className="form-group">
                            <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
                                <input type="checkbox" checked={newNoteData.canvas_enabled} onChange={(e) => setNewNoteData({ ...newNoteData, canvas_enabled: e.target.checked })} />
                                <span>Enable digital canvas/drawing</span>
                            </label>
                        </div>
                        <p style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '1rem' }}>* At least one of Subject, Tag, or Group is required</p>
                        <div style={{ display: 'flex', gap: '1rem' }}>
                            <button onClick={() => setShowCreateModal(false)} className="btn btn-secondary" style={{ flex: 1 }}>Cancel</button>
                            <button onClick={createNote} className="btn btn-primary" disabled={loading || !newNoteData.title} style={{ flex: 1 }}>{loading ? 'Creating...' : 'Create'}</button>
                        </div>
                    </div>
                </div>
            )}

            {groupedNotes.today.length > 0 && (
                <div style={{ marginBottom: '2rem' }}>
                    <h3 style={{ fontSize: '0.875rem', fontWeight: '600', color: 'var(--text-secondary)', marginBottom: '1rem' }}>📅 TODAY</h3>
                    {groupedNotes.today.map(note => <NoteCard key={note.id} note={note} onClick={() => openNote(note.id)} onDelete={() => deleteNote(note.id)} onExtract={() => extractNote(note.id)} onChangeSubject={() => changeSubject(note)} onChangeGroup={() => changeGroup(note)} onArchive={() => archiveNote(note.id)} />)}
                </div>
            )}
            {groupedNotes.yesterday.length > 0 && (
                <div style={{ marginBottom: '2rem' }}>
                    <h3 style={{ fontSize: '0.875rem', fontWeight: '600', color: 'var(--text-secondary)', marginBottom: '1rem' }}>📅 YESTERDAY</h3>
                    {groupedNotes.yesterday.map(note => <NoteCard key={note.id} note={note} onClick={() => openNote(note.id)} onDelete={() => deleteNote(note.id)} onExtract={() => extractNote(note.id)} onChangeSubject={() => changeSubject(note)} onChangeGroup={() => changeGroup(note)} onArchive={() => archiveNote(note.id)} />)}
                </div>
            )}
            {groupedNotes.older.length > 0 && (
                <div>
                    <h3 style={{ fontSize: '0.875rem', fontWeight: '600', color: 'var(--text-secondary)', marginBottom: '1rem' }}>📅 OLDER</h3>
                    {groupedNotes.older.map(note => <NoteCard key={note.id} note={note} onClick={() => openNote(note.id)} onDelete={() => deleteNote(note.id)} onExtract={() => extractNote(note.id)} onChangeSubject={() => changeSubject(note)} onChangeGroup={() => changeGroup(note)} onArchive={() => archiveNote(note.id)} />)}
                </div>
            )}
            {notes.length === 0 && (
                <div style={{ textAlign: 'center', padding: '4rem 2rem', color: 'var(--text-secondary)' }}>
                    <p style={{ fontSize: '1.25rem', marginBottom: '1rem' }}>No notes yet</p>
                    <p>Click "New Note" to create your first note</p>
                </div>
            )}
        </div>
    );
}

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