// ArchiveView Component
// Displays and manages archived notes

function ArchiveView({ user, token, settings }) {
    const [archivedNotes, setArchivedNotes] = useState([]);
    const [loading, setLoading] = useState(true);
    const [selectedNote, setSelectedNote] = useState(null);

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

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

    const unarchiveNote = async (noteId) => {
        if (!confirm('Unarchive 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: false })
            });
            if (response.ok) {
                await loadArchivedNotes();
            }
        } catch (err) {
            alert('Failed to unarchive note');
        }
    };

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

    const handleUpdateMetadata = async (noteId, field, value) => {
        try {
            const response = await fetch(`${API_URL}/notes/${noteId}`, {
                method: 'PATCH',
                headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                body: JSON.stringify({ [field]: value })
            });
            if (response.ok) {
                loadArchivedNotes();
            }
        } catch (err) {
            alert('Failed to update note');
        }
    };

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

    if (selectedNote) {
        return (
            <NoteCanvas
                note={selectedNote}
                token={token}
                settings={settings}
                onBack={() => { setSelectedNote(null); loadArchivedNotes(); }}
            />
        );
    }

    if (loading) {
        return <div className="loading">Loading archived notes...</div>;
    }

    return (
        <div className="fade-in">
            <h2 className="page-title">🗄️ Archived Notes</h2>

            {archivedNotes.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-state-icon">📭</div>
                    <div className="empty-state-text">No archived notes</div>
                </div>
            ) : (
                <div className="notes-grid">
                    {archivedNotes.map(note => (
                        <NoteCard
                            key={note.id}
                            note={note}
                            onClick={() => openNote(note.id)}
                            onArchive={() => unarchiveNote(note.id)}
                            onDelete={() => deleteNote(note.id)}
                            onExtract={() => alert('Please unarchive to extract content')}
                            onChangeSubject={() => {
                                const subject = prompt('New subject:', note.subject || '');
                                if (subject !== null) handleUpdateMetadata(note.id, 'subject', subject);
                            }}
                            onChangeGroup={() => {
                                const group = prompt('New group:', note.note_group || '');
                                if (group !== null) handleUpdateMetadata(note.id, 'note_group', group);
                            }}
                        />
                    ))}
                </div>
            )}
        </div>
    );
}

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