const faqs = document.querySelectorAll('.faq-question');
faqs.forEach(faq => {
    faq.addEventListener('click', () => toggleFaq(faq));
    faq.addEventListener('keydown', e => {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            toggleFaq(faq);
        }
    });
});

function toggleFaq(faq) {
    const parent = faq.parentElement;
    const expanded = faq.getAttribute('aria-expanded') === 'true';
    faq.setAttribute('aria-expanded', String(!expanded));
    const answer = parent.querySelector('.faq-answer');
    answer.style.display = expanded ? 'none' : 'block';
    answer.setAttribute('aria-hidden', String(expanded));
    parent.classList.toggle('open');
}



let dataSaved = false;

// Debounce utility
function debounce(fn, delay) {
    let timer = null;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
}

// Auto‑save on mobile input keyup
$('input[name="user_mobile"]').on('keyup', debounce(function () {
    const user_name = $('#user_name').val().trim();
    const user_age = $('#user_age').val().trim();
    const user_weight = $('#bodyweight').val().trim();
    const user_mobile = $('#phone').val().trim();
    const selectedGoals = $('input[name="goal[]"]:checked').map(function () {
        return $(this).val();
    }).get();

    if (/^[0-9]{10}$/.test(user_mobile) && user_name.length >= 3) {
        const formData = {
            onchangesavedata: true,
            name: user_name,
            phone: user_mobile,
            age: user_age,
            weight: user_weight,
            goal: selectedGoals
        };

        $.ajax({
            url: 'savedata.php',
            method: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(formData),
            success: function (response) {
                if (response.status === 'error') {
                    console.error('Auto-save error:', response.message);
                    dataSaved = false;
                } else {
                    console.log('Auto‑saved successfully.');
                    dataSaved = true;
                }
            },
            error: function (xhr, status, error) {
                console.error('Auto‑save XHR error:', error);
                dataSaved = false;
            }
        });
    }
}, 1000));

// Submission handler
$('#leadForm').on('submit', function (e) {
    e.preventDefault();

    const user_name = $('#user_name').val().trim();
    const user_age = $('#user_age').val().trim();
    const user_weight = $('#bodyweight').val().trim();
    const user_mobile = $('#phone').val().trim();
    const submitBtn = $('#submitBtn');
    const selectedGoals = $('input[name="goal[]"]:checked').map(function () {
        return $(this).val();
    }).get();

    if (!/^[0-9]{10}$/.test(user_mobile)) {
        alert('Please enter a valid 10-digit phone number.');
        return;
    }
    if (user_name.length < 3) {
        alert('Name must be at least 3 characters long.');
        return;
    }

    if (dataSaved) {
        window.location.href = 'thanks.html';
        return false;
    }

    submitBtn.prop('disabled', true).text('Please wait...');

    const formData = {
        submitenquery: true,
        name: user_name,
        phone: user_mobile,
        age: user_age,
        weight: user_weight,
        goal: selectedGoals
    };

    $.ajax({
        url: 'savedata.php',
        method: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(formData),
        success: function (response) {
            if (response.status === 'success') {
                window.location.href = 'thanks.html';
            } else {
                alert('Submission failed: ' + response.message);
            }
            console.log('Form submission result:', response);
        },
        error: function (xhr, status, error) {
            console.error('Form submission XHR error:', xhr.responseText);
            alert('There was an error submitting your form. Please try again later.');
        },
        complete: function () {
            submitBtn.prop('disabled', false).text('Submit');
        }
    });
});
