(function(){
'use strict';

var C = window.cupChat;
if (!C) return;

// ─── DOM refs ───
var root   = document.getElementById('cup-chatbot');
var fab    = document.getElementById('cup-fab');
var win    = document.getElementById('cup-window');
var body   = document.getElementById('cup-body');
var msgBox = document.getElementById('cup-messages');
var input  = document.getElementById('cup-input');
var send   = document.getElementById('cup-send');
var minBtn = document.getElementById('cup-minimize');
var avatar = document.getElementById('cup-avatar');
var hname  = document.getElementById('cup-hname');
var hsub   = document.getElementById('cup-hsub');
var powered= document.getElementById('cup-powered');

// ─── State ───
var sessionId = sessionStorage.getItem('cup_sid') || crypto.randomUUID();
sessionStorage.setItem('cup_sid', sessionId);
var history = []; // multi-turn conversation
var isOpen  = false;
var loading = false;
var initialized = false;

// Shown instead of an empty bubble when the backend returns no answer text.
var CUP_EMPTY_ANSWER_MSG = 'Mi dispiace, non sono riuscito a generare una risposta. Riprova.';

// ─── Init Customization ───
root.classList.add('pos-' + (C.position || 'bottom-right'));

// CSS variables
var style = root.style;
if (C.colorPrimary)    style.setProperty('--cup-primary', C.colorPrimary);
if (C.colorGradient)   style.setProperty('--cup-gradient', C.colorGradient);
if (C.colorBg)         style.setProperty('--cup-bg', C.colorBg);
if (C.colorBotBubble)  style.setProperty('--cup-bot-bubble', C.colorBotBubble);
if (C.colorUserBubble) style.setProperty('--cup-user-bubble', C.colorUserBubble);
if (C.fabBgColor)      style.setProperty('--cup-fab-bg', C.fabBgColor);
if (C.fabIconColor)    style.setProperty('--cup-fab-icon', C.fabIconColor);
if (C.headerIconColor) style.setProperty('--cup-header-icon', C.headerIconColor);
if (C.sendBgColor)     style.setProperty('--cup-send-bg', C.sendBgColor);
if (C.sendIconColor)   style.setProperty('--cup-send-icon', C.sendIconColor);
if (C.suggestionHoverBg)    style.setProperty('--cup-suggestion-hover-bg', C.suggestionHoverBg);
if (C.suggestionHoverColor) style.setProperty('--cup-suggestion-hover-color', C.suggestionHoverColor);

// Force icon colors directly on elements (bypass any CSS specificity issues from theme)
var fabColor  = C.fabIconColor || '#FFFFFF';
var headColor = C.headerIconColor || '#FFFFFF';
var sendColor = C.sendIconColor || '#FFFFFF';
fab.querySelectorAll('svg').forEach(function(s){ s.style.cssText = 'color:'+fabColor+'!important;stroke:'+fabColor+'!important'; });
document.getElementById('cup-minimize').querySelectorAll('svg').forEach(function(s){ s.style.cssText = 'color:'+headColor+'!important;stroke:'+headColor+'!important'; });
document.getElementById('cup-send').querySelectorAll('svg').forEach(function(s){ s.style.cssText = 'color:'+sendColor+'!important;fill:'+sendColor+'!important'; });
if (C.fontFamily)      style.setProperty('--cup-font', C.fontFamily);
if (C.borderRadius)    style.setProperty('--cup-radius', C.borderRadius + 'px');
if (C.widgetWidth)     style.setProperty('--cup-width', C.widgetWidth + 'px');
if (C.widgetHeight)    style.setProperty('--cup-height', C.widgetHeight + 'px');

// Header
hname.textContent = C.botName || 'CUP Bot';
hsub.textContent  = C.headerSubtitle || 'Online';
input.placeholder = C.placeholder || 'Scrivi la tua domanda...';

// Avatar
if (C.avatar) {
    var img = document.createElement('img');
    img.src = C.avatar;
    img.alt = C.botName || 'Bot';
    avatar.appendChild(img);
} else {
    avatar.textContent = '🍕';
}

// Powered by
if (C.showPoweredBy !== false) {
    var pbText = C.poweredByText || 'Conosco un Posto';
    var pbUrl  = C.poweredByUrl || 'https://retrinastiyan.lat';
    powered.innerHTML = 'Powered by <a href="' + pbUrl + '" target="_blank" rel="noopener">' + pbText + '</a>';
} else {
    powered.style.display = 'none';
}

// ─── FAB attention: pulse + tooltip bubble after 4s (once per session, non-mobile) ───
var attentionDismissed = false;
var attentionTimer = null;
var attentionAutoTimer = null;
var attentionBubble = null;

function dismissAttention() {
    if (attentionDismissed) return;
    attentionDismissed = true;
    if (attentionTimer)     { clearTimeout(attentionTimer);     attentionTimer = null; }
    if (attentionAutoTimer) { clearTimeout(attentionAutoTimer); attentionAutoTimer = null; }
    try { sessionStorage.setItem('cup_bubble_shown', '1'); } catch (e) { /* private mode — ignore */ }
    if (fab) fab.classList.remove('cup-pulse');
    if (attentionBubble && attentionBubble.parentNode) {
        attentionBubble.classList.add('cup-attention-out');
        var b = attentionBubble;
        setTimeout(function(){ if (b.parentNode) b.parentNode.removeChild(b); }, 260);
    }
    attentionBubble = null;
}

(function scheduleAttention(){
    // wp_localize_script casts PHP bool false → '' and true → '1', so use truthy check.
    if (!C.showGreetingBubble) return;
    // Don't run on small mobile — too invasive.
    if (typeof window.matchMedia === 'function' && window.matchMedia('(max-width: 480px)').matches) return;
    try {
        if (sessionStorage.getItem('cup_bubble_shown') === '1') return;
    } catch (e) { /* private mode — proceed anyway */ }

    var bubbleText = (C.greetingBubble && String(C.greetingBubble).trim())
        ? String(C.greetingBubble)
        : 'Ciao! Posso aiutarti? 👋';

    attentionTimer = setTimeout(function(){
        attentionTimer = null;
        if (isOpen || attentionDismissed) return;

        fab.classList.add('cup-pulse');

        var bubble = document.createElement('div');
        bubble.className = 'cup-fab-attention';
        bubble.setAttribute('role', 'button');
        bubble.setAttribute('tabindex', '0');
        bubble.setAttribute('aria-label', bubbleText);

        var txt = document.createElement('span');
        txt.className = 'cup-fab-attention__text';
        txt.textContent = bubbleText;
        bubble.appendChild(txt);

        var close = document.createElement('button');
        close.type = 'button';
        close.className = 'cup-fab-attention__close';
        close.setAttribute('aria-label', 'Chiudi');
        close.innerHTML = '&times;';
        close.addEventListener('click', function(e){
            e.stopPropagation();
            dismissAttention();
        });
        bubble.appendChild(close);

        bubble.addEventListener('click', function(){
            // Click on the bubble itself opens the chat.
            dismissAttention();
            if (!isOpen) { isOpen = true; openChat(); }
        });
        bubble.addEventListener('keydown', function(e){
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                dismissAttention();
                if (!isOpen) { isOpen = true; openChat(); }
            }
        });

        attentionBubble = bubble;
        root.appendChild(bubble);

        attentionAutoTimer = setTimeout(dismissAttention, 8000);
    }, 4000);
})();

// ─── Toggle ───
fab.addEventListener('click', function() {
    dismissAttention();
    isOpen = !isOpen;
    if (isOpen) openChat(); else closeChat();
});
minBtn.addEventListener('click', function() {
    isOpen = false;
    closeChat();
});

function openChat() {
    root.classList.add('cup-open');
    win.classList.remove('cup-closed');
    if (!initialized) {
        initialized = true;
        showWelcome();
    }
    setTimeout(function(){ input.focus(); }, 300);
}
function closeChat() {
    root.classList.remove('cup-open');
    win.classList.add('cup-closed');
}

// ─── Welcome ───
function showWelcome() {
    if (C.welcome) {
        addBotBubble(C.welcome);
    }
    // Load suggested questions
    fetch(C.suggestionsUrl, {
        headers: { 'X-WP-Nonce': C.nonce }
    })
    .then(function(r){ return r.json(); })
    .then(function(suggestions){
        if (Array.isArray(suggestions) && suggestions.length) {
            var wrap = document.createElement('div');
            wrap.className = 'cup-welcome-suggestions';
            suggestions.forEach(function(s){
                var btn = document.createElement('button');
                btn.className = 'cup-suggestion-btn';
                btn.textContent = s;
                btn.addEventListener('click', function(){ sendMessage(s); });
                wrap.appendChild(btn);
            });
            msgBox.appendChild(wrap);
            scrollBottom();
        }
    })
    .catch(function(){});
}

// ─── Send ───
input.addEventListener('input', function(){
    send.disabled = !input.value.trim();
});
input.addEventListener('keydown', function(e){
    if (e.key === 'Enter' && !send.disabled && !loading) sendMessage();
});
send.addEventListener('click', function(){
    if (!loading) sendMessage();
});

function sendMessage(text) {
    text = text || input.value.trim();
    if (!text || loading) return;
    input.value = '';
    send.disabled = true;
    loading = true;

    // Remove any previous suggestion buttons
    removeSuggestions();

    // User bubble
    addUserBubble(text);

    // Add to history
    history.push({ role: 'user', content: text });

    // history.slice(0, -1) excludes the current user message we just pushed —
    // the backend gets it via the `message` field and appends it as the final
    // turn itself.
    var sendHistory = history.slice(0, -1).slice(-6);

    sendMessageRegular(text, sendHistory).catch(function(err){
        if (err && err.message === 'nonce_expired') {
            addBotBubble('⚠️ La sessione è scaduta. Ricarica la pagina per continuare.');
        } else {
            addBotBubble('⚠️ Errore di connessione. Riprova tra poco.');
        }
        if (C.debug) console.error('[CUP]', err);
    }).then(function(){
        loading = false;
        send.disabled = !input.value.trim();
    });
}

// ─── Send to the chat API ───
function sendMessageRegular(text, sendHistory) {
    var typing = showTyping();
    return fetch(C.restUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': C.nonce
        },
        body: JSON.stringify({
            message: text,
            session_id: sessionId,
            history: sendHistory
        })
    })
    .then(function(r){
        if (!r.ok && r.status === 403) {
            throw new Error('nonce_expired');
        }
        return r.json();
    })
    .then(function(data){
        removeEl(typing);
        if (data.error) {
            addBotBubble('⚠️ ' + data.error);
        } else {
            addBotBubble(data.answer, data.sources, data.suggestions);
            history.push({ role: 'assistant', content: data.answer });
        }
        if (C.debug) console.log('[CUP]', data);
    });
}

