/* SailWP Co-pilot — contact-form modal binder.
   Finds buttons/links that read like CTAs ("Book now", "Contact", etc.) on
   the current designed page and wires them to a single modal. Submissions
   POST to /wp-json/sailwp-copilot/v1/contact which emails the site admin. */
(function () {
    'use strict';

    if (typeof window === 'undefined' || !window.SailWPContactForm) return;
    var cfg = window.SailWPContactForm;
    var labels = cfg.labels || {};

    // Patterns that classify a button/link as a contact CTA. Order matters:
    // an explicit data-attribute or href anchor wins over text matching, so
    // we don't accidentally swallow buttons whose label happens to contain
    // "join" but link to a real page.
    var ANCHORS = ['#contact', '#book', '#booking', '#signup', '#sign-up', '#join', '#schedule'];
    var TEXT_PATTERNS = [
        /\bbook(\s+(now|a\s+(class|session|table|seat|spot|table)))?\b/i,
        /\bcontact(\s+us)?\b/i,
        /\bget\s+in\s+touch\b/i,
        /\breach\s+out\b/i,
        /\bsign\s+up\b/i,
        /\bjoin\s+(us|now|the\s+waitlist)\b/i,
        /\bschedule\s+(a\s+(call|consultation|visit))?\b/i,
        /\brequest\s+(a\s+(quote|call|consultation|demo))?\b/i,
        /\bget\s+started\b/i
    ];

    function isContactCTA(el) {
        // Explicit attribute = trust the Co-pilot.
        if (el.hasAttribute('data-swcp-contact')) return true;

        var href = (el.getAttribute('href') || '').toLowerCase().trim();
        if (href.indexOf('mailto:') === 0) return true;
        if (ANCHORS.indexOf(href) !== -1) return true;

        // If the link points to a real page, don't intercept — visitor goes there.
        if (href && href[0] !== '#' && href !== 'javascript:void(0)') return false;

        var text = (el.textContent || '').trim();
        if (!text || text.length > 40) return false; // huge text = probably paragraph, not button

        for (var i = 0; i < TEXT_PATTERNS.length; i++) {
            if (TEXT_PATTERNS[i].test(text)) return true;
        }
        return false;
    }

    function buildModal() {
        var backdrop = document.createElement('div');
        backdrop.className = 'swcp-cf-backdrop';
        backdrop.setAttribute('role', 'dialog');
        backdrop.setAttribute('aria-modal', 'true');
        backdrop.setAttribute('aria-labelledby', 'swcp-cf-title');
        backdrop.innerHTML =
            '<div class="swcp-cf-modal">' +
                '<button type="button" class="swcp-cf-close" aria-label="' + esc(labels.close || 'Close') + '">×</button>' +
                '<h2 class="swcp-cf-title" id="swcp-cf-title">' + esc(labels.title || 'Leave your email — we\'ll be in touch.') + '</h2>' +
                '<form class="swcp-cf-form" novalidate>' +
                    '<label class="swcp-cf-field">' +
                        '<span class="swcp-cf-field-label">' + esc(labels.emailLabel || 'Your email') + '</span>' +
                        '<input class="swcp-cf-input" type="email" name="email" required autocomplete="email" placeholder="' + esc(labels.emailPh || 'you@example.com') + '">' +
                    '</label>' +
                    '<label class="swcp-cf-field">' +
                        '<span class="swcp-cf-field-label">' + esc(labels.messageLabel || 'Anything you want us to know? (optional)') + '</span>' +
                        '<textarea class="swcp-cf-textarea" name="message" rows="3"></textarea>' +
                    '</label>' +
                    '<label class="swcp-cf-honeypot" aria-hidden="true">' +
                        'Website <input type="text" name="website" tabindex="-1" autocomplete="off">' +
                    '</label>' +
                    '<button type="submit" class="swcp-cf-submit">' + esc(labels.send || 'Send') + '</button>' +
                    '<div class="swcp-cf-status" role="status" aria-live="polite"></div>' +
                '</form>' +
            '</div>';

        document.body.appendChild(backdrop);

        var form     = backdrop.querySelector('.swcp-cf-form');
        var emailEl  = backdrop.querySelector('input[name="email"]');
        var msgEl    = backdrop.querySelector('textarea[name="message"]');
        var honeyEl  = backdrop.querySelector('input[name="website"]');
        var submitEl = backdrop.querySelector('.swcp-cf-submit');
        var statusEl = backdrop.querySelector('.swcp-cf-status');
        var closeEl  = backdrop.querySelector('.swcp-cf-close');

        function close() {
            backdrop.classList.remove('is-open');
            // Reset for next open.
            setTimeout(function () {
                form.reset();
                statusEl.className = 'swcp-cf-status';
                statusEl.textContent = '';
                submitEl.disabled = false;
                submitEl.textContent = labels.send || 'Send';
            }, 200);
        }
        function open(sourceLabel) {
            backdrop.classList.add('is-open');
            // Stash the originating button label so the email shows which CTA fired.
            form.dataset.sourceButton = sourceLabel || '';
            setTimeout(function () { emailEl.focus(); }, 50);
        }

        closeEl.addEventListener('click', close);
        backdrop.addEventListener('click', function (e) { if (e.target === backdrop) close(); });
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && backdrop.classList.contains('is-open')) close();
        });

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            submitEl.disabled = true;
            submitEl.textContent = labels.sending || 'Sending…';
            statusEl.className = 'swcp-cf-status';
            statusEl.textContent = '';

            var body = new FormData();
            body.append('email', emailEl.value);
            body.append('message', msgEl.value);
            body.append('page_url', cfg.pageUrl || window.location.href);
            body.append('source_button', form.dataset.sourceButton || '');
            body.append('website', honeyEl.value);

            fetch(cfg.restUrl, { method: 'POST', body: body, credentials: 'omit' })
                .then(function (r) { return r.json().then(function (j) { return { status: r.status, body: j }; }); })
                .then(function (res) {
                    if (res.status === 200 && res.body && res.body.ok) {
                        statusEl.className = 'swcp-cf-status is-ok';
                        statusEl.textContent = res.body.message || (labels.send || 'Sent');
                        setTimeout(close, 1800);
                    } else {
                        var msg = (res.body && (res.body.message || res.body.error)) || 'Could not send. Please try again.';
                        statusEl.className = 'swcp-cf-status is-error';
                        statusEl.textContent = msg;
                        submitEl.disabled = false;
                        submitEl.textContent = labels.send || 'Send';
                    }
                })
                .catch(function () {
                    statusEl.className = 'swcp-cf-status is-error';
                    statusEl.textContent = 'Network error. Please try again.';
                    submitEl.disabled = false;
                    submitEl.textContent = labels.send || 'Send';
                });
        });

        return { open: open, close: close };
    }

    function esc(s) {
        return String(s)
            .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
    }

    function bindAll(modal) {
        var els = document.querySelectorAll('a, button');
        for (var i = 0; i < els.length; i++) {
            var el = els[i];
            if (el.dataset.swcpContactBound) continue;
            if (!isContactCTA(el)) continue;
            el.dataset.swcpContactBound = '1';
            (function (label) {
                el.addEventListener('click', function (e) {
                    e.preventDefault();
                    modal.open(label);
                });
            })((el.textContent || '').trim().slice(0, 60));
        }
    }

    function init() {
        var modal = buildModal();
        bindAll(modal);
        // Re-bind on dynamic content (e.g. inline editor swaps). Light MO,
        // no payload — just re-scan when the body's children change.
        var mo = new MutationObserver(function () { bindAll(modal); });
        mo.observe(document.body, { childList: true, subtree: true });
    }

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