<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }
$vcGreeting = 'Hola ' . htmlspecialchars($_SESSION['user_name'] ?? 'jefe', ENT_QUOTES) . '! Soy Vale. ¿En qué te puedo ayudar?';
?>
<!-- Vale Chat FAB (desktop only — mobile uses the Vale tab in bottom nav) -->
<button class="vale-chat-fab" id="valeChatFab" onclick="vcOpen()" aria-label="Hablar con Vale">
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
        <path d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/>
    </svg>
</button>

<!-- Overlay -->
<div class="vc-overlay" id="vcOverlay" onclick="vcClose()"></div>

<!-- Chat drawer -->
<div class="vale-chat-drawer" id="valeChatDrawer">
    <div class="vc-head">
        <div class="vc-head-av"><img src="/img/icon.png" alt="Vale" style="width:80%;height:80%;object-fit:contain;"></div>
        <div>
            <div class="vc-head-title">Vale</div>
            <div class="vc-head-sub" id="vcStatus">En línea</div>
        </div>
        <button class="vc-close" onclick="vcClose()" aria-label="Cerrar">&#215;</button>
    </div>
    <div class="vc-msgs" id="vcMsgs"></div>
    <form class="vc-form" id="vcForm" onsubmit="vcSend(event)">
        <input type="text" id="vcInput" placeholder="Escribí tu mensaje…" autocomplete="off">
        <button type="submit" id="vcSendBtn" aria-label="Enviar">
            <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
            </svg>
        </button>
    </form>
</div>

<script>
(function () {
    var vcHistory = [];
    var vcBusy    = false;
    var vcReady   = false;

    function setVcStatus(text) {
        var el = document.getElementById('vcStatus');
        if (el) el.textContent = text;
    }

    function setVcBusy(busy) {
        vcBusy = busy;
        var btn = document.getElementById('vcSendBtn');
        if (btn) btn.disabled = busy;
        setVcStatus(busy ? 'Pensando…' : 'En línea');
    }

    window.vcOpen = function () {
        document.getElementById('vcOverlay').classList.add('show');
        document.getElementById('valeChatDrawer').classList.add('open');
        var fab = document.getElementById('valeChatFab');
        if (fab) fab.classList.add('open');
        document.body.classList.add('vc-open');
        if (!vcReady) {
            vcReady = true;
            vcAddBubble(<?= json_encode($vcGreeting) ?>, 'in');
        }
        setTimeout(function () { document.getElementById('vcInput').focus(); }, 320);
    };

    window.vcClose = function () {
        document.getElementById('vcOverlay').classList.remove('show');
        document.getElementById('valeChatDrawer').classList.remove('open');
        var fab = document.getElementById('valeChatFab');
        if (fab) fab.classList.remove('open');
        document.body.classList.remove('vc-open');
    };

    function vcAddBubble(text, type) {
        var msgs = document.getElementById('vcMsgs');
        var d = document.createElement('div');
        d.className = 'vc-bubble vc-' + type;
        if (type === 'in') { d.innerHTML = text.replace(/\n/g, '<br>'); }
        else { d.textContent = text; }
        msgs.appendChild(d);
        msgs.scrollTop = msgs.scrollHeight;
    }

    function vcAddChips(options) {
        if (!options || !options.length) return;
        var msgs = document.getElementById('vcMsgs');
        var wrap = document.createElement('div');
        wrap.className = 'vc-chips'; wrap.id = 'vcChips';
        options.forEach(function(opt) {
            var btn = document.createElement('button');
            btn.className = 'vc-chip';
            btn.textContent = opt;
            btn.onclick = function() {
                var w = document.getElementById('vcChips');
                if (w) w.remove();
                document.getElementById('vcInput').value = opt;
                vcSend({ preventDefault: function(){} });
            };
            wrap.appendChild(btn);
        });
        msgs.appendChild(wrap); msgs.scrollTop = msgs.scrollHeight;
    }

    function vcShowTyping() {
        var msgs = document.getElementById('vcMsgs');
        var d = document.createElement('div');
        d.className = 'vc-typing'; d.id = 'vcTyping';
        d.innerHTML = '<span></span><span></span><span></span>';
        msgs.appendChild(d);
        msgs.scrollTop = msgs.scrollHeight;
    }

    function vcHideTyping() {
        var t = document.getElementById('vcTyping');
        if (t) t.remove();
    }

    window.vcSend = function (e) {
        e.preventDefault();
        if (vcBusy) return;
        var input = document.getElementById('vcInput');
        var text  = input.value.trim();
        if (!text) return;
        input.value = '';
        setVcBusy(true);
        vcAddBubble(text, 'out');
        var prior = vcHistory.slice();
        vcHistory.push({ role: 'user', text: text });
        vcShowTyping();

        var controller = window.AbortController ? new AbortController() : null;
        var timeoutId  = setTimeout(function() {
            if (controller) controller.abort();
        }, 25000);

        var fetchOpts = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message: text, history: prior })
        };
        if (controller) fetchOpts.signal = controller.signal;

        fetch('/dashboard/chat', fetchOpts)
        .then(function (r) {
            clearTimeout(timeoutId);
            if (!r.ok) {
                return r.text().then(function(t) { throw new Error('HTTP ' + r.status + ': ' + t.substring(0,200)); });
            }
            return r.json();
        })
        .then(function (data) {
            vcHideTyping();
            var reply = data.reply || '¿Podés repetirlo? Tuve un momento en blanco.';
            vcAddBubble(reply, 'in');
            vcHistory.push({ role: 'model', text: reply });
            vcAddChips(data.options);
            setVcBusy(false);
        })
        .catch(function (err) {
            clearTimeout(timeoutId);
            vcHideTyping();
            var isTimeout = err && err.name === 'AbortError';
            vcAddBubble(isTimeout ? 'Tardó demasiado. Intentá de nuevo.' : 'Error de conexión. Intentá de nuevo.', 'in');
            if (err && !isTimeout) console.error('[vale_chat]', err.message || err);
            setVcBusy(false);
        });
    };
}());
</script>