// ─── Bubbles ───
function addUserBubble(text) {
    var el = document.createElement('div');
    el.className = 'cup-bubble cup-bubble--user';
    el.textContent = text;
    msgBox.appendChild(el);
    scrollBottom();
}

function addBotBubble(text, sources, suggestions) {
    var el = document.createElement('div');
    el.className = 'cup-bubble cup-bubble--bot';
    // Guard: never render an empty bubble — show a graceful fallback instead.
    var safeText = (typeof text === 'string' && text.trim() !== '')
        ? text
        : CUP_EMPTY_ANSWER_MSG;
    el.innerHTML = renderMarkdown(safeText);

    // Source cards
    if (sources && sources.length) {
        var srcWrap = document.createElement('div');
        srcWrap.className = 'cup-sources';

        var label = document.createElement('div');
        label.className = 'cup-sources-label';
        label.textContent = '📖 Fonti';
        srcWrap.appendChild(label);

        sources.forEach(function(src){
            // linkable defaults to true when missing (backward compat with pre-3.12.0 responses).
            var linkable = src.linkable !== false;
            var card;
            if (linkable) {
                card = document.createElement('a');
                card.href = src.url;
                card.target = '_blank';
                card.rel = 'noopener';
                card.className = 'cup-source-card';
            } else {
                card = document.createElement('div');
                card.className = 'cup-source-card cup-source-nolink';
                card.setAttribute('role', 'note');
            }

            // Icon
            var icon = document.createElement('div');
            icon.className = 'cup-source-icon';
            icon.textContent = getSourceEmoji(src);

            // Info
            var info = document.createElement('div');
            info.className = 'cup-source-info';

            var title = document.createElement('div');
            title.className = 'cup-source-title';
            title.textContent = src.title;

            var meta = document.createElement('div');
            meta.className = 'cup-source-meta';
            var parts = [];
            if (src.quartiere) parts.push('📍 ' + src.quartiere);
            if (src.tipo)      parts.push('🍽️ ' + src.tipo);
            if (src.prezzo)    parts.push('💰 ' + src.prezzo);
            meta.textContent = parts.join(' · ') || 'conoscounposto.com';

            info.appendChild(title);
            info.appendChild(meta);

            card.appendChild(icon);
            card.appendChild(info);

            // Arrow only on clickable cards — a chevron on a non-clickable element misleads users.
            if (linkable) {
                var arrow = document.createElement('span');
                arrow.className = 'cup-source-arrow';
                arrow.textContent = '›';
                card.appendChild(arrow);
            }

            srcWrap.appendChild(card);
        });

        el.appendChild(srcWrap);
    }

    msgBox.appendChild(el);

    // Suggestions (quick replies)
    if (suggestions && suggestions.length) {
        var sugWrap = document.createElement('div');
        sugWrap.className = 'cup-suggestions';
        suggestions.forEach(function(s){
            var btn = document.createElement('button');
            btn.className = 'cup-suggestion-btn';
            btn.textContent = s;
            btn.addEventListener('click', function(){ sendMessage(s); });
            sugWrap.appendChild(btn);
        });
        msgBox.appendChild(sugWrap);
    }

    scrollBottom();
}

