/* global jQuery, BlazeAffiliationDebug */
(function () {
    if (!window.BlazeAffiliationDebug || !Array.isArray(window.BlazeAffiliationDebug.replacements)) {
        return;
    }

    const child = (window.BlazeAffiliationDebug && window.BlazeAffiliationDebug.meta_child && Array.isArray(window.BlazeAffiliationDebug.meta_child.replacements)) ? window.BlazeAffiliationDebug.meta_child.replacements : [];
    const replacements = Array.isArray(window.BlazeAffiliationDebug.replacements)
        ? window.BlazeAffiliationDebug.replacements.concat(child)
        : child;

    const btn = document.getElementById('blz-aff-debug-btn');
    if (!btn) return;

    injectStyles();
    enhanceButton(btn);

    let active = false;
    let overlay;
    let mouseHandler;
    let clickHandler;
    let lastHoverMatch = null; // { element, replacement }
    const elementToReplacement = new WeakMap();
    const elementToLabel = new WeakMap();

    // Pre-index DOM elements that correspond to injected formats
    buildIndex();

    function createOverlay() {
        const el = document.createElement('div');
        el.id = 'blz-aff-debug-overlay';
        Object.assign(el.style, {
            position: 'fixed',
            inset: '0',
            background: 'transparent',
            zIndex: 2147483646,
            pointerEvents: 'none'
        });
        document.body.appendChild(el);
        return el;
    }

    function highlight(el) {
        const rect = el.getBoundingClientRect();
        overlay.innerHTML = '';
        const box = document.createElement('div');
        box.className = 'blz-aff-debug-highlight';
        box.style.left = rect.left + 'px';
        box.style.top = rect.top + 'px';
        box.style.width = rect.width + 'px';
        box.style.height = rect.height + 'px';

        const label = document.createElement('div');
        label.className = 'blz-aff-debug-highlight-label';
        const explicit = el.dataset ? (el.dataset.blzAffLabel || '') : '';
        const mapped = elementToLabel.get(el) || '';
        const fallback = el.tagName.toLowerCase();
        label.textContent = explicit || mapped || fallback;

        box.appendChild(label);
        overlay.appendChild(box);
    }

    function findReplacementForTarget(target) {
        // Prefer matching the replacement markup that was injected into the page.
        const outer = target.outerHTML || '';
        for (const r of replacements) {
            if (r && typeof r.markup === 'string' && outer.includes(r.markup.trim().slice(0, 80))) {
                return r;
            }
        }
        // Fallback to original html snippet
        for (const r of replacements) {
            if (r && typeof r.html === 'string' && outer.includes(r.html.trim().slice(0, 80))) {
                return r;
            }
        }
        const text = (target.textContent || '').trim();
        if (text) {
            for (const r of replacements) {
                if (typeof r.html === 'string' && r.html.includes(text.slice(0, 60))) {
                    return r;
                }
            }
        }
        return null;
    }

    function findClosestReplacement(target, maxDepth = 6) {
        let el = target;
        let depth = 0;
        while (el && depth <= maxDepth) {
            if (el.dataset && el.dataset.blzAffFormat === '1') {
                const r = elementToReplacement.get(el);
                if (r) return { element: el, replacement: r };
            }
            el = el.parentElement;
            depth++;
        }
        return null;
    }

    function buildIndex() {
        try {
            for (const r of replacements) {
                if (!r || typeof r.markup !== 'string') continue;
                const markup = r.markup.trim();
                if (!markup) continue;

                const tagMatch = markup.match(/<([a-zA-Z0-9_-]+)/);
                const clsMatch = markup.match(/class=["']([^"']+)["']/);
                let baseSelector = '*';
                if (tagMatch) {
                    baseSelector = tagMatch[1];
                    if (clsMatch) {
                        const classes = clsMatch[1].trim().split(/\s+/).filter(Boolean);
                        if (classes.length) baseSelector += '.' + classes.map(cssEscape).join('.');
                    }
                }

                // Special selectors for affiliation_table formats
                const specialSelectors = [];
                if (/rating-card/.test(markup)) {
                    specialSelectors.push('ul.rating-card', '.rating-card');
                }
                if (/affiliation[_-]?table/.test(markup)) {
                    specialSelectors.push('table.affiliation_table', 'table.affiliation-table', '.affiliation_table', '.affiliation-table');
                }
                if (/aftable_link/.test(markup)) {
                    specialSelectors.push('.aftable_link');
                }

                let candidates = [];
                try {
                    candidates = Array.from(document.querySelectorAll(baseSelector));
                } catch (_) {
                    candidates = [];
                }
                for (const sel of specialSelectors) {
                    try {
                        candidates = candidates.concat(Array.from(document.querySelectorAll(sel)));
                    } catch (_) { /* ignore */ }
                }
                if (candidates.length === 0) {
                    candidates = Array.from(document.querySelectorAll('*'));
                }

                const snippet = normalizeHtml(markup).slice(0, 300);
                const found = candidates.find(el => normalizeHtml(el.outerHTML || '').includes(snippet));
                if (found) {
                    const container = found.closest('ul.rating-card, .rating-card, table.affiliation_table, table.affiliation-table, .affiliation_table, .affiliation-table') || found;
                    container.dataset.blzAffFormat = '1';
                    if (!elementToReplacement.has(container)) {
                        elementToReplacement.set(container, r);
                    }
                    const label = resolveFormatLabel(r, container, markup);
                    if (label) {
                        container.dataset.blzAffLabel = label;
                        elementToLabel.set(container, label);
                    }
                }
            }
        } catch (_) {
            // ignore indexing errors
        }
    }

    function normalizeHtml(str) {
        return String(str)
            .replace(/\s+/g, ' ')
            .replace(/>\s+</g, '><')
            .trim();
    }

    function resolveFormatLabel(repl, el, markup) {
        if (repl) {
            if (typeof repl.name === 'string' && repl.name) return repl.name;
            if (typeof repl.format === 'string' && repl.format) return repl.format;
            if (typeof repl.type === 'string' && repl.type) return repl.type;
        }
        const html = (markup || '').toLowerCase();
        const classList = (el.classList ? Array.from(el.classList) : []).join(' ').toLowerCase();
        if (html.includes('affiliation_table') || html.includes('affiliation-table') || classList.includes('affiliation_table') || classList.includes('affiliation-table')) return 'Affiliation table';
        if (html.includes('rating-card') || classList.includes('rating-card')) return 'Rating card';
        if (classList.includes('aftable_link') || html.includes('aftable_link')) return 'Affiliation table link';
        return 'Formato affiliazione';
    }

    function cssEscape(str) {
        try { return CSS && CSS.escape ? CSS.escape(str) : str.replace(/[^a-zA-Z0-9_-]/g, '\\$&'); } catch (_) { return str; }
    }

    function showPopup(repl) {
        const wrap = document.createElement('div');
        wrap.className = 'blz-aff-debug-wrap light';

        const header = document.createElement('div');
        header.className = 'blz-aff-debug-header';
        header.innerHTML = '<div class="blz-aff-debug-title">\n<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/></svg> Affiliation Debug</div>';

        const close = document.createElement('button');
        close.className = 'blz-aff-debug-close';
        close.setAttribute('aria-label', 'Chiudi');
        close.innerHTML = '&#10005;';
        close.addEventListener('click', function () { wrap.remove(); });
        header.appendChild(close);

        const meta = document.createElement('div');
        meta.className = 'blz-aff-debug-meta';
        meta.textContent = 'Selezionato formato sostituito';

        const grid = document.createElement('div');
        grid.className = 'blz-aff-debug-grid';

        const colLeft = document.createElement('div');
        colLeft.className = 'col';
        const colRight = document.createElement('div');
        colRight.className = 'col';

        const actions = (text) => {
            const bar = document.createElement('div');
            bar.className = 'blz-aff-debug-actions';
            const copy = document.createElement('button');
            copy.textContent = 'Copia';
            copy.addEventListener('click', function () {
                if (navigator.clipboard) navigator.clipboard.writeText(text);
            });
            bar.appendChild(copy);
            return bar;
        };

        const preOrig = document.createElement('pre');
        preOrig.className = 'code';
        preOrig.textContent = repl && repl.html ? repl.html : '';
        const preRepl = document.createElement('pre');
        preRepl.className = 'code';
        preRepl.textContent = repl && repl.markup ? repl.markup : '';

        const headLeft = document.createElement('div');
        headLeft.className = 'blz-aff-debug-subtitle';
        headLeft.textContent = 'Originale';
        const headRight = document.createElement('div');
        headRight.className = 'blz-aff-debug-subtitle';
        headRight.textContent = 'Replacement';

        colLeft.appendChild(headLeft);
        colLeft.appendChild(actions(preOrig.textContent));
        colLeft.appendChild(preOrig);
        colRight.appendChild(headRight);
        colRight.appendChild(actions(preRepl.textContent));
        colRight.appendChild(preRepl);

        grid.appendChild(colLeft);
        grid.appendChild(colRight);

        wrap.appendChild(header);
        wrap.appendChild(meta);
        wrap.appendChild(grid);
        document.body.appendChild(wrap);
    }

    function escapeHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    function enable() {
        if (active) return;
        active = true;
        overlay = createOverlay();
        document.body.style.cursor = 'not-allowed';
        mouseHandler = function (ev) {
            const target = ev.target;
            const match = findClosestReplacement(target);
            lastHoverMatch = match;
            if (match) {
                document.body.style.cursor = 'crosshair';
                highlight(match.element);
            } else {
                document.body.style.cursor = 'not-allowed';
                if (overlay) overlay.innerHTML = '';
            }
        };
        document.addEventListener('mousemove', mouseHandler, true);
        clickHandler = function onClick(ev) {
            const match = lastHoverMatch || findClosestReplacement(ev.target);
            if (match && match.replacement) {
                ev.preventDefault();
                ev.stopPropagation();
                showPopup(match.replacement);
                disable();
            } else {
                // Allow normal page interaction; keep inspector active
                toast('Seleziona un formato valido');
            }
        };
        document.addEventListener('click', clickHandler, true);
        setActiveUI(true);
    }

    function disable() {
        active = false;
        if (overlay) overlay.remove();
        overlay = null;
        document.body.style.cursor = '';
        if (mouseHandler) {
            document.removeEventListener('mousemove', mouseHandler, true);
            mouseHandler = null;
        }
        if (clickHandler) {
            document.removeEventListener('click', clickHandler, true);
            clickHandler = null;
        }
        lastHoverMatch = null;
        setActiveUI(false);
    }

    btn.addEventListener('click', function () {
        if (active) {
            disable();
        } else {
            enable();
        }
    });

    function enhanceButton(button) {
        button.className = 'blz-aff-debug-btn';
        button.innerHTML = '<span class="icon" aria-hidden="true">\n<svg width="17" height="17" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="2"/><line x1="16.5" y1="16.5" x2="22" y2="22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>\n</span>';
        // Draggable
        let sx = 0, sy = 0, startRight = 16, startBottom = 16;
        button.addEventListener('mousedown', function (e) {
            if (e.button !== 0) return;
            e.preventDefault();
            sx = e.clientX; sy = e.clientY;
            const cs = window.getComputedStyle(button);
            startRight = parseInt(cs.right, 10);
            startBottom = parseInt(cs.bottom, 10);
            function move(ev) {
                const dx = ev.clientX - sx;
                const dy = ev.clientY - sy;
                button.style.right = Math.max(8, startRight - dx) + 'px';
                button.style.bottom = Math.max(8, startBottom - dy) + 'px';
            }
            function up() {
                document.removeEventListener('mousemove', move);
                document.removeEventListener('mouseup', up);
            }
            document.addEventListener('mousemove', move);
            document.addEventListener('mouseup', up);
        });
    }

    function setActiveUI(on) {
        if (!btn) return;
        btn.setAttribute('aria-pressed', on ? 'true' : 'false');
        if (on) btn.classList.add('active'); else btn.classList.remove('active');
    }

    function toast(message) {
        const el = document.createElement('div');
        el.className = 'blz-aff-debug-toast';
        el.textContent = message;
        document.body.appendChild(el);
        setTimeout(() => el.classList.add('show'), 10);
        setTimeout(() => {
            el.classList.remove('show');
            setTimeout(() => el.remove(), 250);
        }, 2200);
    }

    function injectStyles() {
        if (document.getElementById('blz-aff-debug-style')) return;
        const css = `
        #blz-aff-debug-btn.blz-aff-debug-btn{
            position:fixed;right:16px;bottom:16px;z-index:2147483647;
            display:inline-flex;align-items:center;justify-content:center;
            width:44px;height:44px;
            padding:0;border-radius:50%;border:1px solid rgba(0,0,0,.18);
            color:#fff;background:linear-gradient(135deg,#e53935,#b71c1c);cursor:pointer;
            font:600 13px/1 system-ui,-apple-system,Segoe UI,Roboto,Arial;letter-spacing:.2px;
            box-shadow:0 10px 20px rgba(0,0,0,.18), 0 2px 6px rgba(0,0,0,.12);
            transition:transform .12s ease, box-shadow .2s ease, opacity .2s ease;
        }
        #blz-aff-debug-btn.blz-aff-debug-btn.active{ background:linear-gradient(135deg,#2e7d32,#1b5e20); }
        #blz-aff-debug-btn.blz-aff-debug-btn:hover{ transform:translateY(-1px); box-shadow:0 12px 24px rgba(0,0,0,.2), 0 3px 8px rgba(0,0,0,.12); }
        #blz-aff-debug-btn .icon{ display:inline-flex; color:#fff }

        #blz-aff-debug-overlay .blz-aff-debug-highlight{ position:absolute;border:2px solid #ca2622cc;border-radius:8px;box-shadow:0 0 0 3px rgba(202,38,34,.18) inset;}
        #blz-aff-debug-overlay .blz-aff-debug-highlight-label{ position:absolute;right:0;top:-28px;background:#ca2622cc;color:#fff;font:600 11px system-ui;padding:4px 8px;border-radius:6px;box-shadow:0 6px 16px rgba(0,0,0,.25);}

        .blz-aff-debug-wrap{ position:fixed; right:16px; bottom:72px; width:min(92vw, 960px); max-height:75vh; overflow:auto; z-index:2147483647; background:#ffffff; color:#1e293b; border:1px solid #e2e8f0; border-radius:12px; box-shadow:0 16px 44px rgba(0,0,0,.18); animation:blzFadeIn .16s ease; }
        .blz-aff-debug-wrap.light{ background:#ffffff }
        .blz-aff-debug-header{ display:flex; align-items:center; justify-content:space-between; padding:12px 14px; border-bottom:1px solid #e2e8f0; background:linear-gradient(180deg,#f8fafc,#ffffff); position:sticky; top:0; z-index:1; }
        .blz-aff-debug-title{ display:flex; align-items:center; gap:8px; font:600 14px system-ui; color:#0f172a; }
        .blz-aff-debug-close{ background:#ffffff; color:#0f172a; border:1px solid #cbd5e1; padding:6px 10px; border-radius:8px; cursor:pointer; }
        .blz-aff-debug-close:hover{ background:#f1f5f9 }
        .blz-aff-debug-meta{ padding:10px 14px; font:500 12px system-ui; color:#475569; border-bottom:1px dashed #e2e8f0; }
        .blz-aff-debug-grid{ display:grid; grid-template-columns:1fr 1fr; gap:0; }
        .blz-aff-debug-grid .col{ padding:12px; border-right:1px solid #f1f5f9 }
        .blz-aff-debug-grid .col:last-child{ border-right:0 }
        .blz-aff-debug-subtitle{ font:700 12px system-ui; color:#0f172a; margin:4px 0 8px }
        .blz-aff-debug-actions{ display:flex; justify-content:flex-end; gap:8px; margin:6px 0 }
        .blz-aff-debug-actions > button{ background:#ffffff; color:#0f172a; border:1px solid #cbd5e1; padding:6px 10px; border-radius:8px; cursor:pointer; }
        .blz-aff-debug-actions > button:hover{ background:#f1f5f9 }
        pre.code{ white-space:pre-wrap; background:#f8fafc; color:#0f172a; padding:12px; border-radius:8px; border:1px solid #e2e8f0; overflow:auto; }
        @keyframes blzFadeIn{ from{ opacity:0; transform:translateY(6px) } to{ opacity:1; transform:none } }
        .blz-aff-debug-toast{ position:fixed; left:50%; transform:translate(-50%,10px); bottom:28px; background:rgba(30,34,45,.95); color:#fff; border:1px solid #2b3142; padding:8px 12px; border-radius:10px; z-index:2147483647; opacity:0; transition:opacity .2s ease, transform .2s ease; font:600 12px system-ui; box-shadow:0 8px 24px rgba(0,0,0,.3) }
        .blz-aff-debug-toast.show{ opacity:1; transform:translate(-50%,0) }
        `;
        const tag = document.createElement('style');
        tag.id = 'blz-aff-debug-style';
        tag.textContent = css;
        document.head.appendChild(tag);
    }
})();


