(function() {
    // Read data injected from template
    var dataEl = document.getElementById('data-hosted-form');
    var submitText = dataEl ? JSON.parse(dataEl.textContent).submitText : 'Submit';
})();

// Client-side conditional field logic (enhancement — form works without this)
document.addEventListener('change', function(e) {
    document.querySelectorAll('.field-group[data-condition]').forEach(function(group) {
        var cond = JSON.parse(group.getAttribute('data-condition'));
        var show = true;
        if (cond.show === undefined) {
            show = true;
        } else if (cond.show === true) {
            show = true;
        } else if (cond.show === false) {
            show = false;
        } else if (cond.field && cond.value !== undefined) {
            var triggerInput = document.querySelector('[name="' + cond.field + '"]');
            if (triggerInput) {
                var val = triggerInput.type === 'checkbox' ? triggerInput.checked : triggerInput.value;
                show = String(val) === String(cond.value);
            }
        }
        group.style.display = show ? '' : 'none';
    });
});

(function() {
    var dataEl = document.getElementById('data-hosted-form');
    var submitText = dataEl ? JSON.parse(dataEl.textContent).submitText : 'Submit';

    var form = document.querySelector('form');
    if (!form) return;

    form.addEventListener('submit', function(e) {
        e.preventDefault();

        var btn = document.querySelector('.submit-btn');
        btn.disabled = true;
        btn.textContent = 'Submitting…';
        btn.style.opacity = '0.6';

        var fd = new FormData(form);
        var action = form.getAttribute('action');

        fetch(action, {
            method: 'POST',
            body: fd,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success || data.submission_id) {
                document.querySelector('.form-container').innerHTML =
                    '<div style="text-align:center;padding:60px 32px;">' +
                        '<div style="font-size:48px;margin-bottom:16px;">✓</div>' +
                        '<h2 style="font-size:20px;margin-bottom:8px;color:#1a1a2e;">Thank You!</h2>' +
                        '<p style="color:#666;font-size:14px;">Your response has been submitted successfully.</p>' +
                    '</div>';
            } else if (data.error) {
                btn.disabled = false;
                btn.textContent = submitText;
                btn.style.opacity = '1';
                alert('Error: ' + data.error);
            }
        })
        .catch(function(err) {
            btn.disabled = false;
            btn.textContent = submitText;
            btn.style.opacity = '1';
            alert('Submission failed. Please try again.');
        });
    });
})();