function getSourceEmoji(src) {
    if (!src.tipo) return '📄';
    var t = src.tipo.toLowerCase();
    if (t.includes('pizza'))        return '🍕';
    if (t.includes('giapponese'))   return '🍣';
    if (t.includes('cinese'))       return '🥟';
    if (t.includes('gelato'))       return '🍦';
    if (t.includes('dolci'))        return '🧁';
    if (t.includes('carne'))        return '🥩';
    if (t.includes('pesce'))        return '🐟';
    if (t.includes('veggie'))       return '🥗';
    if (t.includes('street'))       return '🌮';
    if (t.includes('internazionale'))return '🌍';
    return '🍽️';
}

// ─── Markdown renderer ───
function renderMarkdown(text) {
    // Escape HTML first
    var html = escHtml(text);

    // Paragraphs (double newlines)
    html = html.split(/\n\n+/).map(function(p){ return '<p>' + p.trim() + '</p>'; }).join('');

    // Single newlines → <br>
    html = html.replace(/\n/g, '<br>');

    // Bold
    html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

    // Italic
    html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');

    // Links [text](url)
    html = html.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,
        '<a href="$2" target="_blank" rel="noopener">$1</a>');

    // Bare URLs
    html = html.replace(/(^|[^"'])(https?:\/\/[^\s<]+)/g,
        '$1<a href="$2" target="_blank" rel="noopener">$2</a>');

    // Unordered lists (- item): match after <br> or at start of <p>
    html = html.replace(/(<br>|<p>)- (.*?)(?=<br>|<\/p>|$)/g, function(m, prefix, item){
        return prefix + '<li>' + item + '</li>';
    });
    html = html.replace(/(<li>.*?<\/li>)+/g, '<ul>$&</ul>');

    // Emoji headers (📍 Title:)
    html = html.replace(/([\p{Emoji_Presentation}\p{Emoji}\u200d]+)\s*<strong>(.*?)<\/strong>/gu,
        '<strong>$1 $2</strong>');

    return html;
}

// ─── Helpers ───
function showTyping() {
    var el = document.createElement('div');
    el.className = 'cup-typing';
    el.innerHTML = '<span></span><span></span><span></span>';
    msgBox.appendChild(el);
    scrollBottom();
    return el;
}

function removeEl(el) {
    if (el && el.parentNode) el.parentNode.removeChild(el);
}

function removeSuggestions() {
    var old = msgBox.querySelectorAll('.cup-suggestions, .cup-welcome-suggestions');
    old.forEach(function(el){ el.remove(); });
}

function scrollBottom() {
    requestAnimationFrame(function(){
        body.scrollTop = body.scrollHeight;
    });
}

function escHtml(s) {
    var d = document.createElement('div');
    d.appendChild(document.createTextNode(s));
    return d.innerHTML;
}

// ─── GDPR banner dismiss (sessionStorage only — no cross-session persistence) ───
(function initGdprBanner(){
    var banner = document.getElementById('cup-gdpr-banner');
    if (!banner) return;

    var mode = banner.getAttribute('data-mode') || 'fixed';
    if (mode !== 'dismissable') return;

    // Restore dismiss state — guarded for browsers that block sessionStorage.
    try {
        if (sessionStorage.getItem('cup_gdpr_ack') === '1') {
            banner.style.display = 'none';
            return;
        }
    } catch (e) { /* private mode, storage disabled — banner stays visible */ }

    var closeBtn = document.getElementById('cup-gdpr-close');
    if (!closeBtn) return;
    closeBtn.addEventListener('click', function(){
        banner.style.display = 'none';
        try { sessionStorage.setItem('cup_gdpr_ack', '1'); } catch (e) { /* ignore */ }
    });
})();

})();
