/**
 * MenuX Free — Footer Builder admin JS
 * Column builder, live preview, themes and setup wizard.
 */
(function () {
    'use strict';

    var data = window.menuxFooterData || { footer: {}, style: {}, networks: {} };
    var NETWORKS = data.networks;
    var REST_ROOT = data.restUrl || (window.wpApiSettings && window.wpApiSettings.root) || '';

    /* ── State ───────────────────────────────────────────────────────── */
    var state = {
        enabled:       data.footer.enabled === '1',
        placement:     data.footer.placement || 'manual',
        auto_priority: data.footer.auto_priority || '100',
        layout:        data.footer.layout || 'wide-first',
        columns:       Array.isArray(data.footer.columns) ? JSON.parse(JSON.stringify(data.footer.columns)) : [],
        bottom:        data.footer.bottom || { copyright: '', links: [], show_social: '0' }
    };
    if (!Array.isArray(state.bottom.links)) state.bottom.links = [];

    var SECTION_TYPES = {
        about:      { label: '🏢 About / Text',   icon: 'fa-solid fa-align-left' },
        links:      { label: '🔗 Link list',       icon: 'fa-solid fa-link' },
        contact:    { label: '📍 Contact info',    icon: 'fa-solid fa-location-dot' },
        social:     { label: '🌐 Social icons',    icon: 'fa-solid fa-share-nodes' },
        hours:      { label: '🕒 Opening hours',   icon: 'fa-solid fa-clock' },
        newsletter: { label: '📧 Newsletter',       icon: 'fa-solid fa-envelope-open-text' },
        html:       { label: '✏️ Custom HTML',     icon: 'fa-solid fa-code' }
    };

    /* ── Footer themes (curated palettes) ───────────────────────────────
       Each palette is hand-tuned for contrast + harmony. Dark themes carry a
       subtle vertical gradient for depth; accents are chosen to glow against
       their background without clashing. Keys are stable (PHP whitelist). */
    var FTHEMES = {
        midnight:  { name: 'Midnight',     bg: '#0f172a', bg_gradient: 'linear-gradient(180deg,#13203b,#0b1426)',          heading_color: '#f8fafc', text_color: '#94a3b8', link_color: '#cbd5e1', link_hover_color: '#ffffff', accent_color: '#6366f1', bottom_bg: '#0a101f', bottom_text_color: '#64748b' },
        carbon:    { name: 'Carbon Gold',  bg: '#0c0c10', bg_gradient: 'linear-gradient(180deg,#16161e,#0a0a0e)',          heading_color: '#f4ead2', text_color: '#9b9ba3', link_color: '#d4d4d8', link_hover_color: '#e9d8a6', accent_color: '#d4af37', bottom_bg: '#08080b', bottom_text_color: '#6b6b73' },
        charcoal:  { name: 'Graphite',     bg: '#1b1b1e', bg_gradient: 'linear-gradient(180deg,#232327,#151517)',          heading_color: '#fafafa', text_color: '#a1a1aa', link_color: '#e4e4e7', link_hover_color: '#ffffff', accent_color: '#f59e0b', bottom_bg: '#121214', bottom_text_color: '#71717a' },
        ocean:     { name: 'Deep Ocean',   bg: '#0c2a33', bg_gradient: 'linear-gradient(180deg,#0e3540,#08222a)',          heading_color: '#ecfeff', text_color: '#8fc5cf', link_color: '#cffafe', link_hover_color: '#ffffff', accent_color: '#22d3ee', bottom_bg: '#061a20', bottom_text_color: '#67c2cf' },
        forest:    { name: 'Evergreen',    bg: '#064e3b', bg_gradient: 'linear-gradient(180deg,#075e48,#04372a)',          heading_color: '#ecfdf5', text_color: '#9deccb', link_color: '#d1fae5', link_hover_color: '#ffffff', accent_color: '#34d399', bottom_bg: '#032a20', bottom_text_color: '#6ee7b7' },
        wine:      { name: 'Bordeaux',     bg: '#3b0d18', bg_gradient: 'linear-gradient(180deg,#4c1020,#300a13)',          heading_color: '#fdf2f4', text_color: '#d9a7af', link_color: '#f7dde1', link_hover_color: '#ffffff', accent_color: '#d8a657', bottom_bg: '#280810', bottom_text_color: '#bd8e94' },
        corporate: { name: 'Sapphire',     bg: '#1e3a8a', bg_gradient: 'linear-gradient(160deg,#1e40af,#1b3578 60%,#152a5c)', heading_color: '#ffffff', text_color: '#bcd2f5', link_color: '#dbeafe', link_hover_color: '#ffffff', accent_color: '#38bdf8', bottom_bg: '#15244d', bottom_text_color: '#93c5fd' },
        gradient:  { name: 'Aurora',       bg: '#7c3aed', bg_gradient: 'linear-gradient(135deg,#4f46e5,#7c3aed 55%,#9d4edd)', heading_color: '#ffffff', text_color: '#e4dcfb', link_color: '#f3effe', link_hover_color: '#ffffff', accent_color: '#fbbf24', bottom_bg: '#3a2570', bottom_text_color: '#d6c9f5' },
        light:     { name: 'Porcelain',    bg: '#f8fafc', bg_gradient: 'linear-gradient(180deg,#ffffff,#eef2f7)',          heading_color: '#0f172a', text_color: '#5b6776', link_color: '#334155', link_hover_color: '#0f172a', accent_color: '#2563eb', bottom_bg: '#eef2f7', bottom_text_color: '#64748b' },
        cream:     { name: 'Sandstone',    bg: '#faf6f0', bg_gradient: 'linear-gradient(180deg,#fdfaf5,#f4ece0)',          heading_color: '#44403c', text_color: '#78716c', link_color: '#57534e', link_hover_color: '#292524', accent_color: '#bd6a3c', bottom_bg: '#f1e7d8', bottom_text_color: '#a8a29e' },
        mono:      { name: 'Editorial',    bg: '#ffffff', bg_gradient: '',                                                 heading_color: '#000000', text_color: '#525252', link_color: '#171717', link_hover_color: '#000000', accent_color: '#171717', bottom_bg: '#000000', bottom_text_color: '#a3a3a3' }
    };

    /* ── Helpers ─────────────────────────────────────────────────────── */
    function esc(str) {
        return String(str == null ? '' : str)
            .replace(/&/g, '&amp;').replace(/"/g, '&quot;')
            .replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }
    function styleVal(name) {
        var el = document.querySelector('[name="menux_fstyle[' + name + ']"]');
        if (!el) return '';
        if (el.type === 'checkbox') return el.checked ? '1' : '0';
        return el.value;
    }
    function setStyleVal(name, value) {
        var el = document.querySelector('[name="menux_fstyle[' + name + ']"]');
        if (!el) return;
        if (el.type === 'checkbox') { el.checked = value === '1'; } else { el.value = value; }
    }

    /* ── Inline notification (replaces alert() for non-destructive info) */
    function notify(msg, type) {
        var existing = document.getElementById('mxf-notify');
        if (existing) existing.remove();
        var n = document.createElement('div');
        n.id = 'mxf-notify';
        var colors = type === 'error'
            ? 'background:#fef2f2;border-left:4px solid #ef4444;color:#991b1b;'
            : 'background:#f0fdf4;border-left:4px solid #22c55e;color:#166534;';
        n.style.cssText = colors + 'padding:10px 16px;border-radius:6px;font-size:13px;font-weight:500;'
                        + 'position:fixed;top:32px;right:24px;z-index:99998;box-shadow:0 4px 12px rgba(0,0,0,.12);'
                        + 'max-width:340px;animation:mxfSlideIn .2s ease;';
        n.textContent = msg;
        document.body.appendChild(n);
        setTimeout(function () { if (n.parentNode) n.style.opacity = '0'; n.style.transition = 'opacity .3s'; }, 2800);
        setTimeout(function () { if (n.parentNode) n.remove(); }, 3200);
    }
    // Inject keyframe once
    (function() {
        var s = document.getElementById('mxf-notify-style');
        if (s) return;
        s = document.createElement('style');
        s.id = 'mxf-notify-style';
        s.textContent = '@keyframes mxfSlideIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}';
        document.head.appendChild(s);
    })();

    /* ── Serialization ───────────────────────────────────────────────── */
    function serialize() {
        var json = document.getElementById('menux-footer-json');
        if (json) {
            json.value = JSON.stringify({
                enabled:       state.enabled ? '1' : '0',
                placement:     state.placement,
                auto_priority: state.auto_priority,
                layout:        state.layout,
                columns:       state.columns,
                bottom:        state.bottom
            });
        }
    }

    /* ── Builder UI ──────────────────────────────────────────────────── */
    function fieldRow(label, inner) {
        return '<div style="display:flex;align-items:flex-start;gap:8px;margin-bottom:8px;">'
             + '<span style="font-size:11px;color:#6b7280;min-width:64px;padding-top:6px;">' + label + '</span>'
             + '<div style="flex:1;">' + inner + '</div></div>';
    }

    function renderColumnBody(col, ci) {
        var h = '';
        h += '<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:#9ca3af;margin-bottom:10px;cursor:pointer;">'
           + '<input type="checkbox" data-f="hide_mobile" ' + (col.hide_mobile === '1' || col.hide_mobile === true ? 'checked' : '') + '> Hide this column on mobile</label>';
        switch (col.type) {
        case 'about':
                h += fieldRow('Logo/Image URL',
                    '<div style="display:flex;gap:6px;">'
                    + '<input type="url" data-f="img_url" placeholder="https://… or leave blank" value="' + esc(col.img_url || '') + '" style="flex:1;">'
                    + (typeof wp !== 'undefined' && wp.media
                        ? '<button type="button" class="button button-small mxf-media-pick" data-f="img_url">📂</button>'
                        : '')
                    + '</div>'
                );
                h += fieldRow('Image width', '<input type="text" data-f="img_width" value="' + esc(col.img_width || '') + '" style="width:90px;" placeholder="e.g. 140px">');
                h += fieldRow('Text', '<textarea data-f="text" rows="3" style="width:100%;">' + esc(col.text || '') + '</textarea>');
                break;
            case 'links':
                col.items = col.items || [];
                h += '<div class="mxf-sub-list">';
                col.items.forEach(function (item, ii) {
                    h += '<div style="display:flex;gap:6px;margin-bottom:6px;" data-ii="' + ii + '">'
                       + '<input type="text" data-lf="label" placeholder="Label" value="' + esc(item.label || '') + '" style="flex:1;">'
                       + '<input type="url" data-lf="url" placeholder="https://…" value="' + esc(item.url || '') + '" style="flex:1.4;">'
                       + '<label style="font-size:11px;color:#6b7280;display:flex;align-items:center;gap:3px;" title="Open in new tab"><input type="checkbox" data-lf="target" ' + (item.target === '_blank' ? 'checked' : '') + '>↗</label>'
                       + '<button type="button" class="button button-small mxf-del-link">×</button>'
                       + '</div>';
                });
                h += '</div><button type="button" class="button button-small mxf-add-link">＋ Add link</button>';
                break;
            case 'contact':
                h += fieldRow('Address', '<textarea data-f="address" rows="2" style="width:100%;">' + esc(col.address || '') + '</textarea>');
                h += fieldRow('Phone', '<input type="text" data-f="phone" value="' + esc(col.phone || '') + '" style="width:100%;">');
                h += fieldRow('Email', '<input type="email" data-f="email" value="' + esc(col.email || '') + '" style="width:100%;">');
                break;
            case 'social':
                col.networks = col.networks || [];
                h += '<div class="mxf-sub-list">';
                col.networks.forEach(function (soc, si) {
                    var opts = '';
                    Object.keys(NETWORKS).forEach(function (k) {
                        opts += '<option value="' + k + '"' + (soc.network === k ? ' selected' : '') + '>' + esc(NETWORKS[k].label) + '</option>';
                    });
                    h += '<div style="display:flex;gap:6px;margin-bottom:6px;" data-si="' + si + '">'
                       + '<select data-sf="network" style="width:130px;">' + opts + '</select>'
                       + '<input type="url" data-sf="url" placeholder="https://…" value="' + esc(soc.url || '') + '" style="flex:1;">'
                       + '<button type="button" class="button button-small mxf-del-soc">×</button>'
                       + '</div>';
                });
                h += '</div><button type="button" class="button button-small mxf-add-soc">＋ Add network</button>';
                break;
            case 'hours':
                col.lines = col.lines || [];
                h += '<div class="mxf-sub-list">';
                col.lines.forEach(function (line, li) {
                    h += '<div style="display:flex;gap:6px;margin-bottom:6px;" data-li="' + li + '">'
                       + '<input type="text" data-hf="line" placeholder="Mon–Fri: 9:00–18:00" value="' + esc(line) + '" style="flex:1;">'
                       + '<button type="button" class="button button-small mxf-del-hour">×</button>'
                       + '</div>';
                });
                h += '</div><button type="button" class="button button-small mxf-add-hour">＋ Add line</button>';
                break;
            case 'newsletter':
                h += fieldRow('Subtitle', '<input type="text" data-f="subtitle" value="' + esc(col.subtitle || '') + '" style="width:100%;" placeholder="Subscribe for updates">');
                h += fieldRow('Form action URL', '<input type="url" data-f="form_action" value="' + esc(col.form_action || '') + '" style="width:100%;" placeholder="https://your-list-manager.com/…">');
                h += fieldRow('Placeholder', '<input type="text" data-f="placeholder" value="' + esc(col.placeholder || '') + '" style="width:100%;" placeholder="Your email address">');
                h += fieldRow('Button text', '<input type="text" data-f="button_text" value="' + esc(col.button_text || '') + '" style="width:100%;" placeholder="Subscribe">');
                h += fieldRow('GDPR checkbox', '<input type="text" data-f="gdpr_text" value="' + esc(col.gdpr_text || '') + '" style="width:100%;" placeholder="I agree to the privacy policy (leave blank to omit)">');
                break;
            case 'html':
                h += fieldRow('HTML', '<textarea data-f="html" rows="4" style="width:100%;font-family:monospace;font-size:12px;">' + esc(col.html || '') + '</textarea>');
                break;
        }
        return h;
    }

    function renderBuilder() {
        var wrap = document.getElementById('mxf-cols');
        if (!wrap) return;
        var h = '';
        if (!state.columns.length) {
            h = '<div style="padding:24px;text-align:center;color:#9ca3af;font-size:13px;background:#f9fafb;border-radius:8px;border:1px dashed #e5e7eb;">No sections yet. Use the <strong>Setup Wizard</strong> or add one manually.</div>';
        }
        state.columns.forEach(function (col, ci) {
            var typeOpts = '';
            Object.keys(SECTION_TYPES).forEach(function (t) {
                typeOpts += '<option value="' + t + '"' + (col.type === t ? ' selected' : '') + '>' + SECTION_TYPES[t].label + '</option>';
            });
            h += '<div class="mxf-col-card" data-ci="' + ci + '" draggable="true" style="border:1px solid #e5e7eb;border-radius:10px;padding:12px 14px;margin-bottom:10px;background:#fafafa;transition:opacity .15s,box-shadow .15s;">'
               + '<div style="display:flex;align-items:center;gap:8px;margin-bottom:10px;">'
               + '<span class="mxf-drag-handle" style="cursor:grab;color:#9ca3af;font-size:16px;line-height:1;user-select:none;" title="Drag to reorder">⠿</span>'
               + '<select data-f="type" style="width:170px;">' + typeOpts + '</select>'
               + '<input type="text" data-f="title" placeholder="Section title" value="' + esc(col.title || '') + '" style="flex:1;">'
               + '<button type="button" class="button button-small mxf-col-up" title="Move up">↑</button>'
               + '<button type="button" class="button button-small mxf-col-down" title="Move down">↓</button>'
               + '<button type="button" class="button button-small mxf-col-dup" title="Duplicate">⧉</button>'
               + '<button type="button" class="button button-small mxf-col-del" title="Remove" style="color:#b91c1c;">×</button>'
               + '</div>'
               + '<div class="mxf-col-body">' + renderColumnBody(col, ci) + '</div>'
               + '</div>';
        });
        wrap.innerHTML = h;
        bindDragDrop(wrap);
    }

    /* ── Drag-and-drop reorder ───────────────────────────────────────────
       Uses HTML5 drag API. Only the ⠿ handle initiates the drag, so
       text inputs/textareas inside the card remain normally interactive.  */
    var _drag = { fromIdx: null, toIdx: null };

    function bindDragDrop(wrap) {
        var cards = wrap.querySelectorAll('.mxf-col-card'); // cached once per render
        function resetHighlights() {
            cards.forEach(function (c) { c.style.boxShadow = ''; c.style.borderColor = '#e5e7eb'; });
        }
        cards.forEach(function (card) {
            card.addEventListener('dragstart', function (e) {
                if (!e.target.classList.contains('mxf-drag-handle')) { e.preventDefault(); return; }
                _drag.fromIdx = parseInt(card.getAttribute('data-ci'), 10);
                card.style.opacity = '0.45';
                e.dataTransfer.effectAllowed = 'move';
            });
            card.addEventListener('dragend', function () {
                card.style.opacity = '';
                resetHighlights();
                if (_drag.fromIdx !== null && _drag.toIdx !== null && _drag.fromIdx !== _drag.toIdx) {
                    var moved = state.columns.splice(_drag.fromIdx, 1)[0];
                    state.columns.splice(_drag.toIdx, 0, moved);
                    refresh();
                }
                _drag.fromIdx = _drag.toIdx = null;
            });
            card.addEventListener('dragover', function (e) {
                if (_drag.fromIdx === null) return;
                e.preventDefault();
                e.dataTransfer.dropEffect = 'move';
                _drag.toIdx = parseInt(card.getAttribute('data-ci'), 10);
                resetHighlights();
                card.style.boxShadow = '0 0 0 2px #6366f1';
                card.style.borderColor = '#6366f1';
            });
        });
    }

    function renderBottomLinks() {
        var wrap = document.getElementById('mxf-bottom-links');
        if (!wrap) return;
        var h = '';
        state.bottom.links.forEach(function (l, i) {
            h += '<div style="display:flex;gap:6px;margin-bottom:6px;" data-bi="' + i + '">'
               + '<input type="text" data-bf="label" placeholder="Privacy Policy" value="' + esc(l.label || '') + '" style="flex:1;">'
               + '<input type="url" data-bf="url" placeholder="/privacy" value="' + esc(l.url || '') + '" style="flex:1.3;">'
               + '<button type="button" class="button button-small mxf-del-blink">×</button>'
               + '</div>';
        });
        wrap.innerHTML = h;
    }

    /* ── Live preview ────────────────────────────────────────────────── */
    function previewCss() {
        var s = function (k, fb) { var v = styleVal(k); return v !== '' ? v : fb; };
        var bg       = s('bg', '#0f172a');
        var grad     = document.getElementById('mxf-bg-gradient') ? document.getElementById('mxf-bg-gradient').value : '';
        var headc    = s('heading_color', '#f1f5f9');
        var textc    = s('text_color', '#94a3b8');
        var linkc    = s('link_color', '#cbd5e1');
        var linkh    = s('link_hover_color', '#ffffff');
        var accent   = s('accent_color', '#667eea');
        var py       = Math.round(parseInt(s('padding_y', '56'), 10) * 0.6);
        var px       = Math.round(parseInt(s('padding_x', '24'), 10) * 0.6);
        var gap      = Math.round(parseInt(s('col_gap', '48'), 10) * 0.6);
        var lgap     = parseInt(s('link_gap', '12'), 10);
        var hsize    = Math.max(10, parseInt(s('heading_size', '14'), 10) - 1);
        var hweight  = s('heading_weight', '700');
        var htrans   = s('heading_transform', 'uppercase');
        var fsize    = Math.max(10, parseInt(s('font_size', '14'), 10) - 1);
        var hoverFx  = s('link_hover_effect', 'slide');
        var socStyle = s('social_style', 'circle');
        var socSize  = Math.max(10, parseInt(s('social_size', '16'), 10) - 2);
        var bbg      = s('bottom_bg', '#0b1120');
        var btc      = s('bottom_text_color', '#64748b');
        var p        = '#menux-footer-preview ';
        var bgCss    = grad ? 'background:' + grad + ';' : 'background:' + bg + ';';

        var css = p + '.menux-footer{' + bgCss + 'color:' + textc + ';font-size:' + fsize + 'px;line-height:1.7;}';
        if (styleVal('accent_bar') === '1') {
            css += p + '.menux-footer::before{content:"";display:block;height:' + parseInt(s('accent_height', '3'), 10) + 'px;background:linear-gradient(90deg,' + accent + ',' + accent + 'cc);}';
        }
        css += p + '.menux-footer-inner{padding:' + py + 'px ' + px + 'px;}';
        css += p + '.menux-footer-cols{display:grid;gap:' + gap + 'px;grid-template-columns:repeat(var(--menux-fcols,4),1fr);}';
        css += p + '.menux-footer-cols.menux-flayout-wide-first{grid-template-columns:1.6fr repeat(calc(var(--menux-fcols,4) - 1),1fr);}';
        css += p + '.menux-footer-cols.menux-flayout-centered{text-align:center;}';
        css += p + '.menux-flayout-centered .menux-footer-social{justify-content:center;}';
        css += p + '.menux-flayout-centered .menux-footer-contact li{justify-content:center;}';
        css += p + '.menux-footer-heading{margin:0 0 12px;font-size:' + hsize + 'px;font-weight:' + hweight + ';color:' + headc + ';text-transform:' + htrans + ';letter-spacing:' + (htrans === 'uppercase' ? '.08em' : '0') + ';}';
        css += p + '.menux-footer p{margin:0 0 10px;}';
        css += p + '.menux-footer-list,' + p + '.menux-footer-contact{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:' + lgap + 'px;}';
        css += p + '.menux-footer a{color:' + linkc + ';text-decoration:none;transition:color .2s ease' + (hoverFx === 'slide' ? ',padding-left .2s ease' : '') + ';}';
        css += p + '.menux-footer a:hover{color:' + linkh + ';}';
        if (hoverFx === 'underline') {
            // Mirror the frontend's animated growing-line effect (footer-css.php), not a static underline.
            css += p + '.menux-footer-list a{background-image:linear-gradient(' + linkh + ',' + linkh + ');background-size:0 1px;background-position:0 100%;background-repeat:no-repeat;transition:background-size .25s ease,color .2s ease;}';
            css += p + '.menux-footer-list a:hover{background-size:100% 1px;}';
        } else if (hoverFx === 'slide') {
            css += p + '.menux-footer-list a:hover{padding-left:6px;}';
        }
        css += p + '.menux-footer-contact li{display:flex;align-items:flex-start;gap:8px;}';
        css += p + '.menux-footer-contact i{color:' + accent + ';margin-top:4px;flex-shrink:0;}';
        css += p + '.menux-footer-social{display:flex;flex-wrap:wrap;gap:8px;margin-top:4px;}';
        if (socStyle === 'plain') {
            css += p + '.menux-footer-social a{font-size:' + (socSize + 2) + 'px;color:' + linkc + ';}';
            css += p + '.menux-footer-social a:hover{color:' + accent + ';}';
        } else {
            var radius = socStyle === 'circle' ? '50%' : '7px';
            var box = socSize + 16;
            css += p + '.menux-footer-social a{display:inline-flex;align-items:center;justify-content:center;width:' + box + 'px;height:' + box + 'px;border-radius:' + radius + ';font-size:' + socSize + 'px;color:' + linkc + ';background:rgba(128,128,128,.14);transition:all .2s;}';
            css += p + '.menux-footer-social a:hover{background:' + accent + ';color:#fff;}';
        }
        css += p + '.menux-footer-bottom{background:' + bbg + ';color:' + btc + ';font-size:' + Math.max(10, fsize - 1) + 'px;' + (styleVal('bottom_divider') === '1' ? 'border-top:1px solid rgba(128,128,128,.16);' : '') + '}';
        css += p + '.menux-footer-bottom-inner{padding:12px ' + px + 'px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;}';
        css += p + '.menux-footer-bottom a{color:' + btc + ';}';
        css += p + '.menux-footer-legal{list-style:none;margin:0;padding:0;display:flex;gap:16px;flex-wrap:wrap;}';
        css += p + '.menux-footer-bottom .menux-footer-social{margin-top:0;}';
        return css;
    }

    function previewSocial(networks) {
        var h = '';
        (networks || []).forEach(function (soc) {
            // Match the frontend: skip unknown networks and entries with no URL (footer-render.php).
            if (!NETWORKS[soc.network] || !soc.url) return;
            h += '<a href="#" onclick="return false;"><i class="' + esc(NETWORKS[soc.network].icon) + '"></i></a>';
        });
        return h ? '<div class="menux-footer-social">' + h + '</div>' : '';
    }

    function renderPreview() {
        var box = document.getElementById('menux-footer-preview');
        if (!box) return;
        if (!state.enabled || !state.columns.length) {
            box.innerHTML = '<div style="padding:32px;text-align:center;color:#9ca3af;font-size:13px;">'
                          + (state.columns.length ? 'Footer is disabled — flip the <strong>Enable footer</strong> toggle.' : 'Nothing to preview yet — run the <strong>Setup Wizard</strong> to build your footer in 1 minute.')
                          + '</div>';
            return;
        }
        var h = '<style>' + previewCss() + '</style>';
        h += '<div class="menux-footer"><div class="menux-footer-inner">';
        h += '<div class="menux-footer-cols menux-flayout-' + esc(state.layout) + '" style="--menux-fcols:' + state.columns.length + ';">';
        state.columns.forEach(function (col) {
            var hideMobile = col.hide_mobile === '1' || col.hide_mobile === true;
            h += '<div class="menux-footer-col' + (hideMobile ? ' menux-fcol-hidden-mobile' : '') + '" style="' + (hideMobile ? 'opacity:.35;outline:1px dashed #f59e0b;' : '') + '">';
            if (col.title) h += '<h4 class="menux-footer-heading">' + esc(col.title) + '</h4>';
            switch (col.type) {
                case 'about':
                    if (col.img_url) h += '<img src="' + esc(col.img_url) + '" alt="" style="max-width:' + esc(col.img_width || '160px') + ';height:auto;display:block;margin-bottom:12px;">';
                    if (col.text) h += '<p>' + esc(col.text).replace(/\n/g, '<br>') + '</p>';
                    break;
                case 'links':
                    h += '<ul class="menux-footer-list">';
                    (col.items || []).forEach(function (i) { if (i.label) h += '<li><a href="#" onclick="return false;">' + esc(i.label) + '</a></li>'; });
                    h += '</ul>';
                    break;
                case 'contact':
                    h += '<ul class="menux-footer-contact">';
                    if (col.address) h += '<li><i class="fa-solid fa-location-dot"></i><span>' + esc(col.address).replace(/\n/g, '<br>') + '</span></li>';
                    if (col.phone)   h += '<li><i class="fa-solid fa-phone"></i><a href="#" onclick="return false;">' + esc(col.phone) + '</a></li>';
                    if (col.email)   h += '<li><i class="fa-solid fa-envelope"></i><a href="#" onclick="return false;">' + esc(col.email) + '</a></li>';
                    h += '</ul>';
                    break;
                case 'social':
                    h += previewSocial(col.networks);
                    break;
                case 'hours':
                    h += '<ul class="menux-footer-list">';
                    (col.lines || []).forEach(function (l) { if (l) h += '<li>' + esc(l) + '</li>'; });
                    h += '</ul>';
                    break;
                case 'newsletter':
                    h += '<div class="menux-footer-newsletter">';
                    if (col.subtitle) h += '<p style="margin:0 0 10px;font-size:12px;">' + esc(col.subtitle) + '</p>';
                    h += '<div style="display:flex;">'
                       + '<input type="email" placeholder="' + esc(col.placeholder || 'Your email address') + '" style="flex:1;padding:8px 12px;border:1px solid rgba(128,128,128,.25);background:rgba(255,255,255,.06);color:inherit;border-radius:4px 0 0 4px;font-size:12px;" disabled>'
                       + '<button style="padding:8px 14px;background:' + styleVal('accent_color') + ';color:#fff;border:none;border-radius:0 4px 4px 0;font-size:12px;font-weight:600;cursor:default;">' + esc(col.button_text || 'Subscribe') + '</button>'
                       + '</div>';
                    if (col.gdpr_text) h += '<div style="font-size:11px;margin-top:8px;opacity:.7;">' + esc(col.gdpr_text) + '</div>';
                    // The frontend skips the newsletter entirely without a form action URL — warn here so the preview matches.
                    if (!col.form_action) h += '<div style="font-size:11px;margin-top:8px;color:#f59e0b;">⚠ Add a Form action URL or this block won\'t appear on the site.</div>';
                    h += '</div>';
                    break;
                case 'html':
                    h += '<div style="opacity:.75;font-size:11px;border:1px dashed rgba(128,128,128,.35);border-radius:6px;padding:10px;">Custom HTML block</div>';
                    break;
            }
            h += '</div>';
        });
        h += '</div></div>';
        // Bottom bar
        var b = state.bottom;
        if (b.copyright || b.links.length || b.show_social === '1') {
            h += '<div class="menux-footer-bottom"><div class="menux-footer-bottom-inner">';
            if (b.copyright) h += '<span>' + esc(b.copyright.replace('{year}', String(new Date().getFullYear()))) + '</span>';
            if (b.links.length) {
                h += '<ul class="menux-footer-legal">';
                b.links.forEach(function (l) { if (l.label) h += '<li><a href="#" onclick="return false;">' + esc(l.label) + '</a></li>'; });
                h += '</ul>';
            }
            if (b.show_social === '1') {
                var socCol = state.columns.filter(function (c) { return c.type === 'social'; })[0];
                h += previewSocial(socCol ? socCol.networks : b.networks);
            }
            h += '</div></div>';
        }
        h += '</div>';
        box.innerHTML = h;
    }

    function refresh() { renderBuilder(); renderBottomLinks(); renderPreview(); serialize(); }
    function refreshLight() { renderPreview(); serialize(); }

    /* ── Theme card helpers (shared by gallery and wizard) ──────────────── */

    // Builds one column stub: heading bar + content lines + optional social dots.
    // Defined once at module scope so both renderThemes() and wizRender() can call it.
    function themeColStub(t, headW, lines, lineColor, showDots, compact) {
        var headH = compact ? 3 : 4;
        var lineH = compact ? 2 : 3;
        var dotSz = compact ? 6 : 8;
        var s = '<div style="min-width:0;">'
              + '<div style="height:' + headH + 'px;width:' + headW + '%;background:' + t.heading_color + ';border-radius:2px;margin-bottom:' + (compact ? 4 : 5) + 'px;opacity:.9;"></div>';
        lines.forEach(function (w) {
            s += '<div style="height:' + lineH + 'px;width:' + w + '%;background:' + (lineColor || t.link_color) + ';border-radius:2px;margin-bottom:3px;opacity:' + (compact ? '.6' : '.7') + ';"></div>';
        });
        if (showDots) {
            s += '<div style="display:flex;gap:3px;margin-top:4px;">'
               + '<span style="width:' + dotSz + 'px;height:' + dotSz + 'px;border-radius:50%;background:' + t.accent_color + ';opacity:.9;display:inline-block;"></span>'
               + '<span style="width:' + dotSz + 'px;height:' + dotSz + 'px;border-radius:50%;background:' + t.link_color + ';opacity:.5;display:inline-block;"></span>'
               + '<span style="width:' + dotSz + 'px;height:' + dotSz + 'px;border-radius:50%;background:' + t.link_color + ';opacity:.5;display:inline-block;"></span>'
               + '</div>';
        }
        return s + '</div>';
    }

    /* ── Themes grid ─────────────────────────────────────────────────── */
    function renderThemes() {
        var grid = document.getElementById('mxf-themes-grid');
        if (!grid) return;
        var current = styleVal('theme') || document.getElementById('mxf-theme').value;
        var h = '';
        Object.keys(FTHEMES).forEach(function (key) {
            var t      = FTHEMES[key];
            var bgCss  = t.bg_gradient ? 'background:' + t.bg_gradient + ';' : 'background:' + t.bg + ';';
            var active = current === key;
            var border = active ? '2px solid ' + t.accent_color : '2px solid #e5e7eb';
            var shadow = active ? '0 0 0 3px ' + t.accent_color + '55' : 'none';

            h += '<div class="mxf-theme-card" data-theme="' + key + '" title="' + t.name + '" style="cursor:pointer;border:' + border + ';border-radius:10px;overflow:hidden;transition:border-color .15s,box-shadow .15s;box-shadow:' + shadow + ';">'
               // accent bar
               + '<div style="height:3px;' + bgCss + '">'
               +   '<div style="height:100%;width:100%;background:' + t.accent_color + ';opacity:.9;"></div>'
               + '</div>'
               // footer body — 3 column stubs via shared helper
               + '<div style="' + bgCss + 'padding:9px 8px 7px;display:grid;grid-template-columns:1.3fr 1fr 1fr;gap:6px;min-height:72px;">'
               +   themeColStub(t, 65, [100, 85, 90], t.text_color, true,  false)
               +   themeColStub(t, 55, [75, 65, 70],  null,         false, false)
               +   themeColStub(t, 60, [80, 70, 75],  null,         false, false)
               + '</div>'
               // bottom bar
               + '<div style="background:' + t.bottom_bg + ';padding:5px 8px;display:flex;align-items:center;justify-content:space-between;border-top:1px solid rgba(128,128,128,.12);">'
               +   '<div style="height:3px;width:38%;background:' + t.bottom_text_color + ';border-radius:2px;opacity:.7;"></div>'
               +   '<div style="display:flex;gap:3px;">'
               +     '<span style="width:6px;height:6px;border-radius:50%;background:' + t.bottom_text_color + ';opacity:.5;display:inline-block;"></span>'
               +     '<span style="width:6px;height:6px;border-radius:50%;background:' + t.bottom_text_color + ';opacity:.5;display:inline-block;"></span>'
               +     '<span style="width:6px;height:6px;border-radius:50%;background:' + t.bottom_text_color + ';opacity:.5;display:inline-block;"></span>'
               +   '</div>'
               + '</div>'
               // name label
               + '<div style="background:#fff;padding:6px 8px;font-size:11px;font-weight:600;color:#374151;text-align:center;letter-spacing:.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'
               +   (active ? '<span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:' + t.accent_color + ';margin-right:4px;vertical-align:middle;"></span>' : '')
               +   t.name
               + '</div>'
               + '</div>';
        });
        grid.innerHTML = h;
    }

    function applyFooterTheme(key) {
        var t = FTHEMES[key];
        if (!t) return;
        ['bg', 'heading_color', 'text_color', 'link_color', 'link_hover_color', 'accent_color', 'bottom_bg', 'bottom_text_color'].forEach(function (k) {
            setStyleVal(k, t[k]);
        });
        var grad = document.getElementById('mxf-bg-gradient');
        if (grad) grad.value = t.bg_gradient || '';
        document.getElementById('mxf-theme').value = key;
        renderThemes();
        renderPreview();
    }

    /* ── Wizard ──────────────────────────────────────────────────────── */
    var wiz = { step: 0, layout: '4col', theme: 'midnight', data: {} };

    var WIZ_LAYOUTS = {
        '4col':     { name: '4 columns — Classic',  desc: 'About · Links · Contact · Social', cols: 4 },
        '3col':     { name: '3 columns — Compact',  desc: 'About · Links · Contact (social in bottom bar)', cols: 3 },
        '2col':     { name: '2 columns — Minimal',  desc: 'About · Links', cols: 2 },
        'centered': { name: 'Centered — Elegant',   desc: 'About + social icons, all centered', cols: 1 }
    };

    function wizSteps() { return ['Layout', 'Theme', 'Content', 'Bottom bar']; }

    function wizRender() {
        var steps = wizSteps();
        var prog = document.getElementById('mxf-wizard-progress');
        var body = document.getElementById('mxf-wizard-body');
        var back = document.getElementById('mxf-wizard-back');
        var next = document.getElementById('mxf-wizard-next');
        if (!prog || !body) return;

        prog.innerHTML = steps.map(function (sLabel, i) {
            return '<div style="flex:1;text-align:center;">'
                 + '<div style="height:4px;border-radius:2px;background:' + (i <= wiz.step ? '#667eea' : '#e5e7eb') + ';margin-bottom:5px;"></div>'
                 + '<span style="font-size:11px;color:' + (i === wiz.step ? '#374151' : '#9ca3af') + ';font-weight:' + (i === wiz.step ? '700' : '400') + ';">' + sLabel + '</span>'
                 + '</div>';
        }).join('');

        back.style.visibility = wiz.step === 0 ? 'hidden' : 'visible';
        next.textContent = wiz.step === steps.length - 1 ? '✓ Build my footer' : 'Next →';

        var h = '';
        if (wiz.step === 0) {
            h += '<p style="font-size:13px;color:#6b7280;margin-top:0;">How should your footer be organized?</p>';
            h += '<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">';
            Object.keys(WIZ_LAYOUTS).forEach(function (k) {
                var L = WIZ_LAYOUTS[k];
                var sel = wiz.layout === k;
                var colsMock = '';
                var n = k === 'centered' ? 1 : L.cols;
                // Only 4col/3col build a wide-first layout; 2col builds equal columns (see wizBuild).
                var wideFirst = (k === '4col' || k === '3col');
                for (var i = 0; i < n; i++) {
                    colsMock += '<div style="flex:' + (wideFirst && i === 0 ? '1.6' : '1') + ';background:#cbd5e1;border-radius:3px;height:34px;"></div>';
                }
                h += '<div class="mxf-wiz-layout" data-k="' + k + '" style="cursor:pointer;border:2px solid ' + (sel ? '#667eea' : '#e5e7eb') + ';border-radius:10px;padding:12px;">'
                   + '<div style="display:flex;gap:5px;margin-bottom:8px;' + (k === 'centered' ? 'justify-content:center;max-width:50%;margin-left:auto;margin-right:auto;' : '') + '">' + colsMock + '</div>'
                   + '<div style="font-size:12px;font-weight:700;color:#374151;">' + L.name + '</div>'
                   + '<div style="font-size:11px;color:#9ca3af;">' + L.desc + '</div>'
                   + '</div>';
            });
            h += '</div>';
        } else if (wiz.step === 1) {
            h += '<p style="font-size:13px;color:#6b7280;margin-top:0;">Pick a starting palette — every color stays editable.</p>';
            h += '<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;">';
            Object.keys(FTHEMES).forEach(function (key) {
                var t   = FTHEMES[key];
                var sel = wiz.theme === key;
                var bgCss  = t.bg_gradient ? 'background:' + t.bg_gradient + ';' : 'background:' + t.bg + ';';
                var border = sel ? '2px solid ' + t.accent_color : '2px solid #e5e7eb';
                var shadow = sel ? '0 0 0 3px ' + t.accent_color + '55' : 'none';
                h += '<div class="mxf-wiz-theme" data-k="' + key + '" title="' + t.name + '" style="cursor:pointer;border:' + border + ';border-radius:8px;overflow:hidden;box-shadow:' + shadow + ';transition:border-color .15s,box-shadow .15s;">'
                   // accent bar
                   + '<div style="height:3px;background:' + t.accent_color + ';"></div>'
                   // mini body — 3 column stubs via shared helper (compact mode)
                   + '<div style="' + bgCss + 'padding:7px 7px 5px;display:grid;grid-template-columns:1.3fr 1fr 1fr;gap:4px;">'
                   +   themeColStub(t, 65, [100, 85], t.text_color, false, true)
                   +   themeColStub(t, 55, [75, 65],  null,         false, true)
                   +   themeColStub(t, 60, [70, 60],  null,         false, true)
                   + '</div>'
                   // bottom bar
                   + '<div style="background:' + t.bottom_bg + ';padding:4px 7px;display:flex;align-items:center;justify-content:space-between;">'
                   +   '<div style="height:2px;width:35%;background:' + t.bottom_text_color + ';border-radius:2px;opacity:.6;"></div>'
                   +   '<div style="display:flex;gap:2px;">'
                   +     '<span style="width:5px;height:5px;border-radius:50%;background:' + t.bottom_text_color + ';opacity:.5;display:inline-block;"></span>'
                   +     '<span style="width:5px;height:5px;border-radius:50%;background:' + t.bottom_text_color + ';opacity:.5;display:inline-block;"></span>'
                   +     '<span style="width:5px;height:5px;border-radius:50%;background:' + t.bottom_text_color + ';opacity:.5;display:inline-block;"></span>'
                   +   '</div>'
                   + '</div>'
                   // name
                   + '<div style="font-size:10px;font-weight:600;color:#374151;text-align:center;padding:4px 6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;background:#fff;">'
                   +   (sel ? '<span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:' + t.accent_color + ';margin-right:3px;vertical-align:middle;"></span>' : '')
                   +   t.name + '</div>'
                   + '</div>';
            });
            h += '</div>';
        } else if (wiz.step === 2) {
            var d = wiz.data;
            h += '<p style="font-size:13px;color:#6b7280;margin-top:0;">Tell us about your site — we fill the footer for you. Everything is optional.</p>';
            h += '<table style="width:100%;border-collapse:collapse;">';
            var row = function (label, id, placeholder, type) {
                return '<tr><td style="padding:5px 8px 5px 0;font-size:12px;color:#374151;width:130px;">' + label + '</td>'
                     + '<td style="padding:5px 0;"><input type="' + (type || 'text') + '" id="mxf-wiz-' + id + '" value="' + esc(d[id] || '') + '" placeholder="' + placeholder + '" style="width:100%;"></td></tr>';
            };
            h += row('Company name', 'company', 'Acme Inc.');
            h += row('Tagline / About', 'tagline', 'We build amazing things since 2010.');
            h += row('Email', 'email', 'info@example.com', 'email');
            h += row('Phone', 'phone', '+39 02 1234567');
            h += row('Address', 'address', 'Via Roma 1, Milano');
            h += '</table>';
            h += '<div style="font-size:12px;font-weight:700;color:#374151;margin:12px 0 6px;">Social profiles (leave blank to skip)</div>';
            h += '<table style="width:100%;border-collapse:collapse;">';
            h += row('Facebook', 'facebook', 'https://facebook.com/…', 'url');
            h += row('Instagram', 'instagram', 'https://instagram.com/…', 'url');
            h += row('X (Twitter)', 'x', 'https://x.com/…', 'url');
            h += row('LinkedIn', 'linkedin', 'https://linkedin.com/company/…', 'url');
            h += row('YouTube', 'youtube', 'https://youtube.com/@…', 'url');
            h += '</table>';
        } else if (wiz.step === 3) {
            var d2 = wiz.data;
            var defCopy = '© {year} ' + (d2.company || 'Your Company') + '. All rights reserved.';
            h += '<p style="font-size:13px;color:#6b7280;margin-top:0;">Last touch: the bottom bar.</p>';
            h += '<table style="width:100%;border-collapse:collapse;">';
            h += '<tr><td style="padding:5px 8px 5px 0;font-size:12px;color:#374151;width:130px;">Copyright</td>'
               + '<td style="padding:5px 0;"><input type="text" id="mxf-wiz-copyright" value="' + esc(d2.copyright || defCopy) + '" style="width:100%;"></td></tr>';
            h += '</table>';
            h += '<div style="margin-top:10px;display:flex;flex-direction:column;gap:6px;font-size:13px;color:#374151;">';
            h += '<label><input type="checkbox" id="mxf-wiz-privacy" ' + (d2.privacy !== false ? 'checked' : '') + '> Add a “Privacy Policy” link</label>';
            h += '<label><input type="checkbox" id="mxf-wiz-terms" ' + (d2.terms ? 'checked' : '') + '> Add a “Terms & Conditions” link</label>';
            h += '<label><input type="checkbox" id="mxf-wiz-cookies" ' + (d2.cookies ? 'checked' : '') + '> Add a “Cookie Policy” link</label>';
            h += '</div>';
        }
        body.innerHTML = h;
    }

    function wizCollect() {
        var ids = ['company', 'tagline', 'email', 'phone', 'address', 'facebook', 'instagram', 'x', 'linkedin', 'youtube', 'copyright'];
        ids.forEach(function (id) {
            var el = document.getElementById('mxf-wiz-' + id);
            if (el) wiz.data[id] = el.value.trim();
        });
        ['privacy', 'terms', 'cookies'].forEach(function (id) {
            var el = document.getElementById('mxf-wiz-' + id);
            if (el) wiz.data[id] = el.checked;
        });
    }

    function wizBuild() {
        var d = wiz.data;
        var socials = [];
        ['facebook', 'instagram', 'x', 'linkedin', 'youtube'].forEach(function (n) {
            if (d[n]) socials.push({ network: n, url: d[n] });
        });

        var about = { type: 'about', title: d.company || 'About us', text: d.tagline || '' };
        var links = { type: 'links', title: 'Quick Links', items: [
            { label: 'Home',    url: '/',        target: '' },
            { label: 'About',   url: '',         target: '' },
            { label: 'Contact', url: '',         target: '' }
        ] };
        var contact = { type: 'contact', title: 'Contact', address: d.address || '', phone: d.phone || '', email: d.email || '' };
        var social  = { type: 'social', title: 'Follow Us', networks: socials };

        var cols = [];
        var showSocialBottom = false;
        if (wiz.layout === '4col') {
            cols = [about, links, contact, social];
        } else if (wiz.layout === '3col') {
            cols = [about, links, contact];
            if (socials.length) showSocialBottom = true;
        } else if (wiz.layout === '2col') {
            cols = [about, links];
            if (socials.length) showSocialBottom = true;
        } else { // centered
            cols = [Object.assign({}, about, { title: d.company || '' })];
            if (socials.length) cols.push({ type: 'social', title: '', networks: socials });
        }

        var bottomLinks = [];
        if (d.privacy !== false) bottomLinks.push({ label: 'Privacy Policy', url: '' });
        if (d.terms)   bottomLinks.push({ label: 'Terms & Conditions', url: '' });
        if (d.cookies) bottomLinks.push({ label: 'Cookie Policy', url: '' });

        state.columns = cols;
        state.layout  = wiz.layout === 'centered' ? 'centered'
                      : wiz.layout === '2col'     ? 'equal'
                      : 'wide-first';
        state.enabled = true;
        state.bottom  = {
            copyright:   d.copyright || ('© {year} ' + (d.company || 'Your Company') + '. All rights reserved.'),
            links:       bottomLinks,
            show_social: showSocialBottom ? '1' : '0',
            networks:    showSocialBottom ? socials : []
        };

        var enabledCb = document.getElementById('mxf-enabled');
        if (enabledCb) enabledCb.checked = true;
        var layoutSel = document.getElementById('mxf-layout');
        if (layoutSel) layoutSel.value = state.layout;
        var copyInput = document.getElementById('mxf-copyright');
        if (copyInput) copyInput.value = state.bottom.copyright;
        var bsCb = document.getElementById('mxf-bottom-social');
        if (bsCb) bsCb.checked = state.bottom.show_social === '1';

        applyFooterTheme(wiz.theme);
        refresh();
        wizClose();
        var pv = document.getElementById('menux-footer-preview');
        if (pv) pv.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    function wizOpen()  { wiz.step = 0; document.getElementById('mxf-wizard').style.display = 'flex'; wizRender(); }
    function wizClose() { document.getElementById('mxf-wizard').style.display = 'none'; }

    /* ── Events ──────────────────────────────────────────────────────── */
    function bindEvents() {
        var form = document.getElementById('menux-footer-form');
        if (form) form.addEventListener('submit', serialize);

        var enabledCb = document.getElementById('mxf-enabled');
        if (enabledCb) enabledCb.addEventListener('change', function () { state.enabled = this.checked; refreshLight(); });

        var layoutSel = document.getElementById('mxf-layout');
        if (layoutSel) layoutSel.addEventListener('change', function () { state.layout = this.value; refreshLight(); });

        var placementSel = document.getElementById('mxf-placement');
        var priorityWrap = document.getElementById('mxf-priority-wrap');
        if (placementSel) placementSel.addEventListener('change', function () {
            state.placement = this.value;
            if (priorityWrap) priorityWrap.style.display = this.value === 'auto' ? '' : 'none';
            serialize();
        });
        var prioInput = document.getElementById('mxf-priority');
        if (prioInput) prioInput.addEventListener('input', function () {
            state.auto_priority = this.value || '100';
            serialize();
        });

        var addCol = document.getElementById('mxf-add-col');
        if (addCol) addCol.addEventListener('click', function () {
            if (state.columns.length >= 6) { notify('Maximum 6 sections per footer.', 'error'); return; }
            state.columns.push({ type: 'links', title: 'New section', items: [{ label: '', url: '', target: '' }] });
            refresh();
        });

        var copyInput = document.getElementById('mxf-copyright');
        if (copyInput) {
            copyInput.value = state.bottom.copyright || '';
            copyInput.addEventListener('input', function () { state.bottom.copyright = this.value; refreshLight(); });
        }
        var bsCb = document.getElementById('mxf-bottom-social');
        if (bsCb) {
            bsCb.checked = state.bottom.show_social === '1';
            bsCb.addEventListener('change', function () { state.bottom.show_social = this.checked ? '1' : '0'; refreshLight(); });
        }
        var addBlink = document.getElementById('mxf-add-bottom-link');
        if (addBlink) addBlink.addEventListener('click', function () {
            if (state.bottom.links.length >= 6) return;
            state.bottom.links.push({ label: '', url: '' });
            renderBottomLinks(); refreshLight();
        });

        // Delegated events: columns builder
        var colsWrap = document.getElementById('mxf-cols');
        if (colsWrap) {
            colsWrap.addEventListener('input', onColsEdit);
            colsWrap.addEventListener('change', onColsEdit);
            colsWrap.addEventListener('click', onColsClick);
            // WordPress media library picker for logo/image fields
            colsWrap.addEventListener('click', function (e) {
                if (!e.target.classList.contains('mxf-media-pick')) return;
                e.preventDefault();
                var targetField = e.target.getAttribute('data-f');
                var card = e.target.closest('.mxf-col-card');
                if (!card || typeof wp === 'undefined' || !wp.media) return;
                var frame = wp.media({ title: 'Select Image', button: { text: 'Use this image' }, multiple: false });
                frame.on('select', function () {
                    var att = frame.state().get('selection').first().toJSON();
                    var input = card.querySelector('[data-f="' + targetField + '"]');
                    if (input) { input.value = att.url; input.dispatchEvent(new Event('input', { bubbles: true })); }
                });
                frame.open();
            });
        }
        var blWrap = document.getElementById('mxf-bottom-links');
        if (blWrap) {
            var onBl = function (e) {
                var row = e.target.closest('[data-bi]');
                if (!row) return;
                var i = parseInt(row.getAttribute('data-bi'), 10);
                var f = e.target.getAttribute('data-bf');
                if (f && state.bottom.links[i]) { state.bottom.links[i][f] = e.target.value; refreshLight(); }
            };
            blWrap.addEventListener('input', onBl);
            blWrap.addEventListener('click', function (e) {
                if (!e.target.classList.contains('mxf-del-blink')) return;
                var row = e.target.closest('[data-bi]');
                if (!row) return;
                state.bottom.links.splice(parseInt(row.getAttribute('data-bi'), 10), 1);
                renderBottomLinks(); refreshLight();
            });
        }

        // Style inputs → live preview
        document.querySelectorAll('.mxf-style').forEach(function (el) {
            el.addEventListener('input', renderPreview);
            el.addEventListener('change', renderPreview);
        });

        // Themes
        var themesGrid = document.getElementById('mxf-themes-grid');
        if (themesGrid) themesGrid.addEventListener('click', function (e) {
            var card = e.target.closest('.mxf-theme-card');
            if (card) applyFooterTheme(card.getAttribute('data-theme'));
        });

        // Ctrl+S / Cmd+S → save
        document.addEventListener('keydown', function (e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                var form = document.getElementById('menux-footer-form');
                if (!form) return;
                e.preventDefault();
                serialize();
                form.querySelector('[name="menux_footer_save"]').click();
            }
        });

        // Wizard
        document.getElementById('mxf-wizard-open').addEventListener('click', wizOpen);
        document.getElementById('mxf-wizard-close').addEventListener('click', wizClose);
        document.getElementById('mxf-wizard-back').addEventListener('click', function () {
            wizCollect();
            if (wiz.step > 0) { wiz.step--; wizRender(); }
        });
        document.getElementById('mxf-wizard-next').addEventListener('click', function () {
            wizCollect();
            if (wiz.step < wizSteps().length - 1) { wiz.step++; wizRender(); } else { wizBuild(); }
        });
        document.getElementById('mxf-wizard-body').addEventListener('click', function (e) {
            var lay = e.target.closest('.mxf-wiz-layout');
            if (lay) { wiz.layout = lay.getAttribute('data-k'); wizRender(); return; }
            var th = e.target.closest('.mxf-wiz-theme');
            if (th) { wiz.theme = th.getAttribute('data-k'); wizRender(); }
        });
    }

    function onColsEdit(e) {
        var card = e.target.closest('.mxf-col-card');
        if (!card) return;
        var ci = parseInt(card.getAttribute('data-ci'), 10);
        var col = state.columns[ci];
        if (!col) return;

        var f = e.target.getAttribute('data-f');
        if (f) {
            if (f === 'type' && e.target.value !== col.type) {
                // Reset type-specific data when switching type
                var prevTitle = col.title;
                var prevHideMobile = col.hide_mobile;
                state.columns[ci] = { type: e.target.value, title: prevTitle, hide_mobile: prevHideMobile };
                if (e.target.value === 'links')      state.columns[ci].items = [{ label: '', url: '', target: '' }];
                if (e.target.value === 'social')     state.columns[ci].networks = [{ network: 'facebook', url: '' }];
                if (e.target.value === 'hours')      state.columns[ci].lines = [''];
                if (e.target.value === 'newsletter') { state.columns[ci].placeholder = ''; state.columns[ci].button_text = 'Subscribe'; }
                refresh();
                return;
            }
            col[f] = e.target.type === 'checkbox' ? (e.target.checked ? '1' : '0') : e.target.value;
            refreshLight();
            return;
        }
        var lf = e.target.getAttribute('data-lf');
        if (lf) {
            var lrow = e.target.closest('[data-ii]');
            var ii = parseInt(lrow.getAttribute('data-ii'), 10);
            if (col.items && col.items[ii]) {
                col.items[ii][lf] = lf === 'target' ? (e.target.checked ? '_blank' : '') : e.target.value;
                refreshLight();
            }
            return;
        }
        var sf = e.target.getAttribute('data-sf');
        if (sf) {
            var srow = e.target.closest('[data-si]');
            var si = parseInt(srow.getAttribute('data-si'), 10);
            if (col.networks && col.networks[si]) { col.networks[si][sf] = e.target.value; refreshLight(); }
            return;
        }
        var hf = e.target.getAttribute('data-hf');
        if (hf) {
            var hrow = e.target.closest('[data-li]');
            var li = parseInt(hrow.getAttribute('data-li'), 10);
            if (col.lines) { col.lines[li] = e.target.value; refreshLight(); }
        }
    }

    function onColsClick(e) {
        var card = e.target.closest('.mxf-col-card');
        if (!card) return;
        var ci = parseInt(card.getAttribute('data-ci'), 10);
        var col = state.columns[ci];
        var cls = e.target.classList;

        if (cls.contains('mxf-col-del')) {
            if (!confirm('Remove this section?')) return;
            state.columns.splice(ci, 1); refresh();
        } else if (cls.contains('mxf-col-dup')) {
            if (state.columns.length >= 6) { notify('Maximum 6 sections per footer.', 'error'); return; }
            state.columns.splice(ci + 1, 0, JSON.parse(JSON.stringify(col))); refresh();
        } else if (cls.contains('mxf-col-up') && ci > 0) {
            state.columns.splice(ci - 1, 0, state.columns.splice(ci, 1)[0]); refresh();
        } else if (cls.contains('mxf-col-down') && ci < state.columns.length - 1) {
            state.columns.splice(ci + 1, 0, state.columns.splice(ci, 1)[0]); refresh();
        } else if (cls.contains('mxf-add-link')) {
            col.items = col.items || []; if (col.items.length < 20) col.items.push({ label: '', url: '', target: '' }); refresh();
        } else if (cls.contains('mxf-del-link')) {
            var ii = parseInt(e.target.closest('[data-ii]').getAttribute('data-ii'), 10);
            col.items.splice(ii, 1); refresh();
        } else if (cls.contains('mxf-add-soc')) {
            col.networks = col.networks || []; if (col.networks.length < 14) col.networks.push({ network: 'facebook', url: '' }); refresh();
        } else if (cls.contains('mxf-del-soc')) {
            var si = parseInt(e.target.closest('[data-si]').getAttribute('data-si'), 10);
            col.networks.splice(si, 1); refresh();
        } else if (cls.contains('mxf-add-hour')) {
            col.lines = col.lines || []; if (col.lines.length < 10) col.lines.push(''); refresh();
        } else if (cls.contains('mxf-del-hour')) {
            var li = parseInt(e.target.closest('[data-li]').getAttribute('data-li'), 10);
            col.lines.splice(li, 1); refresh();
        }
    }

    /* ── Page picker (autocomplete for link URL inputs) ─────────────────
       Triggered when the user focuses or types in a [data-lf="url"] field
       inside the footer builder. Searches WordPress pages/posts via the
       REST API; does nothing if the REST root is unavailable.              */
    var _pp = { el: null, timer: null, active: null };

    function ppDropdown() {
        if (_pp.el) return _pp.el;
        var d = document.createElement('div');
        d.id = 'mxf-pp';
        d.style.cssText = 'position:absolute;z-index:99999;background:#fff;border:1px solid #c3c4c7;border-radius:6px;'
                        + 'box-shadow:0 4px 16px rgba(0,0,0,.13);max-height:210px;overflow-y:auto;display:none;';
        document.body.appendChild(d);
        document.addEventListener('mousedown', function(e) {
            if (_pp.el && !_pp.el.contains(e.target) && e.target !== _pp.active) ppHide();
        });
        _pp.el = d;
        return d;
    }

    function ppHide() { if (_pp.el) _pp.el.style.display = 'none'; _pp.active = null; }

    function ppPosition(input) {
        var r = input.getBoundingClientRect();
        var d = ppDropdown();
        d.style.left = (r.left + window.scrollX) + 'px';
        d.style.top  = (r.bottom + window.scrollY + 2) + 'px';
        d.style.width = Math.max(r.width, 260) + 'px';
    }

    function ppFetch(input, term) {
        if (!REST_ROOT) return;
        clearTimeout(_pp.timer);
        _pp.timer = setTimeout(function () {
            fetch(REST_ROOT + 'wp/v2/search?search=' + encodeURIComponent(term) + '&per_page=8&type=post&subtype=any&_fields=id,title,url')
                .then(function (r) { return r.ok ? r.json() : []; })
                .then(function (rows) { if (_pp.active === input) ppShow(input, rows); })
                .catch(function () {});
        }, 220);
    }

    function ppShow(input, rows) {
        var d = ppDropdown();
        ppPosition(input);
        if (!rows || !rows.length) { d.style.display = 'none'; return; }
        d.innerHTML = rows.map(function (r) {
            var title = r.title || '(no title)';
            var href  = r.url  || '';
            return '<div class="mxf-pp-item" data-url="' + esc(href) + '">'
                 + '<strong style="display:block;font-size:12px;color:#1e1e1e;">' + esc(title) + '</strong>'
                 + '<span style="display:block;font-size:11px;color:#9ca3af;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + esc(href) + '</span>'
                 + '</div>';
        }).join('');
        d.querySelectorAll('.mxf-pp-item').forEach(function (item) {
            item.style.cssText = 'padding:7px 12px;cursor:pointer;border-bottom:1px solid #f3f4f6;';
            item.addEventListener('mouseenter', function () { item.style.background = '#f0f0ff'; });
            item.addEventListener('mouseleave', function () { item.style.background = ''; });
            item.addEventListener('mousedown',  function (e) {
                e.preventDefault();
                if (_pp.active) {
                    _pp.active.value = item.dataset.url;
                    _pp.active.dispatchEvent(new Event('input', { bubbles: true }));
                }
                ppHide();
            });
        });
        d.style.display = 'block';
    }

    // Event delegation — works on dynamically rendered link rows
    document.addEventListener('focusin', function (e) {
        if (!e.target.matches('[data-lf="url"],[data-bf="url"]')) return;
        _pp.active = e.target;
        var val = e.target.value;
        if (val && !val.startsWith('http') && val.length >= 2) ppFetch(e.target, val);
    });
    document.addEventListener('input', function (e) {
        if (!e.target.matches('[data-lf="url"],[data-bf="url"]')) return;
        _pp.active = e.target;
        var val = e.target.value;
        if (val.length >= 2 && !val.startsWith('http')) { ppFetch(e.target, val); }
        else { ppHide(); }
    });
    document.addEventListener('focusout', function (e) {
        if (e.target.matches('[data-lf="url"],[data-bf="url"]')) setTimeout(ppHide, 150);
    });

    /* ── Init ────────────────────────────────────────────────────────── */
    document.addEventListener('DOMContentLoaded', function () {
        bindEvents();
        renderThemes();
        refresh();
        // First visit with an empty footer → guide the user straight into the wizard.
        if (!state.columns.length) wizOpen();
    });
})();
