/**
 * SEO Forge — custom modal dialog .
 *
 * Drop-in replacements for window.alert / window.confirm with a styled
 * overlay + card. Promise-based API so callers can await or .then.
 *
 * window.sfModal.alert('Saved.', { title: 'All set', variant: 'success' });
 * window.sfModal.confirm('Delete this?').then(function(ok){ if (ok) ... });
 *
 * Variants: 'warning' (default), 'danger', 'info', 'success'.
 */
(function(){
    if (window.sfModal) return;

    var ACTIVE = null;

    function el(tag, attrs, children) {
        var n = document.createElement(tag);
        if (attrs) {
            for (var k in attrs) {
                if (k === 'class') n.className = attrs[k];
                else if (k === 'text') n.textContent = attrs[k];
                else n.setAttribute(k, attrs[k]);
            }
        }
        (children || []).forEach(function(c){ n.appendChild(c); });
        return n;
    }

    function iconClass(variant) {
        // WordPress Dashicons — already loaded on every admin page, no innerHTML
        // required. We use the most recognisable icon per variant.
        switch (variant) {
            case 'success': return 'dashicons dashicons-yes-alt';
            case 'danger':  return 'dashicons dashicons-warning';
            case 'info':    return 'dashicons dashicons-info-outline';
            case 'pro':     return 'dashicons dashicons-superhero-alt';
            default:        return 'dashicons dashicons-warning';
        }
    }

    function buildOverlay() {
        var overlay = el('div', { class: 'sf-modal-overlay', role: 'presentation' });
        overlay.addEventListener('click', function(e){
            if (e.target === overlay && ACTIVE && ACTIVE.cancel) ACTIVE.cancel();
        });
        return overlay;
    }

    function buildCard(opts, resolveWith) {
        var variant = opts.variant || 'warning';
        var isPaywall = opts.mode === 'paywall';
        var card = el('div', {
            class: 'sf-modal-card sf-modal-card--' + variant + (isPaywall ? ' sf-modal-card--paywall' : ''),
            role: 'dialog',
            'aria-modal': 'true',
            'aria-labelledby': 'sf-modal-title',
        });

 // dismiss "X" for the paywall — the upsell must never trap the
        // editor (AC6: close via X or outside click). Other modes keep relying
        // on their action buttons + Escape + outside-click.
        if (isPaywall) {
            var xBtn = el('button', { type: 'button', class: 'sf-modal-close', 'aria-label': opts.closeLabel || 'Close' });
            xBtn.appendChild(el('span', { class: 'dashicons dashicons-no-alt', 'aria-hidden': 'true' }));
            xBtn.addEventListener('click', function(){ resolveWith(false); });
            card.appendChild(xBtn);
        }

        var iconWrap = el('div', { class: 'sf-modal-icon' });
        iconWrap.appendChild(el('span', { class: iconClass(variant), 'aria-hidden': 'true' }));
        card.appendChild(iconWrap);

        var body = el('div', { class: 'sf-modal-body' });
        if (opts.title) body.appendChild(el('h3', { id: 'sf-modal-title', class: 'sf-modal-title', text: opts.title }));
        var msgEl = el('div', { class: 'sf-modal-message' });
        // Message is plain text; split on newlines so multi-line reads cleanly.
        String(opts.message || '').split('\n').forEach(function(line, i){
            if (i > 0) msgEl.appendChild(el('br'));
            msgEl.appendChild(document.createTextNode(line));
        });
        body.appendChild(msgEl);
        card.appendChild(body);

        var actions = el('div', { class: 'sf-modal-actions' });
        var focusEl;

        if (opts.mode === 'confirm') {
            var cancelBtn = el('button', { type: 'button', class: 'sf-modal-btn sf-modal-btn--ghost', text: opts.cancelText || 'Cancel' });
            cancelBtn.addEventListener('click', function(){ resolveWith(false); });
            actions.appendChild(cancelBtn);
        }

        if (isPaywall) {
            // Secondary "Maybe later" + a real <a> CTA so the browser handles
            // the upgrade navigation (no AI/API call ever fires from here).
            var laterBtn = el('button', { type: 'button', class: 'sf-modal-btn sf-modal-btn--ghost', text: opts.laterText || 'Maybe later' });
            laterBtn.addEventListener('click', function(){ resolveWith(false); });
            actions.appendChild(laterBtn);

            var cta = el('a', {
                class: 'sf-modal-btn sf-modal-btn--primary sf-modal-btn--' + variant,
                href: opts.ctaUrl || '#',
                target: '_blank',
                rel: 'noopener',
                text: opts.ctaText || 'Upgrade',
            });
            cta.addEventListener('click', function(){ resolveWith(true); });
            actions.appendChild(cta);
            focusEl = cta;
        } else {
            var okBtn = el('button', {
                type: 'button',
                class: 'sf-modal-btn sf-modal-btn--primary sf-modal-btn--' + variant,
                text: opts.okText || (opts.mode === 'confirm' ? 'Confirm' : 'OK'),
            });
            okBtn.addEventListener('click', function(){ resolveWith(true); });
            actions.appendChild(okBtn);
            focusEl = okBtn;
        }

        card.appendChild(actions);

        // Focus primary action once the card is in the DOM.
        setTimeout(function(){ try { focusEl.focus(); } catch (e) {} }, 10);

        return card;
    }

    function open(opts) {
        return new Promise(function(resolve){
            // If another modal is open, close it (cancel) first so the new one can replace.
            if (ACTIVE) ACTIVE.cancel();

            var overlay = buildOverlay();
            var card;

            function close(val) {
                document.removeEventListener('keydown', onKey, true);
                if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
                if (ACTIVE === api) ACTIVE = null;
                resolve(val);
            }
            function resolveWith(v){ close(v); }
            function onKey(e){
                if (e.key === 'Escape') { e.stopPropagation(); close(opts.mode === 'confirm' ? false : true); }
                else if (e.key === 'Enter') { e.stopPropagation(); close(true); }
            }

            var api = { cancel: function(){ close(opts.mode === 'confirm' ? false : true); } };
            ACTIVE = api;

            card = buildCard(opts, resolveWith);
            overlay.appendChild(card);
            document.body.appendChild(overlay);
            document.addEventListener('keydown', onKey, true);
        });
    }

    window.sfModal = {
        alert: function(message, opts) {
            opts = opts || {};
            return open({
                mode: 'alert',
                message: message,
                title: opts.title || '',
                variant: opts.variant || 'warning',
                okText: opts.okText,
            });
        },
        confirm: function(message, opts) {
            opts = opts || {};
            return open({
                mode: 'confirm',
                message: message,
                title: opts.title || '',
                variant: opts.variant || 'warning',
                okText: opts.okText,
                cancelText: opts.cancelText,
            });
        },
 // AI upsell modal. Resolves true if the user clicks the CTA,
        // false on dismiss (X / Maybe later / Escape / outside click).
        paywall: function(message, opts) {
            opts = opts || {};
            return open({
                mode: 'paywall',
                message: message,
                title: opts.title || 'Unlock AI Powers',
                variant: 'pro',
                ctaUrl: opts.ctaUrl,
                ctaText: opts.ctaText,
                laterText: opts.laterText,
                closeLabel: opts.closeLabel,
            });
        },
    };
})();
