/**
 * Logica Applicativa Coulibaly Siaka - Funnel Strategist Edition
 * Autore: Senior Frontend Engineer
 */

const FORMSPREE_ENDPOINT = "https://formspree.io/f/mbdkjjlr";
const EBOOK_URL = "https://drive.google.com/file/d/1Ug8eGGx_ekhIoA54Kyf6IW8afmiNq401/view?usp=drive_link";

document.addEventListener('DOMContentLoaded', () => {
    // Inizializzazione moduli
    setupNewsletter();
    setupEbookFlow();
    setupDiagnosisModal();
});

/**
 * NEWSLETTER: Invio AJAX
 */
function setupNewsletter() {
    const form = document.getElementById('newsletter-form') as HTMLFormElement;
    const initial = document.getElementById('newsletter-initial-view');
    const success = document.getElementById('newsletter-success-view');

    if (!form) return;

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const btn = form.querySelector('button') as HTMLButtonElement;
        const nameInput = document.getElementById('nl-name') as HTMLInputElement;
        const emailInput = document.getElementById('nl-email') as HTMLInputElement;

        try {
            btn.disabled = true;
            btn.innerText = "Inviando...";
            await submitToFormspree({ 
                subject: `Iscrizione Newsletter - ${nameInput.value}`, 
                name: nameInput.value, 
                email: emailInput.value 
            });
            if (initial) initial.style.display = 'none';
            if (success) success.style.display = 'block';
            const userDisplay = document.getElementById('nl-user-name');
            if (userDisplay) userDisplay.innerText = nameInput.value.split(' ')[0].toUpperCase();
        } catch (err) {
            alert("Errore invio.");
            btn.disabled = false;
            btn.innerText = "Unisciti alla Newsletter";
        }
    });
}

/**
 * EBOOK FLOW: Lead Magnet
 */
function setupEbookFlow() {
    const showBtn = document.getElementById('show-prompt-form');
    const formContainer = document.getElementById('prompt-form-container');
    const initialView = document.getElementById('prompt-initial-view');
    const successView = document.getElementById('prompt-success-view');

    showBtn?.addEventListener('click', () => {
        if (initialView) initialView.style.display = 'none';
        if (formContainer) formContainer.style.display = 'block';
    });

    const pbForm = document.getElementById('prompt-book-form') as HTMLFormElement;
    pbForm?.addEventListener('submit', async (e) => {
        e.preventDefault();
        const btn = pbForm.querySelector('button') as HTMLButtonElement;
        const name = (document.getElementById('pb-name') as HTMLInputElement).value;
        const email = (document.getElementById('pb-email') as HTMLInputElement).value;
        const phone = (document.getElementById('pb-phone') as HTMLInputElement).value;

        try {
            btn.disabled = true;
            await submitToFormspree({ subject: `Richiesta Ebook SEO - ${name}`, name, email, phone });
            if (formContainer) formContainer.style.display = 'none';
            if (successView) successView.style.display = 'block';
            const userDisplay = document.getElementById('user-display-name');
            if (userDisplay) userDisplay.innerText = name.split(' ')[0].toUpperCase();
            setTimeout(() => window.open(EBOOK_URL, '_blank'), 1000);
        } catch (err) {
            alert("Errore nell'invio dei dati.");
            btn.disabled = false;
        }
    });
}

/**
 * DIAGNOSIS MODAL: 4 Step Master Flow
 */
function setupDiagnosisModal() {
    const modal = document.getElementById('diagnosis-modal');
    const openBtn = document.getElementById('btn-scale-diagnosis');
    const closeBtn = document.getElementById('close-modal');
    const closeSuccess = document.getElementById('close-modal-success');
    const form = document.getElementById('diagnosis-form') as HTMLFormElement;
    const steps = document.querySelectorAll('.modal-step');
    const dots = document.querySelectorAll('.dot');
    let currentStepIndex = 0;

    // Inizializzazione Telefono (intl-tel-input)
    const phoneInput = document.getElementById('diag_phone');
    let iti: any;
    if (phoneInput && (window as any).intlTelInput) {
        iti = (window as any).intlTelInput(phoneInput, {
            initialCountry: "it",
            separateDialCode: true,
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
        });
    }

    openBtn?.addEventListener('click', () => {
        if (modal) modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    });

    const close = () => {
        if (modal) modal.style.display = 'none';
        document.body.style.overflow = 'auto';
        resetModal();
    };

    function resetModal() {
        steps.forEach((s, idx) => {
            s.classList.toggle('active', idx === 0);
        });
        dots.forEach((d, idx) => {
            d.classList.toggle('active', idx === 0);
        });
        currentStepIndex = 0;
        if (form) {
            form.reset();
            form.style.display = 'block';
        }
        const success = document.getElementById('diagnosis-success');
        if (success) success.style.display = 'none';
        const indicators = document.querySelector('.step-indicator');
        if (indicators) (indicators as HTMLElement).style.display = 'flex';
    }

    closeBtn?.addEventListener('click', close);
    closeSuccess?.addEventListener('click', close);

    // Navigazione Step
    document.querySelectorAll('.next-step').forEach(btn => {
        btn.addEventListener('click', () => {
            const currentStep = steps[currentStepIndex];
            const inputs = currentStep.querySelectorAll('input, select, textarea') as NodeListOf<HTMLInputElement>;
            let isValid = true;
            
            inputs.forEach(input => {
                if (!input.checkValidity()) {
                    input.reportValidity();
                    isValid = false;
                }
            });

            if (isValid && currentStepIndex < steps.length - 1) {
                steps[currentStepIndex].classList.remove('active');
                dots[currentStepIndex].classList.remove('active');
                currentStepIndex++;
                steps[currentStepIndex].classList.add('active');
                dots[currentStepIndex].classList.add('active');
                
                // UX: Ritorna in cima al modal
                const content = document.querySelector('.modal-content');
                if (content) content.scrollTop = 0;
            }
        });
    });

    // Submit Finale
    form?.addEventListener('submit', async (e) => {
        e.preventDefault();
        const btn = document.getElementById('submit-diagnosis') as HTMLButtonElement;
        const formData = new FormData(form);
        const payload: any = {};
        
        formData.forEach((value, key) => {
            payload[key] = value;
        });
        
        // Formatta il telefono se disponibile
        if (iti) {
            payload.phone_whatsapp = iti.getNumber();
        }

        payload._subject = `CANDIDATURA MASTER FLOW: ${payload.business_name} - ${payload.full_name}`;

        try {
            btn.disabled = true;
            btn.innerText = "Elaborando i dati...";
            await submitToFormspree(payload);
            form.style.display = 'none';
            const success = document.getElementById('diagnosis-success');
            if (success) success.style.display = 'block';
            const indicators = document.querySelector('.step-indicator');
            if (indicators) (indicators as HTMLElement).style.display = 'none';
        } catch (err) {
            alert("Errore nell'invio della candidatura. Riprova più tardi.");
            btn.disabled = false;
            btn.innerText = "CANDIDATI PER L'ANALISI DI SCALABILITÀ";
        }
    });
}

/**
 * UTILITY: Formspree Fetch
 */
async function submitToFormspree(data: any) {
    const response = await fetch(FORMSPREE_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(data)
    });
    if (!response.ok) throw new Error("Fetch failed");
    return await response.json();
}