import './bootstrap';

document.documentElement.classList.add('js');

document.addEventListener('DOMContentLoaded', () => {
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (window.location.hash) {
        history.replaceState(null, document.title, window.location.pathname + window.location.search);
        window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
    }
    const form = document.querySelector('form[data-async="lead"]');
    const faqAccordion = document.querySelector('[data-accordion="faq"]');
    const languageSelects = document.querySelectorAll('[data-language-select]');
    const menuTriggers = document.querySelectorAll('[data-menu-trigger]');
    const siteMenu = document.querySelector('[data-site-menu]');
    const copyTargets = document.querySelectorAll('[data-copy-value]');
    const heroReveals = document.querySelectorAll('[data-hero-reveal]');
    const revealItems = document.querySelectorAll('[data-reveal]');

    const revealElement = (element) => {
        element.classList.add('is-visible');
    };

    if (heroReveals.length > 0) {
        requestAnimationFrame(() => {
            heroReveals.forEach((element) => revealElement(element));
        });
    }

    if (revealItems.length > 0) {
        if (prefersReducedMotion || !('IntersectionObserver' in window)) {
            revealItems.forEach((element) => revealElement(element));
        } else {
            const observer = new IntersectionObserver(
                (entries) => {
                    entries.forEach((entry) => {
                        if (!entry.isIntersecting) {
                            return;
                        }
                        revealElement(entry.target);
                        observer.unobserve(entry.target);
                    });
                },
                { threshold: 0.2, rootMargin: '0px 0px -10% 0px' }
            );

            revealItems.forEach((element) => observer.observe(element));
        }
    }

    const initFaqAccordion = () => {
        if (!faqAccordion) {
            return;
        }
        const items = faqAccordion.querySelectorAll('details');
        items.forEach((item) => {
            item.addEventListener('toggle', () => {
                if (!item.open) {
                    return;
                }
                items.forEach((other) => {
                    if (other !== item) {
                        other.open = false;
                    }
                });
            });
        });
    };

    const toggleAnimatedPanel = (panel, isOpen) => {
        if (!panel) {
            return;
        }
        if (prefersReducedMotion) {
            panel.classList.toggle('hidden', !isOpen);
            panel.classList.toggle('is-open', isOpen);
            return;
        }
        if (isOpen) {
            panel.classList.remove('hidden');
            requestAnimationFrame(() => {
                panel.classList.add('is-open');
            });
            return;
        }
        panel.classList.remove('is-open');
        const onEnd = () => {
            panel.classList.add('hidden');
            panel.removeEventListener('transitionend', onEnd);
        };
        panel.addEventListener('transitionend', onEnd);
        setTimeout(() => {
            if (!panel.classList.contains('is-open')) {
                panel.classList.add('hidden');
                panel.removeEventListener('transitionend', onEnd);
            }
        }, 260);
    };

    initFaqAccordion();
    if (languageSelects.length > 0) {
        languageSelects.forEach((languageSelect) => {
            const trigger = languageSelect.querySelector('[data-language-trigger]');
            const menu = languageSelect.querySelector('[data-language-menu]');
            const options = languageSelect.querySelectorAll('[data-language-option]');

            if (!trigger || !menu) {
                return;
            }

            const closeMenu = () => {
                toggleAnimatedPanel(menu, false);
                trigger.setAttribute('aria-expanded', 'false');
            };

            const openMenu = () => {
                toggleAnimatedPanel(menu, true);
                trigger.setAttribute('aria-expanded', 'true');
            };

            trigger.addEventListener('click', () => {
                if (menu.classList.contains('hidden')) {
                    openMenu();
                } else {
                    closeMenu();
                }
            });

            options.forEach((option) => {
                option.addEventListener('click', () => {
                    closeMenu();
                });
            });

            document.addEventListener('click', (event) => {
                if (!languageSelect.contains(event.target)) {
                    closeMenu();
                }
            });
        });
    }

    if (siteMenu && menuTriggers.length > 0) {
        const menuLinks = siteMenu.querySelectorAll('[data-menu-link]');
        const activeClasses = ['border-emerald-500', 'text-emerald-700', 'bg-emerald-50'];

        const setActiveLink = (hash) => {
            if (!hash) {
                return;
            }
            menuLinks.forEach((link) => {
                link.classList.remove(...activeClasses);
            });
            const activeLink = Array.from(menuLinks).find((link) => link.getAttribute('href') === hash);
            if (activeLink) {
                activeLink.classList.add(...activeClasses);
            }
        };

        const setMenuOpen = (isOpen) => {
            toggleAnimatedPanel(siteMenu, isOpen);
            menuTriggers.forEach((trigger) => {
                trigger.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
            });
        };

        menuTriggers.forEach((trigger) => {
            trigger.addEventListener('click', () => {
                const isHidden = siteMenu.classList.contains('hidden');
                setMenuOpen(isHidden);
            });
        });

        menuLinks.forEach((link) => {
            link.addEventListener('click', () => {
                setActiveLink(link.getAttribute('href'));
                setMenuOpen(false);
            });
        });

        setActiveLink(window.location.hash);
        window.addEventListener('hashchange', () => {
            setActiveLink(window.location.hash);
        });

        document.addEventListener('click', (event) => {
            if (!siteMenu.contains(event.target) && !Array.from(menuTriggers).some((trigger) => trigger.contains(event.target))) {
                setMenuOpen(false);
            }
        });
    }

    if (copyTargets.length > 0) {
        const copyText = async (value) => {
            if (navigator.clipboard && window.isSecureContext) {
                await navigator.clipboard.writeText(value);
                return;
            }
            const temp = document.createElement('textarea');
            temp.value = value;
            temp.setAttribute('readonly', '');
            temp.style.position = 'absolute';
            temp.style.left = '-9999px';
            document.body.appendChild(temp);
            temp.select();
            document.execCommand('copy');
            document.body.removeChild(temp);
        };

        copyTargets.forEach((target) => {
            target.addEventListener('click', async () => {
                const value = target.getAttribute('data-copy-value');
                if (!value) {
                    return;
                }
                try {
                    await copyText(value);
                } catch (error) {
                    // No-op: copy failure should not block UI.
                }
            });
        });
    }

    if (!form) {
        return;
    }

    const successBox = form.querySelector('[data-success]');
    const errorSummary = form.querySelector('[data-error-summary]');
    const submitButton = form.querySelector('[data-submit]');
    const errorFields = form.querySelectorAll('[data-error-for]');
    const phoneInput = form.querySelector('#phone');
    const codFiscalInput = form.querySelector('#cod_fiscal');
    const successDefault = form.dataset.successDefault;
    const errorDefault = form.dataset.errorDefault;

    const clearErrors = () => {
        errorSummary.classList.add('hidden');
        errorFields.forEach((field) => {
            field.classList.add('hidden');
            field.textContent = '';
        });
    };

    const showError = (name, message) => {
        const field = form.querySelector(`[data-error-for="${name}"]`);
        if (!field) {
            return;
        }
        field.textContent = message;
        field.classList.remove('hidden');
    };

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

        if (submitButton) {
            submitButton.disabled = true;
        }

        if (successBox) {
            successBox.classList.add('hidden');
            successBox.textContent = '';
        }

        clearErrors();

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                },
                body: new FormData(form),
            });

            if (response.ok) {
                const data = await response.json();
                const redirectUrl = data.redirect || data.redirect_url;

                if (redirectUrl) {
                    window.location.assign(redirectUrl);
                    return;
                }

                if (successBox) {
                    successBox.textContent = data.message ?? successDefault ?? '';
                    successBox.classList.remove('hidden');
                }

                form.reset();
                return;
            }

            if (response.status === 422) {
                const data = await response.json();
                errorSummary.classList.remove('hidden');

                Object.entries(data.errors || {}).forEach(([name, messages]) => {
                    showError(name, messages[0] ?? errorDefault ?? '');
                });

                return;
            }

            errorSummary.classList.remove('hidden');
        } catch (error) {
            errorSummary.classList.remove('hidden');
        } finally {
            if (submitButton) {
                submitButton.disabled = false;
            }
        }
    });

    if (phoneInput) {
        phoneInput.addEventListener('input', (event) => {
            const rawValue = event.target.value;
            const cleaned = rawValue.replace(/(?!^\+)[^0-9]/g, '').replace(/^\+{2,}/, '+');
            if (cleaned !== rawValue) {
                event.target.value = cleaned;
            }
        });
    }

    if (codFiscalInput) {
        codFiscalInput.addEventListener('input', (event) => {
            const rawValue = event.target.value;
            const cleaned = rawValue.replace(/\D/g, '').slice(0, 13);
            if (cleaned !== rawValue) {
                event.target.value = cleaned;
            }
        });
    }

});
