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

    // 1. INICIALIZACIÓN DE ANIMACIONES (AOS)
    // ===============================================
    AOS.init({
        duration: 800,
        once: true,
        offset: 50,
    });

    // 2. LÓGICA DEL MENÚ MÓVIL
    // ===============================================
    const openMobileMenuBtn = document.getElementById('openMobileMenu');
    const mobileMenu = document.getElementById('mobileMenu');
    const mobileMenuOverlay = document.getElementById('mobileMenuOverlay');
    const mobileMenuLinks = document.querySelectorAll('.mobile-menu-link');

    function toggleMobileMenu() {
        mobileMenu.classList.toggle('active');
        mobileMenuOverlay.classList.toggle('active');
        document.body.classList.toggle('no-scroll');
    }

    if (openMobileMenuBtn) {
        openMobileMenuBtn.addEventListener('click', toggleMobileMenu);
    }
    if (mobileMenuOverlay) {
        mobileMenuOverlay.addEventListener('click', toggleMobileMenu);
    }
    mobileMenuLinks.forEach(link => {
        link.addEventListener('click', () => {
            if (mobileMenu.classList.contains('active')) {
                toggleMobileMenu();
            }
        });
    });

    // 3. LÓGICA DEL PANEL LATERAL (MODAL DE ORACIÓN)
    // ===============================================
    const openQuoteModalDesktopBtn = document.getElementById('openQuoteModalDesktop');
    const openQuoteModalMobileBtn = document.getElementById('openQuoteModalMobile');
    const closeQuoteModalBtn = document.getElementById('closeQuoteModal');
    const quoteModal = document.getElementById('quoteModal');
    const quoteModalContent = document.getElementById('quoteModalContent');

    function openModal() {
        if (!quoteModal) return;
        quoteModal.style.display = 'flex';
        setTimeout(() => {
            quoteModalContent.style.transform = 'translateX(0)';
            document.body.classList.add('no-scroll');
        }, 10);
    }

    function closeModal() {
        if (!quoteModal) return;
        quoteModalContent.style.transform = 'translateX(100%)';
        document.body.classList.remove('no-scroll');
        setTimeout(() => {
            quoteModal.style.display = 'none';
        }, 300);
    }

    if (openQuoteModalDesktopBtn) openQuoteModalDesktopBtn.addEventListener('click', openModal);
    if (openQuoteModalMobileBtn) openQuoteModalMobileBtn.addEventListener('click', openModal);
    if (closeQuoteModalBtn) closeQuoteModalBtn.addEventListener('click', closeModal);
    if (quoteModal) {
        quoteModal.addEventListener('click', (event) => {
            if (event.target === quoteModal) {
                closeModal();
            }
        });
    }

    // 4. LÓGICA DE ENVÍO DE FORMULARIOS
    // ===============================================
    const handleFormSubmit = async (form, messageElement) => {
        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            const formData = new FormData(form);
            const submitButton = form.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.innerHTML;

            submitButton.disabled = true;
            submitButton.innerHTML = 'Enviando...';
            messageElement.classList.add('hidden');

            try {
                const response = await fetch('send_email.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                messageElement.textContent = data.message;
                messageElement.classList.remove('hidden', 'text-green-500', 'text-red-500');

                if (data.success) {
                    messageElement.classList.add('text-green-500');
                    form.reset();
                    if (form.id === 'modal-quote-form') {
                        setTimeout(closeModal, 3000);
                    }
                } else {
                    messageElement.classList.add('text-red-500');
                }
            } catch (error) {
                messageElement.textContent = 'Error de conexión. Inténtalo más tarde.';
                messageElement.classList.remove('hidden');
                messageElement.classList.add('text-red-500');
                console.error('Error:', error);
            } finally {
                submitButton.disabled = false;
                submitButton.innerHTML = originalButtonText;
            }
        });
    };

    const contactForm = document.getElementById('contact-form');
    const formMessage = document.getElementById('form-message');
    const modalQuoteForm = document.getElementById('modal-quote-form');
    const modalFormMessage = document.getElementById('modal-form-message');

    if (contactForm && formMessage) {
        handleFormSubmit(contactForm, formMessage);
    }
    if (modalQuoteForm && modalFormMessage) {
        handleFormSubmit(modalQuoteForm, modalFormMessage);
    }

    // 5. LÓGICA DEL ACORDEÓN (CORREGIDA Y UNIFICADA)
    // ===============================================
    const accordionHeaders = document.querySelectorAll('.accordion-header');

    accordionHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const content = this.nextElementSibling;
            const isActive = this.classList.contains('active');

            // Primero, cerrar todos los demás acordeones
            accordionHeaders.forEach(h => {
                if (h !== this) {
                    h.classList.remove('active');
                    h.nextElementSibling.classList.remove('active');
                    h.nextElementSibling.style.maxHeight = null;
                }
            });

            // Luego, abrir o cerrar el actual
            if (isActive) {
                this.classList.remove('active');
                content.classList.remove('active');
                content.style.maxHeight = null;
            } else {
                this.classList.add('active');
                content.classList.add('active');
                content.style.maxHeight = content.scrollHeight + "px";
            }
        });
    });

    // 6. FORMATO AUTOMÁTICO PARA NÚMERO DE TELÉFONO (IMask)
    // =====================================================
    const phoneInputs = document.querySelectorAll('input[type="tel"]');
    if (phoneInputs.length > 0) {
        const maskOptions = {
            mask: '(000) 000-0000'
        };
        phoneInputs.forEach(inputElement => {
            IMask(inputElement, maskOptions);
        });
    }

    // 7. DESPLAZAMIENTO SUAVE PARA ENLACES ANCLA
    // ===============================================
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        });
    });
});

// ========== LÓGICA PARA LA GALERÍA DE IMAGEN DESTACADA ==========

function updateMainImage(newImageSrc) {
    const mainImage = document.getElementById('main-gallery-image');
    
    // Opcional: añade un efecto de desvanecimiento para una transición suave
    mainImage.style.opacity = '0';
    
    setTimeout(() => {
        mainImage.src = newImageSrc;
        mainImage.style.opacity = '1';
    }, 300); // El tiempo debe coincidir con la duración de la transición en CSS
}