document.addEventListener('DOMContentLoaded', () => {
    let currentNoteId = null;
    let isEditing = false;

    const notesList = document.getElementById('notes-list');
    const noteTitle = document.getElementById('note-title');
    const noteContent = document.getElementById('note-content');
    const saveNoteBtn = document.getElementById('save-note');
    const deleteNoteBtn = document.getElementById('delete-note');
    const newNoteBtn = document.getElementById('new-note');

    async function loadNotes(search = '') {
        try {
            const response = await fetch(`notes/get_notes.php${search ? `?search=${encodeURIComponent(search)}` : ''}`);
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            notesList.innerHTML = data.notes.map(note => `
                <div class="note-item p-4 border-b border-gray-200 dark:border-gray-700 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors ${note.id === currentNoteId ? 'bg-gray-50 dark:bg-gray-700' : ''}"
                     data-note-id="${note.id}">
                    <div class="flex justify-between items-start">
                        <h3 class="font-medium">${note.title || 'Untitled'}</h3>
                        <span class="text-xs text-gray-500">${formatDate(note.updated_at)}</span>
                    </div>
                    <p class="text-sm text-gray-600 dark:text-gray-400 mt-1 line-clamp-2">
                        ${note.content}
                    </p>
                </div>
            `).join('');
            
            attachNoteListeners();
            
        } catch (error) {
            showNotification(error.message, 'error');
        }
    }

    async function loadNoteDetails(noteId) {
        try {
            const response = await fetch(`notes/get_notes.php?id=${noteId}`);
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            currentNoteId = noteId;
            noteTitle.value = data.note.title;
            noteContent.value = data.note.content;
            
            toggleEditMode(true);
            highlightSelectedNote();
            
        } catch (error) {
            showNotification(error.message, 'error');
        }
    }

    async function saveNote() {
        try {
            const title = noteTitle.value.trim();
            const content = noteContent.value.trim();
            
            if (!title && !content) {
                throw new Error('Note cannot be empty');
            }

            const endpoint = currentNoteId ? 'update_note.php' : 'create_note.php';
            const noteData = {
                title,
                content
            };

            if (currentNoteId) {
                noteData.id = currentNoteId;
            }

            const response = await fetch(`notes/${endpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(noteData)
            });

            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            showNotification(currentNoteId ? 'Note updated successfully' : 'Note created successfully', 'success');
            
            currentNoteId = data.note.id;
            await loadNotes();
            highlightSelectedNote();
            
        } catch (error) {
            showNotification(error.message, 'error');
        }
    }

    async function deleteNote() {
        if (!currentNoteId) return;
        
        if (!confirm('Are you sure you want to delete this note?')) return;
        
        try {
            const response = await fetch('notes/delete_note.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: currentNoteId
                })
            });

            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            showNotification('Note deleted successfully', 'success');
            
            currentNoteId = null;
            noteTitle.value = '';
            noteContent.value = '';
            toggleEditMode(false);
            await loadNotes();
            
        } catch (error) {
            showNotification(error.message, 'error');
        }
    }

    function createNewNote() {
        currentNoteId = null;
        noteTitle.value = '';
        noteContent.value = '';
        toggleEditMode(true);
        noteTitle.focus();
    }

    function toggleEditMode(enabled) {
        isEditing = enabled;
        noteTitle.disabled = !enabled;
        noteContent.disabled = !enabled;
        saveNoteBtn.classList.toggle('hidden', !enabled);
        deleteNoteBtn.classList.toggle('hidden', !currentNoteId || !enabled);
    }

    function highlightSelectedNote() {
        document.querySelectorAll('.note-item').forEach(item => {
            item.classList.toggle('bg-gray-50', item.dataset.noteId === currentNoteId);
            item.classList.toggle('dark:bg-gray-700', item.dataset.noteId === currentNoteId);
        });
    }

    function attachNoteListeners() {
        document.querySelectorAll('.note-item').forEach(item => {
            item.addEventListener('click', () => {
                loadNoteDetails(item.dataset.noteId);
            });
        });
    }

    function showNotification(message, type = 'success') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500' : 'bg-red-500'
        } text-white`;
        notification.textContent = message;
        document.body.appendChild(notification);
        setTimeout(() => notification.remove(), 3000);
    }

    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('fr-FR', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // Event Listeners
    newNoteBtn.addEventListener('click', createNewNote);
    saveNoteBtn.addEventListener('click', saveNote);
    deleteNoteBtn.addEventListener('click', deleteNote);

    noteContent.addEventListener('keydown', (e) => {
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            saveNote();
        }
    });

    // Search functionality
    const searchInput = document.querySelector('input[placeholder="Search notes..."]');
    let searchTimeout;
    searchInput.addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            loadNotes(e.target.value);
        }, 300);
    });

    // Initialize
    loadNotes();
});