/**
 * SlideMind Chat Widget
 *
 * Self-contained chat widget for SCORM/xAPI iframes.
 * Expects window.SLIDEMIND_STRINGS and window.SLIDEMIND_CONFIG to be set
 * by the inline script in widget.php before this file loads.
 *
 * Auth flow: calls GET /bootstrap?configId=... once on load to obtain
 * wp_rest nonce + learnerId/sessionId. Every /chat request passes
 * X-WP-Nonce.
 *
 * @package SlideMind
 * @since   0.4.0
 */
(function(){
    'use strict';

    var SLIDEMIND_STRINGS = window.SLIDEMIND_STRINGS || {};
    var CONFIG = window.SLIDEMIND_CONFIG || {};
    var CTX = null;

    /* ── Bootstrap (async) ──────────────────────────── */
    function bootstrap(callback) {
        // CONFIG.restUrl already contains '?' with plain permalinks
        // (e.g. /index.php?rest_route=/slidemind/v2/). Use '&' when it does,
        // '?' otherwise, so the configId param lands as a real $_GET entry.
        var url = CONFIG.restUrl + 'bootstrap';
        url += (url.indexOf('?') !== -1 ? '&' : '?')
            + 'configId=' + encodeURIComponent(CONFIG.configId);
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.withCredentials = true;
        xhr.onload = function() {
            if (xhr.status !== 200) { callback(null); return; }
            try { callback(JSON.parse(xhr.responseText)); } catch (e) { callback(null); }
        };
        xhr.onerror = function() { callback(null); };
        try { xhr.send(); } catch (e) { callback(null); }
    }

    bootstrap(function(ctx) {
        if (!ctx) {
            // Graceful degradation: widget loads but chat is disabled.
            var $fallback = document.getElementById('sm-w-empty') || document.body;
            if ($fallback) {
                $fallback.innerHTML = '<p style="color:#64748b;text-align:center;padding:24px;">' +
                    (SLIDEMIND_STRINGS.unknownError || 'Access denied') + '</p>';
            }
            return;
        }

        CTX = ctx;
        // Widget uses ctx identity directly (no local SCORM/xAPI resolution —
        // that's handled by the premium /external/whoami in Pro builds).
        CONFIG.learnerId = CTX.learnerId;
        CONFIG.sessionId = CTX.sessionId;
        CONFIG.sessionToken = CTX.sessionToken;

        var history = [];
        var sending = false;
        var turnCount = 0;

        /* ── DOM refs ────────────────────────────────────── */
        var $messages = document.getElementById('sm-w-messages');
        var $textarea = document.getElementById('sm-w-textarea');
        var $send     = document.getElementById('sm-w-send');
        var $typing   = document.getElementById('sm-w-typing');
        var $empty    = document.getElementById('sm-w-empty');
        var $reset    = document.getElementById('sm-w-reset');

        /* ── Auto-resize textarea ───────────────────────── */
        $textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });

        /* ── Send on Enter (Shift+Enter = newline) ──────── */
        $textarea.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        $send.addEventListener('click', sendMessage);

        if ($reset) {
            $reset.addEventListener('click', function() {
                history = [];
                turnCount = 0;
                $messages.querySelectorAll('.sm-w-msg').forEach(function(el) { el.remove(); });
                // Remove any lingering end-of-session banner.
                $messages.querySelectorAll('.sm-w-session-end').forEach(function(el) { el.remove(); });
                if ($empty) $empty.style.display = 'flex';
                $textarea.disabled = false;
                $send.disabled = false;
                // Re-render the opening bubble if configured.
                showOpeningBubble();
            });
        }

        /* ── Send message ───────────────────────────────── */
        function sendMessage() {
            if (sending) return;
            var text = $textarea.value.trim();
            if (!text) return;

            if ($empty) $empty.style.display = 'none';

            if (CONFIG.mode === 'qa') {
                $messages.querySelectorAll('.sm-w-msg').forEach(function(el) { el.remove(); });
                history = [];
            }

            appendMessage(text, 'user');
            $textarea.value = '';
            $textarea.style.height = 'auto';

            var messages = [];
            history.push({ role: 'user', content: text });
            messages = messages.concat(history);

            if (CONFIG.mode === 'qa') {
                messages = [{ role: 'user', content: text }];
            }

            sending = true;
            $send.disabled = true;
            $typing.classList.add('active');
            scrollBottom();

            var xhr = new XMLHttpRequest();
            xhr.open('POST', CONFIG.restUrl + 'chat', true);
            xhr.withCredentials = true;
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('X-WP-Nonce', CTX.nonce);

            xhr.onreadystatechange = function() {
                if (xhr.readyState !== 4) return;

                $typing.classList.remove('active');
                sending = false;
                $send.disabled = false;

                if (xhr.status === 200) {
                    try {
                        var r = JSON.parse(xhr.responseText);
                        if (r.success) {
                            var content = '';
                            if (r.structured && r.data) {
                                var parts = [];
                                for (var k in r.data) {
                                    if (r.data.hasOwnProperty(k)) parts.push(r.data[k]);
                                }
                                content = parts.join('\n');
                            } else if (r.message) {
                                content = r.message.content || '';
                            }

                            if (content) {
                                appendMessage(content, 'ai');
                                history.push({ role: 'assistant', content: content });
                                turnCount++;

                                if (CONFIG.maxTurns > 0 && turnCount >= CONFIG.maxTurns) {
                                    $textarea.disabled = true;
                                    $send.disabled = true;
                                    if (CONFIG.gracefulClose) {
                                        var banner = document.createElement('div');
                                        banner.className = 'sm-w-session-end';
                                        banner.textContent = CONFIG.closingMessage || SLIDEMIND_STRINGS.sessionEnded || '';
                                        if (banner.textContent) {
                                            $messages.insertBefore(banner, $typing);
                                            scrollBottom();
                                        }
                                    } else if (CONFIG.closingMessage) {
                                        appendMessage(CONFIG.closingMessage, 'ai');
                                    }
                                }
                            }
                        } else {
                            appendMessage(r.error || SLIDEMIND_STRINGS.unknownError, 'error');
                        }
                    } catch(e) {
                        appendMessage(SLIDEMIND_STRINGS.responseParseError, 'error');
                    }
                } else {
                    appendMessage(SLIDEMIND_STRINGS.httpConnectionError.replace('%s', xhr.status), 'error');
                }

                if (!$textarea.disabled) $textarea.focus();
            };

            var payload = {
                configId: CONFIG.configId,
                messages: messages,
                variables: {}
            };
            if (CONFIG.learnerId) payload.learnerId = CONFIG.learnerId;
            if (CONFIG.sessionId) {
                payload.sessionId = CONFIG.sessionId;
                payload.sessionToken = CONFIG.sessionToken;
            }

            xhr.send(JSON.stringify(payload));
        }

        /* ── Append a message bubble ────────────────────── */
        function appendMessage(text, type) {
            var div = document.createElement('div');
            div.className = 'sm-w-msg sm-w-msg--' + type;
            div.textContent = text;
            $messages.insertBefore(div, $typing);
            scrollBottom();
        }

        /* ── Opening message (chat mode only) ─────────────── */
        function showOpeningBubble() {
            var text = CONFIG.openingMessage;
            if (!text || CONFIG.mode !== 'chat') return;
            if ($empty) $empty.style.display = 'none';
            appendMessage(text, 'ai');
        }

        /* ── Scroll to bottom ───────────────────────────── */
        function scrollBottom() {
            requestAnimationFrame(function() {
                $messages.scrollTop = $messages.scrollHeight;
            });
        }

        /* ── Auto-focus ──────────────────────────────────── */
        $textarea.focus();

        /* ── Consent overlay ─────────────────────────────── */
        var $consentAccept = document.getElementById('sm-consent-accept');
        if ($consentAccept) {
            $consentAccept.addEventListener('click', function() {
                var overlay = document.getElementById('sm-consent-overlay');
                if (overlay) overlay.remove();
                $textarea.focus();
            });
        }

        /* ── Render opening bubble (last — all refs ready) ── */
        showOpeningBubble();
    });

})();
