/**
 * Shois Chat Button — Lead Capture Form
 *
 * Pre-chat form that collects name/email before opening chat links.
 * Data saved via REST API to shcb_leads option.
 *
 * @package ShoisChatButton
 */
(function () {
    'use strict';

    /**
     * Initialize lead capture if enabled.
     */
    function init() {
        if (typeof window.shcb_config === 'undefined') {
            return;
        }

        var config = window.shcb_config;

        if (!config.lead_capture || !config.lead_capture.enabled) {
            return;
        }

        // Intercept agent clicks to show form first.
        document.addEventListener('click', function (e) {
            var agentCard = e.target.closest('.shcb-agent-card');
            if (!agentCard) return;

            // Check if already submitted.
            if (sessionStorage.getItem('shcb_lead_captured') === '1') {
                return; // Let the click pass through.
            }

            e.preventDefault();
            e.stopPropagation();
            showLeadForm(agentCard);
        }, true);
    }

    /**
     * Show the lead capture form overlay.
     *
     * @param {HTMLElement} agentCard The clicked agent card.
     */
    function showLeadForm(agentCard) {
        var config = window.shcb_config.lead_capture;

        // Create overlay.
        var overlay = document.createElement('div');
        overlay.className = 'shcb-lead-overlay';

        var form = document.createElement('form');
        form.className = 'shcb-lead-form';

        var title = document.createElement('h4');
        title.className = 'shcb-lead-title';
        title.textContent = config.title || 'Before we start...';
        form.appendChild(title);

        var subtitle = document.createElement('p');
        subtitle.className = 'shcb-lead-subtitle';
        subtitle.textContent = config.subtitle || 'Please share your details so we can help you better.';
        form.appendChild(subtitle);

        // Fields.
        var fields = config.fields || ['name', 'email'];
        fields.forEach(function (field) {
            var input = document.createElement('input');
            input.type = field === 'email' ? 'email' : 'text';
            input.className = 'shcb-lead-input';
            input.name = field;
            input.required = true;
            input.placeholder = field.charAt(0).toUpperCase() + field.slice(1);
            form.appendChild(input);
        });

        // Submit button.
        var submitBtn = document.createElement('button');
        submitBtn.type = 'submit';
        submitBtn.className = 'shcb-lead-submit';
        submitBtn.textContent = config.button_text || 'Start Chat';
        form.appendChild(submitBtn);

        // Skip link.
        var skip = document.createElement('button');
        skip.type = 'button';
        skip.className = 'shcb-lead-skip';
        skip.textContent = config.skip_text || 'Skip';
        skip.addEventListener('click', function () {
            closeLeadForm(overlay);
            sessionStorage.setItem('shcb_lead_captured', '1');
            agentCard.click();
        });
        form.appendChild(skip);

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var data = {};
            fields.forEach(function (field) {
                var input = form.querySelector('[name="' + field + '"]');
                if (input) {
                    data[field] = input.value.trim();
                }
            });

            data.page_url = window.location.href;
            data.timestamp = new Date().toISOString();

            // Send to REST API.
            if (window.shcb_config.rest_url && window.shcb_config.nonce) {
                var xhr = new XMLHttpRequest();
                xhr.open('POST', window.shcb_config.rest_url + '/leads');
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.setRequestHeader('X-WP-Nonce', window.shcb_config.nonce);
                xhr.send(JSON.stringify(data));
            }

            sessionStorage.setItem('shcb_lead_captured', '1');
            closeLeadForm(overlay);
            agentCard.click();
        });

        overlay.appendChild(form);

        var popup = document.querySelector('.shcb-popup');
        if (popup) {
            popup.appendChild(overlay);
        }
    }

    /**
     * Close lead form overlay.
     *
     * @param {HTMLElement} overlay The overlay element.
     */
    function closeLeadForm(overlay) {
        overlay.classList.add('shcb-lead-closing');
        setTimeout(function () {
            if (overlay.parentNode) {
                overlay.parentNode.removeChild(overlay);
            }
        }, 200);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
