import './bootstrap';

import Alpine from 'alpinejs';
import { maskPhone, maskCNPJ, maskCPF, maskCEP, maskCurrencyBRL, parseCurrencyBRL, fetchCEP, initMasks } from './masks';

// Expose for Alpine inline use
window.maskPhone       = maskPhone;
window.maskCNPJ        = maskCNPJ;
window.maskCPF         = maskCPF;
window.maskCEP         = maskCEP;
window.maskCurrencyBRL = maskCurrencyBRL;
window.parseCurrencyBRL = parseCurrencyBRL;
window.fetchCEP        = fetchCEP;

window.Alpine = Alpine;

document.addEventListener('alpine:init', () => {

    Alpine.data('mobileMenu', () => ({
        open: false,
        toggle() { this.open = !this.open; },
        close() { this.open = false; },
    }));

    Alpine.data('tabs', (initial = 0) => ({
        active: initial,
        setTab(i) { this.active = i; },
        isActive(i) { return this.active === i; },
    }));

    Alpine.data('contactForm', () => ({
        form: { name: '', email: '', phone: '', company: '', message: '' },
        loading: false,
        success: false,
        error: false,
        async submit() {
            this.loading = true;
            this.error = false;
            try {
                const res = await fetch('/contato', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify(this.form),
                });
                if (!res.ok) throw new Error();
                this.success = true;
            } catch {
                this.error = true;
            } finally {
                this.loading = false;
            }
        },
    }));

});

// Scroll reveal (including directional variants)
document.addEventListener('DOMContentLoaded', () => {
    const observer = new IntersectionObserver(
        entries => entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('visible'); } }),
        { threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
    );
    document.querySelectorAll('.reveal, .reveal-right, .reveal-left').forEach(el => observer.observe(el));

    // Bind data-mask attributes
    initMasks();

    // Counter animation
    document.querySelectorAll('[data-counter]').forEach(el => {
        const io = new IntersectionObserver(([entry]) => {
            if (!entry.isIntersecting) return;
            const target = parseInt(el.dataset.counter, 10);
            const suffix = el.dataset.suffix || '';
            const duration = 1800;
            let start = null;
            const step = ts => {
                if (!start) start = ts;
                const progress = Math.min((ts - start) / duration, 1);
                el.textContent = Math.floor(progress * target) + suffix;
                if (progress < 1) requestAnimationFrame(step);
            };
            requestAnimationFrame(step);
            io.disconnect();
        }, { threshold: 0.5 });
        io.observe(el);
    });
});

Alpine.start();
