import './bootstrap';

import Alpine from 'alpinejs';

document.addEventListener('alpine:init', () => {
    Alpine.data('siteShell', () => ({
        mobileMenuOpen: false,
        headerScrolled: false,

        init() {
            const syncHeader = () => {
                this.headerScrolled = window.scrollY > 16;
            };

            syncHeader();
            window.addEventListener('scroll', syncHeader, { passive: true });
            this.bindContactForms();
        },

        bindContactForms() {
            document.querySelectorAll('[data-contact-form]').forEach((form) => {
                if (form.dataset.bound === 'true') {
                    return;
                }

                form.dataset.bound = 'true';

                form.addEventListener('submit', (event) => {
                    const siteKey = form.dataset.recaptchaSiteKey;
                    const tokenField = form.querySelector('input[name="g-recaptcha-response"]');

                    if (!siteKey || !window.grecaptcha || !tokenField) {
                        return;
                    }

                    if (form.dataset.recaptchaVerified === 'true') {
                        form.dataset.recaptchaVerified = 'false';
                        return;
                    }

                    event.preventDefault();

                    window.grecaptcha.ready(() => {
                        window.grecaptcha.execute(siteKey, { action: 'submit' }).then((token) => {
                            tokenField.value = token;
                            form.dataset.recaptchaVerified = 'true';
                            form.requestSubmit();
                        });
                    });
                });
            });
        },
    }));
});

window.Alpine = Alpine;
Alpine.start();
