
(function(){
    'use strict';

    
    var trigger = document.getElementById('instagent-help-trigger');
    var panel   = document.getElementById('instagent-help-panel');
    var closeBtn= document.getElementById('instagent-help-close');
    var msgsEl  = document.getElementById('instagent-help-messages');
    var inputEl = document.getElementById('instagent-help-input');
    var sendBtn = document.getElementById('instagent-help-send');
    var ctxRow  = document.getElementById('instagent-help-context');
    var ctxVal  = document.getElementById('instagent-help-context-value');

    if (!trigger || !panel) return;  

    var SUGGESTIONS = [
        'How do I make a cinematic hero?',
        'What does Padding Top do on a section?',
        'When should I use Page mode vs Scene mode?',
        'How do I make a heading with hollow letters?'
    ];

    
    var inFlight = false;

    
    function readEditorContext() {
        var ctx = {
            page_mode:        '',
            selected_block:   '',
            active_tab:       '',
            selected_control: '',
            page_slug:        ''
        };

        
        var selType = window.selectedElementType || '';
        if (selType) ctx.selected_block = String(selType);

        
        var activeStab = document.querySelector('.impulse-section-tab.active[data-stab]');
        if (activeStab) ctx.active_tab = activeStab.getAttribute('data-stab') || '';

        
        if (window.Impulse && Impulse.page) {
            ctx.page_mode = 'scene';
            if (Impulse.page.slug) ctx.page_slug = String(Impulse.page.slug);
        }

        return ctx;
    }

    function renderContextBar() {
        var ctx = readEditorContext();
        var bits = [];
        if (ctx.selected_block) bits.push('Block: <strong>' + esc(ctx.selected_block) + '</strong>');
        if (ctx.active_tab)     bits.push('Tab: <strong>' + esc(ctx.active_tab) + '</strong>');
        if (ctx.page_mode)      bits.push('Mode: <strong>' + esc(ctx.page_mode) + '</strong>');
        if (bits.length) {
            ctxRow.style.display = 'flex';
            ctxVal.innerHTML = bits.join('  ·  ');
        } else {
            ctxRow.style.display = 'none';
        }
    }

    
    function openPanel() {
        renderContextBar();
        panel.classList.add('open');
        if (msgsEl.children.length === 0) renderEmpty();
        setTimeout(function(){ inputEl.focus(); }, 50);
    }
    function closePanel() {
        panel.classList.remove('open');
    }

    trigger.addEventListener('click', function() {
        panel.classList.contains('open') ? closePanel() : openPanel();
    });
    closeBtn.addEventListener('click', closePanel);

    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && panel.classList.contains('open')) closePanel();
    });

    
    function renderEmpty() {
        msgsEl.innerHTML = '';
        var wrap = document.createElement('div');
        wrap.className = 'instagent-help-empty';
        wrap.innerHTML =
            '<div class="heading">Ask Instagent.</div>' +
            '<div class="body">We answer from the Instinctor knowledge base. Direct, no fluff.</div>' +
            '<div class="suggestions"></div>';
        var sugs = wrap.querySelector('.suggestions');
        SUGGESTIONS.forEach(function(s) {
            var btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'suggestion';
            btn.textContent = s;
            btn.addEventListener('click', function() {
                inputEl.value = s;
                send();
            });
            sugs.appendChild(btn);
        });
        msgsEl.appendChild(wrap);
    }

    
    function send() {
        if (inFlight) return;
        var q = (inputEl.value || '').trim();
        if (!q) return;

        
        var empty = msgsEl.querySelector('.instagent-help-empty');
        if (empty) empty.remove();

        
        var userMsg = document.createElement('div');
        userMsg.className = 'instagent-help-msg user';
        userMsg.textContent = q;
        msgsEl.appendChild(userMsg);

        inputEl.value = '';
        inputEl.style.height = '36px';
        scrollDown();

        
        var typing = document.createElement('div');
        typing.className = 'instagent-help-typing';
        typing.innerHTML = '<span></span><span></span><span></span>';
        msgsEl.appendChild(typing);
        scrollDown();

        inFlight = true;
        sendBtn.disabled = true;

        var ctx = readEditorContext();
        var fd = new FormData();
        fd.append('action', 'instinctor_help_ask');
        fd.append('question', q);
        Object.keys(ctx).forEach(function(k) { fd.append(k, ctx[k]); });

        fetch(window.Impulse && window.Impulse.ajaxUrl ? window.Impulse.ajaxUrl : '/wp-admin/admin-ajax.php', {
            method: 'POST',
            body: fd,
            credentials: 'same-origin'
        })
        .then(function(r){ return r.json(); })
        .then(function(d) {
            typing.remove();
            inFlight = false;
            sendBtn.disabled = false;
            if (d && d.success && d.answer) {
                appendBotAnswer(d.answer, d.sources || []);
            } else {
                appendBotAnswer(d && d.message ? d.message
                    : "We couldn't answer that. Try again, or open Settings → Contact Support to reach our team.", []);
            }
        })
        .catch(function(err) {
            typing.remove();
            inFlight = false;
            sendBtn.disabled = false;
            appendBotAnswer("We couldn't reach the help service. Check your connection and try again.", []);
        });
    }

    function appendBotAnswer(answer, sources) {
        var bot = document.createElement('div');
        bot.className = 'instagent-help-msg bot';
        bot.innerHTML = renderMarkdown(answer);
        if (sources && sources.length) {
            var sEl = document.createElement('div');
            sEl.className = 'instagent-help-sources';
            sEl.innerHTML = '<span class="label">Sources</span>' + sources.map(esc).join(' · ');
            bot.appendChild(sEl);
        }
        msgsEl.appendChild(bot);
        scrollDown();
    }

    sendBtn.addEventListener('click', send);
    inputEl.addEventListener('keydown', function(e) {
        
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            send();
        }
    });

    
    inputEl.addEventListener('input', function() {
        inputEl.style.height = '36px';
        var h = Math.min(120, inputEl.scrollHeight);
        inputEl.style.height = h + 'px';
    });

    function scrollDown() {
        msgsEl.scrollTop = msgsEl.scrollHeight;
    }


    

    function renderMarkdown(md) {
        var lines = String(md).replace(/\r\n?/g, '\n').split('\n');
        var html = '';
        var inOL = false, inUL = false;
        function closeLists() {
            if (inOL) { html += '</ol>'; inOL = false; }
            if (inUL) { html += '</ul>'; inUL = false; }
        }

        var paraBuf = [];
        function flushPara() {
            if (paraBuf.length) {
                html += '<p>' + inlineMd(paraBuf.join(' ')) + '</p>';
                paraBuf = [];
            }
        }

        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            var olm = line.match(/^\s*(\d+)\.\s+(.+)$/);
            var ulm = line.match(/^\s*[-*]\s+(.+)$/);
            if (olm) {
                flushPara();
                if (!inOL) { closeLists(); html += '<ol>'; inOL = true; }
                html += '<li>' + inlineMd(olm[2]) + '</li>';
            } else if (ulm) {
                flushPara();
                if (!inUL) { closeLists(); html += '<ul>'; inUL = true; }
                html += '<li>' + inlineMd(ulm[1]) + '</li>';
            } else if (line.trim() === '') {
                flushPara();
                closeLists();
            } else {
                if (inOL || inUL) { closeLists(); }
                paraBuf.push(line.trim());
            }
        }
        flushPara();
        closeLists();
        return html;
    }

    function inlineMd(s) {
        
        s = esc(s);
        
        s = s.replace(/\*\*([^\*]+)\*\*/g, '<strong>$1</strong>');
        
        s = s.replace(/(^|\W)\*([^\*]+)\*(?=\W|$)/g, '$1<em>$2</em>');
        
        s = s.replace(/`([^`]+)`/g, '<code>$1</code>');
        return s;
    }

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