(function () {
    'use strict';

    let documentId = null;
    let chatContainer = null;
    let chatMessages = null;
    let chatInput = null;
    let chatSendBtn = null;
    let summaryContent = null;
    let summaryStatus = null;
    let suggestedQuestions = null;
    let questionsContainer = null;
    let isLoading = false;
    let viewerSuggestBusy = false;
    let summarizeUrl = '/chat/summarize';
    let askUrl = '/chat/ask';
    let suggestViewerUrl = '/chat/suggest';

    const VIEWER_SUGGEST_FALLBACK = [
        'Summarize all key information from this document',
        'What are the most important talking points?',
        'List any objections and suggested rebuttals',
        'What are the key pricing details?',
        'Provide qualifying questions for leads',
    ];

    const csrfName = 'csrf_test_name';
    const csrfHeader = 'X-CSRF-TOKEN';
    let csrfToken = '';

    function getMeta(name) {
        const meta = document.querySelector('meta[name="' + name + '"]');
        return meta ? meta.getAttribute('content') : '';
    }

    function updateCsrfFromHeader(xhr) {
        const token = xhr.getResponseHeader(csrfHeader);
        if (token) {
            csrfToken = token;
        }
    }

    function postRequest(url, data, callback) {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        if (csrfToken) {
            xhr.setRequestHeader(csrfHeader, csrfToken);
        }

        const params = [];
        if (csrfToken) {
            params.push(encodeURIComponent(csrfName) + '=' + encodeURIComponent(csrfToken));
        }
        Object.keys(data).forEach(function (key) {
            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        });

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) return;
            updateCsrfFromHeader(xhr);
            let result = null;
            try {
                result = JSON.parse(xhr.responseText);
            } catch (e) {
                result = { success: false, error: 'Invalid JSON response: ' + xhr.responseText };
            }
            callback(result, xhr.status);
        };

        xhr.onerror = function () {
            callback({ success: false, error: 'Network error occurred.' }, 0);
        };

        xhr.send(params.join('&'));
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.appendChild(document.createTextNode(text));
        return div.innerHTML;
    }

    function formatText(text) {
        return escapeHtml(text)
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\n/g, '<br>');
    }

    function renderSummary(text) {
        if (!summaryContent) return;
        const formatted = formatText(text);
        summaryContent.innerHTML = '<p class="whitespace-pre-wrap leading-relaxed">' + formatted + '</p>';
        if (summaryStatus) {
            summaryStatus.className = 'ml-auto inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium bg-emerald-50 text-emerald-700 border border-emerald-100';
            summaryStatus.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg> Summary Ready';
        }
    }

    function setViewerSuggestBusy(isBusy, labelText) {
        viewerSuggestBusy = !!isBusy;
        const btn = document.getElementById('viewerRegenerateSuggestBtn');
        const icon = document.getElementById('viewerRegenerateSuggestIcon');
        const lbl = document.getElementById('viewerRegenerateSuggestLabel');
        const caption = document.getElementById('viewerSuggestStatusCaption');
        if (btn) btn.disabled = viewerSuggestBusy;
        if (icon) {
            if (viewerSuggestBusy) icon.classList.add('animate-spin');
            else icon.classList.remove('animate-spin');
        }
        if (lbl) lbl.textContent = viewerSuggestBusy ? (labelText || 'Generating…') : 'Regenerate';
        if (caption && viewerSuggestBusy) {
            caption.classList.remove('text-slate-400', 'text-emerald-600', 'text-amber-600', 'text-rose-500');
            caption.classList.add('text-slate-400');
            caption.textContent = labelText || 'Generating new AI questions for the current scope…';
        }
    }

    async function fetchViewerSuggestions(opts) {
        opts = opts || {};
        if (viewerSuggestBusy || !questionsContainer || !suggestedQuestions) return;
        const seed = opts.newSeed
            ? String(Math.floor(Math.random() * 900000) + 100000)
            : (typeof opts.seed === 'string' ? opts.seed : '');
        setViewerSuggestBusy(true, opts.newSeed ? 'Re-generating new set…' : 'Generating AI suggestions for scope…');

        const body = new FormData();
        body.append(csrfName, csrfToken || '');
        if (documentId) body.append('document_id', String(documentId));
        body.append('count', '5');
        if (seed) body.append('seed', seed);

        let data = null;
        let errMsg = null;
        try {
            const res = await fetch(suggestViewerUrl, { method: 'POST', body: body });
            const ct = (res.headers.get('content-type') || '');
            if (ct.indexOf('application/json') >= 0) data = await res.json();
            if (!data || !data.success) throw new Error((data && data.error) ? data.error : ('HTTP ' + res.status));
        } catch (e) {
            errMsg = (e && e.message) ? e.message : 'Unknown';
        } finally {
            setViewerSuggestBusy(false);
        }

        if (data && data.success) {
            renderQuestions(data.questions || [], {
                docLabelsUsed: data.doc_labels_used || [],
                contextChars: data.context_chars || 0,
                seed: data.seed || seed || '',
                warn: data.warn || '',
            });
            return;
        }

        renderQuestions(VIEWER_SUGGEST_FALLBACK, {
            docLabelsUsed: documentId ? ['Document #' + documentId] : [],
            contextChars: 0,
            seed: seed || '',
            warn: 'Network/AI error: ' + (errMsg || 'Unknown') + '. Showing default starter questions.',
        });
        const caption = document.getElementById('viewerSuggestStatusCaption');
        if (caption) {
            caption.classList.remove('text-slate-400', 'text-emerald-600', 'text-amber-600');
            caption.classList.add('text-rose-500');
        }
    }

    function renderQuestions(arr, captionOpts) {
        if (!questionsContainer || !suggestedQuestions) return;
        captionOpts = captionOpts || {};
        if (!Array.isArray(arr) || arr.length === 0) {
            questionsContainer.innerHTML = '';
            const caption = document.getElementById('viewerSuggestStatusCaption');
            if (caption) {
                caption.classList.remove('text-slate-400', 'text-emerald-600', 'text-amber-600', 'text-rose-500');
                caption.classList.add('text-amber-600');
                caption.textContent = (typeof captionOpts.warn === 'string' && captionOpts.warn)
                    ? '⚠ ' + captionOpts.warn
                    : 'No AI-generated suggestions available yet. Try the Regenerate button.';
            }
            suggestedQuestions.classList.remove('hidden');
            return;
        }
        questionsContainer.innerHTML = '';
        arr.forEach(function (question, idx) {
            if (typeof question !== 'string' || question.trim() === '') return;
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] leading-tight font-medium bg-white text-slate-700 border border-slate-200 hover:bg-blue-50 hover:text-blue-700 hover:border-blue-200 transition-all shadow-sm group q-pill';
            btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="w-2.5 h-2.5 text-slate-400 group-hover:text-blue-500 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg> <span class="truncate max-w-[280px]">' + escapeHtml(question) + '</span>';
            btn.addEventListener('click', function () {
                sendMessage(question);
            });
            questionsContainer.appendChild(btn);
        });

        const caption = document.getElementById('viewerSuggestStatusCaption');
        if (caption) {
            const scopeLabel = captionOpts.docLabelsUsed && captionOpts.docLabelsUsed.length
                ? ('Scoped to: ' + captionOpts.docLabelsUsed.slice(0, 2).join('; ') + (captionOpts.docLabelsUsed.length > 2 ? '; +' + (captionOpts.docLabelsUsed.length - 2) : ''))
                : (documentId ? ('Scoped to document #' + documentId) : 'Scoped to all documents (cross-search)');
            const warn = typeof captionOpts.warn === 'string' && captionOpts.warn.trim().length > 0;
            caption.classList.remove('text-slate-400', 'text-emerald-600', 'text-amber-600', 'text-rose-500');
            if (warn) {
                caption.classList.add('text-amber-600');
                caption.textContent = '⚠ ' + captionOpts.warn + ' | ' + scopeLabel + (typeof captionOpts.contextChars === 'number' ? (' · ' + captionOpts.contextChars.toLocaleString() + ' chars context') : '') + (typeof captionOpts.seed === 'string' && captionOpts.seed ? (' · seed=' + captionOpts.seed) : '');
            } else {
                caption.classList.add('text-emerald-600');
                caption.textContent = '✓ ' + scopeLabel + (typeof captionOpts.contextChars === 'number' ? (' · ' + captionOpts.contextChars.toLocaleString() + ' chars context') : '') + (typeof captionOpts.seed === 'string' && captionOpts.seed ? (' · seed=' + captionOpts.seed) : '');
            }
        }
        suggestedQuestions.classList.remove('hidden');
    }

    function appendMessage(role, text, followUps) {
        if (!chatMessages) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'flex gap-3 max-w-[90%] fade-in';

        if (role === 'user') {
            wrapper.classList.add('ml-auto', 'flex-row-reverse');
        }

        const avatar = document.createElement('div');
        avatar.className = 'w-8 h-8 rounded-2xl flex items-center justify-center flex-shrink-0 shadow-md';
        if (role === 'user') {
            avatar.className += ' bg-gradient-to-br from-emerald-400 to-cyan-500 text-white';
            avatar.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.2"><path stroke-linecap="round" stroke-linejoin="round" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" /></svg>';
        } else {
            avatar.className += ' bg-gradient-to-br from-violet-500 via-blue-500 to-indigo-600 text-white shadow-blue-500/20';
            avatar.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.2"><path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>';
        }

        const contentCol = document.createElement('div');
        contentCol.className = 'flex flex-col items-start gap-2 min-w-0 flex-1';
        if (role === 'user') {
            contentCol.classList.add('items-end');
        }

        const bubble = document.createElement('div');
        bubble.className = 'rounded-2xl border shadow-sm p-3.5';
        if (role === 'user') {
            bubble.className += ' bg-gradient-to-br from-blue-600 to-indigo-600 text-white rounded-tr-sm border-blue-500 shadow-blue-500/10';
            bubble.innerHTML = '<p class="text-sm leading-relaxed whitespace-pre-wrap break-words">' + formatText(text) + '</p>';
        } else {
            bubble.className += ' bg-white text-slate-700 rounded-tl-sm border-slate-200';
            bubble.innerHTML = '<div class="text-sm leading-relaxed whitespace-pre-wrap break-words">' + formatText(text) + '</div>';
        }
        contentCol.appendChild(bubble);

        if (role === 'assistant' && Array.isArray(followUps) && followUps.length > 0) {
            const clean = followUps
                .filter(function (q) { return typeof q === 'string' && q.trim().length >= 3; })
                .slice(0, 4);
            if (clean.length > 0) {
                const box = document.createElement('div');
                box.className = 'w-full flex flex-col items-start gap-1.5 pl-1';
                const label = document.createElement('div');
                label.className = 'inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-indigo-600/80 px-1.5 pt-1';
                label.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg> Follow up';
                box.appendChild(label);
                const row = document.createElement('div');
                row.className = 'flex flex-wrap gap-1.5 w-full';
                clean.forEach(function (question) {
                    const btn = document.createElement('button');
                    btn.type = 'button';
                    btn.className = 'inline-flex items-start gap-1.5 px-3 py-1.5 rounded-2xl text-[12px] font-medium text-left bg-indigo-50 text-indigo-700 border border-indigo-100 hover:bg-indigo-100 hover:text-indigo-800 hover:border-indigo-200 transition-all shadow-sm group max-w-[calc(100%-4px)]';
                    btn.innerHTML =
                        '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-indigo-500 group-hover:text-indigo-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">' +
                        '<path stroke-linecap="round" stroke-linejoin="round" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>' +
                        '<span class="break-words leading-snug">' + escapeHtml(question) + '</span>';
                    btn.addEventListener('click', function () { sendMessage(question); });
                    row.appendChild(btn);
                });
                box.appendChild(row);
                contentCol.appendChild(box);
            }
        }

        wrapper.appendChild(avatar);
        wrapper.appendChild(contentCol);
        chatMessages.appendChild(wrapper);

        requestAnimationFrame(function () {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        });

        return wrapper;
    }

    function appendLoading() {
        if (!chatMessages) return;

        const wrapper = document.createElement('div');
        wrapper.className = 'flex gap-3 max-w-[90%] fade-in';
        wrapper.id = 'ai-loading-bubble';

        const avatar = document.createElement('div');
        avatar.className = 'w-8 h-8 rounded-2xl bg-gradient-to-br from-violet-500 via-blue-500 to-indigo-600 text-white flex items-center justify-center flex-shrink-0 shadow-md shadow-blue-500/20';
        avatar.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.2"><path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>';

        const bubble = document.createElement('div');
        bubble.className = 'bg-white rounded-2xl rounded-tl-sm border border-slate-200 shadow-sm p-3.5';
        bubble.innerHTML = '<div class="flex items-center gap-1.5 py-1 px-1"><span class="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style="animation-delay:0ms"></span><span class="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style="animation-delay:150ms"></span><span class="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style="animation-delay:300ms"></span></div>';

        wrapper.appendChild(avatar);
        wrapper.appendChild(bubble);
        chatMessages.appendChild(wrapper);

        requestAnimationFrame(function () {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        });

        return wrapper;
    }

    function removeLoading() {
        const loading = document.getElementById('ai-loading-bubble');
        if (loading) loading.remove();
    }

    function setInputEnabled(enabled) {
        isLoading = !enabled;
        if (chatInput) chatInput.disabled = !enabled;
        if (chatSendBtn) chatSendBtn.disabled = !enabled;
        if (!enabled) {
            if (chatInput) chatInput.classList.add('opacity-70', 'cursor-not-allowed');
        } else {
            if (chatInput) chatInput.classList.remove('opacity-70', 'cursor-not-allowed');
            if (chatInput) chatInput.focus();
        }
    }

    function sendMessage(text) {
        const content = typeof text === 'string' && text.trim() !== ''
            ? text.trim()
            : (chatInput ? chatInput.value.trim() : '');
        if (!content || isLoading) return;

        setInputEnabled(false);
        appendMessage('user', content);
        if (chatInput) chatInput.value = '';
        appendLoading();

        const payload = { question: content };
        if (documentId) {
            payload.document_id = documentId;
        }

        postRequest(askUrl, payload, function (res) {
            removeLoading();
            setInputEnabled(true);
            if (res && res.success) {
                let answer = res.answer || '';
                if (res.sources && Array.isArray(res.sources) && res.sources.length > 0) {
                    answer += '\n\n📚 Sources: ' + res.sources.map(function (s) { return '• ' + s; }).join('\n            ');
                }
                const fups = (res.follow_ups && Array.isArray(res.follow_ups)) ? res.follow_ups : [];
                appendMessage('assistant', answer, fups);
                try {
                    if (fups.length > 0) {
                        const caption = document.getElementById('viewerSuggestStatusCaption');
                        const prevHtml = caption ? caption.textContent : '';
                        const prevClassList = caption ? Array.from(caption.classList) : [];
                        renderQuestions(fups, {});
                        if (caption && prevHtml) {
                            caption.textContent = prevHtml;
                            caption.className = prevClassList.join(' ') + (caption.className ? '' : '');
                        }
                    }
                } catch (_e) {}
            } else {
                const errMsg = '⚠️ Error: ' + ((res && res.error) ? res.error : 'Something went wrong. Please try again.');
                const fallback = [];
                if (res && res.error) {
                    try {
                        const docScope = documentId ? ('document scope ID=' + documentId) : 'current knowledge base';
                        fallback.push('Try asking with keywords from the ' + docScope + '.');
                        fallback.push('Ask a shorter, specific question (10-25 words).');
                        fallback.push('Pick a single document from the Search within dropdown first.');
                    } catch (_e) {}
                }
                appendMessage('assistant', errMsg, fallback.length > 0 ? fallback : null);
            }
        });
    }

    function autoSummarize() {
        if (!documentId) return;

        if (summaryContent) {
            summaryContent.innerHTML = '<p class="text-slate-500 italic">Analyzing document and generating AI summary... Please wait.</p>';
        }
        if (summaryStatus) {
            summaryStatus.className = 'ml-auto inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium bg-amber-50 text-amber-700 border border-amber-100';
            summaryStatus.innerHTML = '<svg class="w-3 h-3 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Summarizing...';
        }

        postRequest(summarizeUrl, { document_id: documentId }, function (res) {
            if (res && res.success) {
                if (res.summary) renderSummary(res.summary);
                if (res.questions) renderQuestions(res.questions);
            } else {
                if (summaryContent) {
                    summaryContent.innerHTML = '<p class="text-red-600">❌ Failed to generate summary: ' + escapeHtml((res && res.error) ? res.error : 'Unknown error') + '</p>';
                }
                if (summaryStatus) {
                    summaryStatus.className = 'ml-auto inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium bg-red-50 text-red-700 border border-red-100';
                    summaryStatus.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg> Failed';
                }
                renderQuestions([]);
            }
        });
    }

    function setupInputEvents() {
        if (chatSendBtn) {
            chatSendBtn.addEventListener('click', function () {
                sendMessage();
            });
        }

        if (chatInput) {
            chatInput.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            chatInput.addEventListener('input', function () {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 150) + 'px';
            });
        }
    }

    function init() {
        chatContainer = document.getElementById('chatContainer');
        if (!chatContainer) return;

        documentId = chatContainer.getAttribute('data-document-id');
        if (documentId) documentId = parseInt(documentId, 10) || null;

        const su = chatContainer.getAttribute('data-summarize-url');
        if (su && typeof su === 'string' && su.trim() !== '') {
            summarizeUrl = su.trim();
        }
        const au = chatContainer.getAttribute('data-ask-url');
        if (au && typeof au === 'string' && au.trim() !== '') {
            askUrl = au.trim();
        }
        const su2 = chatContainer.getAttribute('data-suggest-url');
        if (su2 && typeof su2 === 'string' && su2.trim() !== '') {
            suggestViewerUrl = su2.trim();
        } else {
            try {
                if (typeof askUrl === 'string' && askUrl !== '') {
                    const idx = askUrl.lastIndexOf('/chat/ask');
                    if (idx >= 0) {
                        suggestViewerUrl = askUrl.substring(0, idx) + '/chat/suggest';
                    }
                }
            } catch (_e) {
                suggestViewerUrl = '/chat/suggest';
            }
        }

        chatMessages = document.getElementById('chatMessages');
        chatInput = document.getElementById('chatInput');
        chatSendBtn = document.getElementById('chatSendBtn');
        summaryContent = document.getElementById('summaryContent');
        summaryStatus = document.getElementById('summaryStatus');
        suggestedQuestions = document.getElementById('suggestedQuestions');
        questionsContainer = document.getElementById('questionsContainer');

        csrfToken = getMeta(csrfName) || getMeta('csrf-token') || getMeta('csrf');

        const viewerRegenBtn = document.getElementById('viewerRegenerateSuggestBtn');
        if (viewerRegenBtn) {
            viewerRegenBtn.addEventListener('click', function () {
                fetchViewerSuggestions({ newSeed: true });
            });
        }

        setupInputEvents();
        fetchViewerSuggestions({ newSeed: true });
        autoSummarize();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
