document.addEventListener('DOMContentLoaded', () => {

    document.querySelectorAll('[data-note-id]').forEach(button => {
        button.addEventListener('click', () => {
            const noteId = button.getAttribute('data-note-id');
            if (noteId) {
                window.location.href = `/notes/${noteId}`;
            }
        });
    });

    let formToDelete = null;

    function setupDeleteButtons() {
        document.querySelectorAll('.show-delete-modal').forEach(button => {
            button.addEventListener('click', function() {
                formToDelete = this.closest('form');
                const title = this.dataset.title || '';
                document.getElementById('noteToDeleteTitle').textContent = title;
                new bootstrap.Modal(document.getElementById('deleteNoteModal')).show();
            });
        });
    }

    // Función para limpiar HTML y obtener solo texto plano
    function stripHtml(html) {
        let tmp = document.createElement("DIV");
        tmp.innerHTML = html;
        return tmp.textContent || tmp.innerText || "";
    }

    // Función centralizada para abrir el modal con contenido HTML y configurar editor + guardado + cierre
    function openNoteModalWithContent(html) {
        document.getElementById('noteContent').innerHTML = html;

        const viewNoteModal = new bootstrap.Modal(document.getElementById('viewNoteModal'));
        viewNoteModal.show();

        document.body.style.overflow = '';
        document.body.style.paddingRight = '';

        destroyEditor();
        ckeditor();
        let originalContent = CKEDITOR.instances.editor1.getData();

        // Asumo que el título está en un input con id 'noteTitle' dentro del modal
        const titleInput = document.getElementById('noteTitle');
        let originalTitle = titleInput ? titleInput.value : '';

        const modalEl = document.getElementById('viewNoteModal');
        modalEl.removeEventListener('hide.bs.modal', modalEl.handleModalClose);

        modalEl.handleModalClose = function(e) {
            const currentContent = CKEDITOR.instances.editor1.getData();
            const currentTitle = titleInput ? titleInput.value : '';

            if (
                stripHtml(currentContent).trim() !== stripHtml(originalContent).trim() ||
                currentTitle.trim() !== originalTitle.trim()
            ) {
                e.preventDefault();
                Swal.fire({
                    title: 'Tienes cambios sin guardar',
                    text: "¿Seguro que quieres cerrar el editor sin guardar?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Sí, cerrar',
                    cancelButtonText: 'No, seguir editando',
                    reverseButtons: true,
                    didOpen: () => { document.body.style.paddingRight = ''; }
                }).then(result => {
                    if (result.isConfirmed) {
                        modalEl.removeEventListener('hide.bs.modal', modalEl.handleModalClose);
                        bootstrap.Modal.getInstance(modalEl).hide();
                    }
                });
            }
        };
        modalEl.addEventListener('hide.bs.modal', modalEl.handleModalClose);

        // Configurar botón guardar
        const form = document.getElementById('noteForm');
        const saveButton = document.getElementById('saveNoteBtn');

        if (form && saveButton && !saveButton.dataset.bound) {
            saveButton.addEventListener('click', () => {
                const content = CKEDITOR.instances.editor1.getData();
                const formData = new FormData(form);
                formData.set('content', content);

                fetch(form.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-HTTP-Method-Override': 'PUT',
                            'Accept': 'application/json'
                        }
                    })
                    .then(response => {
                        if (!response.ok) return response.json().then(err => { throw err; });
                        return response.json();
                    })
                    .then(data => {
                        originalContent = CKEDITOR.instances.editor1.getData();
                        originalTitle = titleInput ? titleInput.value : '';

                        const alert = document.createElement('div');
                        alert.className = 'alert alert-success alert-dismissible fade show';
                        alert.innerHTML = `
                        ${data.message}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    `;

                        const existingAlerts = form.querySelectorAll('.alert');
                        existingAlerts.forEach(a => a.remove());

                        form.insertBefore(alert, form.firstChild);

                        setTimeout(() => {
                            alert.classList.remove('show');
                            setTimeout(() => alert.remove(), 150);
                        }, 2000);
                    })
                    .catch(error => {
                        const alert = document.createElement('div');
                        alert.className = 'alert alert-danger alert-dismissible fade show';
                        alert.innerHTML = `
                        ${error?.message || 'Error al actualizar la nota'}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    `;

                        const existingAlerts = form.querySelectorAll('.alert');
                        existingAlerts.forEach(a => a.remove());

                        form.insertBefore(alert, form.firstChild);

                        setTimeout(() => {
                            alert.classList.remove('show');
                            setTimeout(() => alert.remove(), 150);
                        }, 2000);
                    });
            });
            saveButton.dataset.bound = true;
        }
    }

    function setupContentButtons() {
        const createNoteForm = document.getElementById('createNoteForm2');
        const notasContainer = document.getElementById('notasContainer');

        if (createNoteForm) {
            const card = createNoteForm.querySelector('.card');
            if (card) {
                card.addEventListener('click', (e) => {
                    e.stopPropagation();
                    e.preventDefault();

                    // Cerrar sidebar
                    if (notasContainer) {
                        notasContainer.classList.remove('active');
                    }

                    const url = createNoteForm.action || '/notes/create';
                    const token = createNoteForm.querySelector('input[name="_token"]').value;

                    fetch(url, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': token,
                                'X-Requested-With': 'XMLHttpRequest',
                                'Accept': 'application/json',
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({})
                        })
                        .then(response => {
                            if (!response.ok) throw new Error('Error al crear la nota');
                            return response.json();
                        })
                        .then(data => {
                            if (data.note && data.note.id) {
                                const noteId = data.note.id;
                                const contentUrl = `/notes/${noteId}/content`;

                                fetch(contentUrl)
                                    .then(res => res.text())
                                    .then(html => {
                                        openNoteModalWithContent(html);
                                    })
                                    .catch(() => alert('No se pudo cargar el contenido de la nota.'));
                            } else {
                                console.log('Nota creada, pero sin ID');
                            }
                        })
                        .catch(() => alert('No se pudo crear la nota.'));
                });
            }
        }

        document.querySelectorAll('.view-note-details').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const noteId = this.getAttribute('data-note-id');
                const url = `/notes/${noteId}/content`;
                const notasContainer = document.getElementById('notasContainer');

                if (notasContainer.classList.contains('active')) {
                    notasContainer.classList.remove('active');
                    notasContainer.querySelector('#notesContent').innerHTML = '';
                }

                fetch(url)
                    .then(res => res.text())
                    .then(html => {
                        openNoteModalWithContent(html);
                    })
                    .catch(() => console.error('Error cargando la nota'));
            });
        });
    }

    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    if (confirmDeleteBtn) {
        confirmDeleteBtn.addEventListener('click', () => {
            if (formToDelete) formToDelete.submit();
        });
    }

    const toggleNotesBtn = document.getElementById('quickNotes-button');
    if (toggleNotesBtn) {
        toggleNotesBtn.addEventListener('click', e => {
            e.preventDefault();

            const notasContainer = document.getElementById('notasContainer');

            if (notasContainer.classList.contains('active')) {
                notasContainer.classList.remove('active');
                notasContainer.querySelector('#notesContent').innerHTML = '';
                return;
            }

            fetch(window.NOTES_FETCH_ROUTE)
                .then(res => res.text())
                .then(html => {
                    notasContainer.querySelector('#notesContent').innerHTML = html;
                    notasContainer.classList.add('active');
                    setupDeleteButtons();
                    setupContentButtons();
                })
                .catch(err => console.error('Error cargando las notas:', err));
        });
    }

    const closeNotesBtn = document.querySelector('.notes-sidebar .btn');
    if (closeNotesBtn) {
        closeNotesBtn.addEventListener('click', () => {
            const notasContainer = document.getElementById('notasContainer');
            notasContainer.classList.remove('active');
            notasContainer.querySelector('#notesContent').innerHTML = '';
        });
    }

    function ckeditor() {
        CKEDITOR.replace('editor1', {
            height: 200,
            toolbar: [
                { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'] },
                { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'] },
                { name: 'insert', items: ['Link', 'Image', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar'] },
                { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
                { name: 'colors', items: ['TextColor', 'BGColor'] },
                { name: 'tools', items: ['Maximize'] },
                { name: 'editing', items: ['Scayt'] }
            ]
        });


    }


    const modal = document.querySelector('#viewNoteModal .modal-dialog');
    const header = document.querySelector('#viewNoteModal .modal-header');

    let isDragging = false;
    let offsetX, offsetY;

    header.style.cursor = 'move';

    header.addEventListener('mousedown', function(e) {
        const rect = modal.getBoundingClientRect();

        if (getComputedStyle(modal).position !== 'absolute') {
            modal.style.position = 'absolute';
            modal.style.top = rect.top + window.scrollY + 'px';
            modal.style.left = rect.left + window.scrollX + 'px';
            modal.style.margin = '0';
        }

        isDragging = true;
        offsetX = e.clientX - rect.left;
        offsetY = e.clientY - rect.top;
    });

    document.addEventListener('mousemove', function(e) {
        if (isDragging) {
            const newLeft = e.clientX - offsetX;
            const newTop = e.clientY - offsetY;

            // Limites máximos
            const maxLeft = window.innerWidth - modal.offsetWidth;
            const maxTop = window.innerHeight - modal.offsetHeight;

            // Clamp para evitar que se salga de pantalla
            const clampedLeft = Math.max(0, Math.min(newLeft, maxLeft));
            const clampedTop = Math.max(0, Math.min(newTop, maxTop));

            modal.style.left = clampedLeft + 'px';
            modal.style.top = clampedTop + 'px';
        }
    });

    document.addEventListener('mouseup', function() {
        isDragging = false;
    });

    function destroyEditor() {
        if (CKEDITOR.instances.editor1) {
            CKEDITOR.instances.editor1.destroy(true);
        }
    }


});