/* scripts.js */
document.addEventListener('DOMContentLoaded', () => {
    const flyout     = document.getElementById('contact-flyout');
    const closeBtn   = document.getElementById('closeFlyout');
    const form       = document.getElementById('contactForm');
    const contactNav = document.getElementById('ContactMenu');
    const submitBtn  = form.querySelector('.submit-btn');
    const btnText    = submitBtn.querySelector('.btn-text');
    const btnSpinner = submitBtn.querySelector('.btn-spinner');

    const modal      = document.getElementById('formModal');
    const modalMsg   = document.getElementById('formModalMessage');

    closeBtn.addEventListener('click', () => {
        flyout.style.display = 'none';
    });

    form.addEventListener('submit', e => {
        e.preventDefault();

        btnText.style.display = 'none';
        btnSpinner.style.display = 'inline-block';

        flyout.classList.add('wiggle');
        setTimeout(() => flyout.classList.remove('wiggle'), 600);

        const formData = new FormData(form);

        fetch(form.action, {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(result => {
                if (result.trim() === "OK") {
                    form.reset();
                    showModal("✅ Thanks! We’ll be in touch shortly.");
                } else {
                    showModal("❌ Error: " + result);
                }
            })
            .catch(() => {
                showModal("❌ Failed to send message. Please try again.");
            })
            .finally(() => {
                btnText.style.display = 'inline';
                btnSpinner.style.display = 'none';
            });
    });

    function showModal(message) {
        modalMsg.textContent = message;
        modal.classList.remove('hidden');
        setTimeout(() => {
            modal.classList.add('hidden');
        }, 4000);
    }

    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({ behavior: 'smooth' });
            }
        });
    });

    contactNav.addEventListener('click', (e) => {
        e.preventDefault();

        if (flyout.style.display === 'none' || flyout.style.display === '') {
            flyout.style.display = 'block';
        } else {
            flyout.classList.remove('wiggle');
            void flyout.offsetWidth;
            flyout.classList.add('wiggle');
        }
    });
});
