<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}
$businessName = $tenant['name'] ?? 'Negocio';
$publicKey = $tenant['web_public_key'] ?? '';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($businessName); ?> — Chat con Vale</title>
    <link rel="stylesheet" href="/css/style.css">
    <style>
        body { height: 100vh; overflow: hidden; }
        .chat-page { display: flex; flex-direction: column; height: 100vh; max-width: 720px; margin: 0 auto; background: var(--color-crema); }
        .chat-page-head { background: var(--color-barro); color: var(--color-crema); padding: 1rem 1.25rem; display: flex; align-items: center; gap: .75rem; }
        .chat-page-head .avatar { background: var(--color-oro); }
        .chat-page-head h1 { color: #fff; font-size: 1.1rem; margin: 0; }
        .chat-page-head p { font-size: .75rem; opacity: .85; margin: 0; }
        .chat-page-msgs { flex: 1; overflow-y: auto; padding: 1.25rem; display: flex; flex-direction: column; gap: .75rem; }
        .cp-bubble { max-width: 78%; padding: .7rem 1rem; border-radius: 14px; font-size: .95rem; line-height: 1.4; white-space: pre-wrap; word-wrap: break-word; box-shadow: var(--shadow-soft); }
        .cp-in { align-self: flex-start; background: #fff; border: 1px solid var(--color-border); border-bottom-left-radius: 3px; }
        .cp-out { align-self: flex-end; background: var(--color-oro); color: var(--color-tinta); border-bottom-right-radius: 3px; }
        .cp-opts { display: flex; flex-wrap: wrap; gap: .5rem; }
        .cp-opt { background: #fff; border: 1.5px solid var(--color-barro); color: var(--color-barro); border-radius: 16px; padding: .5rem .9rem; font-size: .88rem; font-weight: 600; cursor: pointer; font-family: var(--font-body); }
        .cp-opt:hover { background: var(--color-barro); color: #fff; }
        .chat-page-form { display: flex; gap: .5rem; padding: .85rem; border-top: 1px solid var(--color-border); background: #fff; }
        .chat-page-form input { flex: 1; border: 1px solid var(--color-border); border-radius: 24px; padding: .7rem 1rem; font-size: 1rem; font-family: var(--font-body); outline: none; }
        .chat-page-form button { border: none; background: var(--color-barro); color: #fff; border-radius: 50%; width: 44px; height: 44px; font-size: 1.1rem; cursor: pointer; flex-shrink: 0; }
        .chat-invalid { display: flex; align-items: center; justify-content: center; height: 100vh; text-align: center; padding: 2rem; color: var(--color-text-muted); }
    </style>
</head>
<body>
<?php if (!$tenant): ?>
    <div class="chat-invalid">
        <div>
            <h2 style="color: var(--color-barro);">Chat no disponible</h2>
            <p>El enlace no es válido o el negocio no existe.</p>
        </div>
    </div>
<?php else: ?>
    <div class="chat-page">
        <div class="chat-page-head">
            <div class="avatar"><img src="/img/icon.png" alt="Vale" style="width:80%;height:80%;object-fit:contain;"></div>
            <div>
                <h1><?php echo htmlspecialchars($businessName); ?></h1>
                <p>Chateás con Vale · asistente virtual con IA</p>
            </div>
        </div>
        <div class="chat-page-msgs" id="cpMsgs"></div>
        <form class="chat-page-form" id="cpForm">
            <input type="text" id="cpInput" placeholder="Escribí tu mensaje…" autocomplete="off">
            <button type="submit" aria-label="Enviar">→</button>
        </form>
    </div>

    <script>
        var valeKey = <?php echo json_encode($publicKey); ?>;
        var cookieName = 'vale_visitor_' + valeKey.slice(0, 8);

        function getCookie(name) {
            var m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
            return m ? decodeURIComponent(m[1]) : '';
        }
        function setCookie(name, value) {
            document.cookie = name + '=' + encodeURIComponent(value) + '; max-age=' + (365 * 24 * 60 * 60) + '; path=/; SameSite=Lax';
        }

        var visitorId = getCookie(cookieName);
        var msgs = document.getElementById('cpMsgs');
        var form = document.getElementById('cpForm');
        var input = document.getElementById('cpInput');

        function addBubble(text, kind) {
            var b = document.createElement('div');
            b.className = 'cp-bubble ' + (kind === 'out' ? 'cp-out' : 'cp-in');
            b.textContent = text;
            msgs.appendChild(b);
            msgs.scrollTop = msgs.scrollHeight;
            return b;
        }

        function clearOptions() {
            var prev = msgs.querySelector('.cp-opts');
            if (prev) prev.remove();
        }

        function addOptions(opts) {
            clearOptions();
            if (!opts || !opts.length) return;
            var wrap = document.createElement('div');
            wrap.className = 'cp-opts';
            opts.forEach(function (o) {
                var btn = document.createElement('button');
                btn.className = 'cp-opt';
                btn.textContent = o;
                btn.addEventListener('click', function () { clearOptions(); send(o); });
                wrap.appendChild(btn);
            });
            msgs.appendChild(wrap);
            msgs.scrollTop = msgs.scrollHeight;
        }

        addBubble('¡Hola! Soy Vale, la asistente virtual de <?php echo htmlspecialchars(addslashes($businessName)); ?>. ¿En qué te puedo ayudar?', 'in');

        function send(text) {
            clearOptions();
            addBubble(text, 'out');
            var typing = addBubble('…', 'in');
            fetch('/agent/web', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ key: valeKey, visitorId: visitorId, message: text })
            })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    typing.remove();
                    if (data.visitorId) { visitorId = data.visitorId; setCookie(cookieName, visitorId); }
                    addBubble(data.reply || 'No pude responder ahora mismo.', 'in');
                    addOptions(data.options || []);
                })
                .catch(function () {
                    typing.remove();
                    addBubble('Hubo un problema de conexión. Intentá de nuevo.', 'in');
                });
        }

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var t = input.value.trim();
            if (!t) return;
            input.value = '';
            send(t);
        });
        input.focus();
    </script>
<?php endif; ?>
</body>
</html>
