<?php
$assistantConfig = is_array($assistant_config ?? null) ? $assistant_config : [];
$messages = is_array($messages ?? null) ? $messages : [];
$closedChats = is_array($closed_chats ?? null) ? $closed_chats : [];
$assistantReady = (bool) ($assistantConfig['is_ready'] ?? false);
$chatClosed = (bool) ($chat_closed ?? false);
$idleTimeoutSeconds = max(60, (int) ($idle_timeout_seconds ?? 300));
$viewingClosedSessionId = (int) ($viewing_closed_session_id ?? 0);
$currentSessionId = (int) ($current_session_id ?? 0);
?>

<style>
    .vx-ai-chat {
        border: 1px solid #dbe5f6;
        border-radius: 14px;
        background: #f8fbff;
        min-height: 360px;
        max-height: 560px;
        overflow-y: auto;
        padding: 14px;
    }
    .vx-ai-msg {
        border-radius: 12px;
        padding: 10px 12px;
        margin-bottom: 10px;
        white-space: pre-wrap;
        line-height: 1.45;
    }
    .vx-ai-msg-user {
        background: #e8f4ff;
        border: 1px solid #c9e0fb;
        color: #1f3f68;
        margin-left: 48px;
    }
    .vx-ai-msg-bot {
        background: #ffffff;
        border: 1px solid #dce8f9;
        color: #1f2f4b;
        margin-right: 48px;
    }
    .vx-ai-msg-system {
        background: #fff7e6;
        border: 1px solid #ffe0a3;
        color: #7a5a14;
        margin-right: 20px;
        margin-left: 20px;
    }
    .vx-ai-quick {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }
    .vx-ai-closed-item {
        border: 1px solid #dbe5f6;
        border-radius: 12px;
        padding: 10px 12px;
        background: #fff;
    }
    .vx-ai-closed-item.is-selected {
        border-color: #6ea8fe;
        box-shadow: 0 0 0 1px rgba(110, 168, 254, 0.2);
        background: #f8fbff;
    }
    .vx-ai-closed-list {
        display: grid;
        gap: 10px;
        max-height: 420px;
        overflow-y: auto;
        padding-right: 2px;
    }
    .vx-ai-side-card .card-body {
        display: flex;
        flex-direction: column;
        gap: 16px;
    }
</style>

<div class="row g-3">
    <div class="col-12 col-xxl-8">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex align-items-start justify-content-between flex-wrap gap-2 mb-2">
                    <div>
                        <h2 class="h5 mb-1"><i class="bx bx-bot me-1"></i>Asistente IA Veltrix</h2>
                        <small class="text-muted">
                            Resuelve dudas de uso del sistema: POS, caja, inventario, compras, reportes y más.
                        </small>
                    </div>
                    <?php if ($assistantReady): ?>
                        <span class="badge text-bg-success">Operativo</span>
                    <?php else: ?>
                        <span class="badge text-bg-warning">Sin configurar</span>
                    <?php endif; ?>
                </div>

                <div class="d-flex flex-wrap align-items-center gap-2 mb-3">
                    <span
                        id="vxAiStateBadge"
                        class="badge <?= $chatClosed ? 'text-bg-secondary' : 'text-bg-info' ?>"
                    >
                        <?= $chatClosed ? 'Cerrado por inactividad' : 'Sesión de chat activa' ?>
                    </span>
                    <button
                        type="button"
                        id="vxAiReopenBtn"
                        class="btn btn-sm btn-outline-secondary <?= $chatClosed ? '' : 'd-none' ?>"
                    >
                        Reabrir chat
                    </button>
                </div>

                <div id="vxAiChat" class="vx-ai-chat mb-3">
                    <?php if ($messages === []): ?>
                        <div class="vx-ai-msg vx-ai-msg-bot">
Hola. Soy tu asistente de Veltrix POS.
Puedo ayudarte con procesos, flujos y configuración del sistema.
                        </div>
                    <?php endif; ?>

                    <?php foreach ($messages as $message): ?>
                        <?php
                        $role = strtolower(trim((string) ($message['rol'] ?? 'assistant')));
                        $content = trim((string) ($message['contenido'] ?? ''));
                        if ($content === '') {
                            continue;
                        }

                        if ($role === 'user') {
                            $cssClass = 'vx-ai-msg-user';
                        } elseif ($role === 'assistant') {
                            $cssClass = 'vx-ai-msg-bot';
                        } else {
                            $cssClass = 'vx-ai-msg-system';
                        }
                        ?>
                        <div class="vx-ai-msg <?= e($cssClass) ?>"><?= e($content) ?></div>
                    <?php endforeach; ?>

                    <?php if (!$assistantReady): ?>
                        <div class="vx-ai-msg vx-ai-msg-system">
El asistente IA aún no está activo. Pide al superadmin configurar API e Integraciones > Agente IA.
                        </div>
                    <?php endif; ?>

                    <?php if ($chatClosed): ?>
                        <div class="vx-ai-msg vx-ai-msg-system" id="vxAiClosedServerNotice">
El chat está cerrado por inactividad. Puedes reabrir este chat o abrir uno de la lista de chats cerrados.
                        </div>
                    <?php endif; ?>
                </div>

                <div class="vx-ai-quick mb-3" id="vxAiQuickWrap">
                    <button type="button" class="btn btn-sm btn-light border" data-ai-question="¿Cómo hago una venta rápida en POS?">Venta rápida POS</button>
                    <button type="button" class="btn btn-sm btn-light border" data-ai-question="¿Cómo registrar una compra y afectar inventario?">Registrar compra</button>
                    <button type="button" class="btn btn-sm btn-light border" data-ai-question="¿Cómo hago cierre de caja y arqueo?">Cierre de caja</button>
                    <button type="button" class="btn btn-sm btn-light border" data-ai-question="¿Cómo crear un usuario y asignar permisos?">Usuarios y permisos</button>
                </div>

                <form id="vxAiAskForm" action="<?= e(url('ayuda-ia/preguntar')) ?>" method="post">
                    <?= csrf_field() ?>
                    <div class="input-group">
                        <input
                            type="text"
                            class="form-control"
                            name="pregunta"
                            id="vxAiQuestion"
                            maxlength="1200"
                            placeholder="Escribe tu duda..."
                            <?= ($assistantReady && !$chatClosed) ? '' : 'disabled' ?>
                            required
                        >
                        <button class="btn btn-primary" type="submit" id="vxAiAskBtn" <?= ($assistantReady && !$chatClosed) ? '' : 'disabled' ?>>
                            <i class="bx bx-send me-1"></i>Preguntar
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-12 col-xxl-4">
        <div class="card border-0 shadow-sm vx-ai-side-card">
            <div class="card-body">
                <div class="alert alert-light border mt-3 mb-3">
                    <strong>Tip:</strong> Haz preguntas concretas para respuestas más rápidas.
                    <br>
                    Ejemplo: “¿Cómo anular una venta y dejar trazabilidad?”
                </div>

                <div class="d-flex align-items-center justify-content-between">
                    <h3 class="h6 mb-0">Chats cerrados</h3>
                    <span class="badge text-bg-light border"><?= e((string) count($closedChats)) ?></span>
                </div>
                <div class="vx-ai-closed-list">
                    <?php foreach ($closedChats as $closed): ?>
                        <?php
                        $closedId = (int) ($closed['id'] ?? 0);
                        $closedTitle = trim((string) ($closed['titulo'] ?? 'Chat cerrado'));
                        if ($closedTitle === '') {
                            $closedTitle = 'Chat cerrado';
                        }
                        $closedAtRaw = trim((string) ($closed['closed_at'] ?? ''));
                        $closedAt = $closedAtRaw !== '' ? date('d/m/Y H:i', strtotime($closedAtRaw)) : 'Sin fecha';
                        $messagesCount = (int) ($closed['mensajes'] ?? 0);
                        $isSelected = $viewingClosedSessionId > 0 && $viewingClosedSessionId === $closedId;
                        ?>
                        <div class="vx-ai-closed-item <?= $isSelected ? 'is-selected' : '' ?>">
                            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                                <div>
                                    <strong><?= e($closedTitle) ?></strong>
                                    <div class="small text-muted">
                                        Cerrado: <?= e($closedAt) ?> | Mensajes: <?= e((string) $messagesCount) ?>
                                    </div>
                                </div>
                                <div class="d-flex flex-wrap gap-2">
                                    <a
                                        href="<?= e(url('ayuda-ia') . '?chat_cerrado=' . $closedId) ?>"
                                        class="btn btn-sm btn-outline-secondary"
                                    >
                                        Ver
                                    </a>
                                    <form action="<?= e(url('ayuda-ia/reabrir')) ?>" method="post" class="m-0">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="session_id" value="<?= e((string) $closedId) ?>">
                                        <button class="btn btn-sm btn-primary" type="submit">Reabrir</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <?php if ($closedChats === []): ?>
                        <div class="vx-ai-closed-item">
                            <span class="text-muted">No tienes chats cerrados todavía.</span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
window.addEventListener('DOMContentLoaded', () => {
    const chat = document.getElementById('vxAiChat');
    const form = document.getElementById('vxAiAskForm');
    const questionInput = document.getElementById('vxAiQuestion');
    const askButton = document.getElementById('vxAiAskBtn');
    const quickButtons = Array.from(document.querySelectorAll('[data-ai-question]'));
    const reopenButton = document.getElementById('vxAiReopenBtn');
    const stateBadge = document.getElementById('vxAiStateBadge');

    if (!(chat instanceof HTMLElement) || !(form instanceof HTMLFormElement) || !(questionInput instanceof HTMLInputElement)) {
        return;
    }

    const assistantReady = <?= json_encode($assistantReady) ?> === true;
    const idleTimeoutSeconds = Number(<?= json_encode($idleTimeoutSeconds) ?>) || 300;
    const reopenUrl = <?= json_encode(url('ayuda-ia/reabrir')) ?>;
    const homeUrl = <?= json_encode(url('ayuda-ia')) ?>;
    const currentSessionId = Number(<?= json_encode($currentSessionId) ?>) || 0;
    const csrfInput = form.querySelector('input[name="_token"]');
    const csrfToken = csrfInput instanceof HTMLInputElement ? csrfInput.value : '';

    let chatClosed = <?= json_encode($chatClosed) ?> === true;
    let lastActivityAt = Date.now();

    const appendMessage = (text, type) => {
        const box = document.createElement('div');
        box.className = 'vx-ai-msg ' + (type === 'user'
            ? 'vx-ai-msg-user'
            : (type === 'system' ? 'vx-ai-msg-system' : 'vx-ai-msg-bot'));
        box.textContent = text;
        chat.appendChild(box);
        chat.scrollTop = chat.scrollHeight;
    };

    const appendTyping = () => {
        const box = document.createElement('div');
        box.className = 'vx-ai-msg vx-ai-msg-bot';
        box.id = 'vxAiTyping';
        box.textContent = 'Pensando...';
        chat.appendChild(box);
        chat.scrollTop = chat.scrollHeight;
    };

    const removeTyping = () => {
        const typing = document.getElementById('vxAiTyping');
        if (typing) {
            typing.remove();
        }
    };

    const setControlsState = (enabled) => {
        if (askButton instanceof HTMLButtonElement) {
            askButton.disabled = !enabled;
        }
        questionInput.disabled = !enabled;
        quickButtons.forEach((button) => {
            button.disabled = !enabled;
        });
    };

    const updateStateBadge = () => {
        if (!(stateBadge instanceof HTMLElement)) {
            return;
        }

        if (chatClosed) {
            stateBadge.classList.remove('text-bg-info');
            stateBadge.classList.add('text-bg-secondary');
            stateBadge.textContent = 'Cerrado por inactividad';
        } else {
            stateBadge.classList.remove('text-bg-secondary');
            stateBadge.classList.add('text-bg-info');
            stateBadge.textContent = 'Sesión de chat activa';
        }
    };

    const setChatClosed = (closed, reasonText = '') => {
        chatClosed = closed;
        setControlsState(assistantReady && !chatClosed);
        updateStateBadge();

        if (reopenButton instanceof HTMLButtonElement) {
            reopenButton.classList.toggle('d-none', !chatClosed);
        }

        if (reasonText !== '') {
            appendMessage(reasonText, 'system');
        }
    };

    const touchActivity = () => {
        if (chatClosed) {
            return;
        }
        lastActivityAt = Date.now();
    };

    const bootstrapClosedNotice = document.getElementById('vxAiClosedServerNotice');
    if (bootstrapClosedNotice) {
        chat.scrollTop = chat.scrollHeight;
    }

    setControlsState(assistantReady && !chatClosed);
    updateStateBadge();

    quickButtons.forEach((button) => {
        button.addEventListener('click', () => {
            if (chatClosed) {
                return;
            }

            const value = String(button.getAttribute('data-ai-question') || '').trim();
            if (value !== '') {
                questionInput.value = value;
                questionInput.focus();
                touchActivity();
            }
        });
    });

    if (reopenButton instanceof HTMLButtonElement) {
        reopenButton.addEventListener('click', async () => {
            if (!assistantReady) {
                return;
            }

            reopenButton.disabled = true;
            try {
                const body = new FormData();
                body.set('_token', csrfToken);
                if (currentSessionId > 0) {
                    body.set('session_id', String(currentSessionId));
                }

                const response = await fetch(reopenUrl, {
                    method: 'POST',
                    body,
                    headers: {
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    credentials: 'same-origin'
                });

                let payload = {};
                try {
                    payload = await response.json();
                } catch (_) {
                    payload = {};
                }

                if (!response.ok || !payload || payload.ok !== true) {
                    const message = String((payload && payload.message) || 'No se pudo reabrir el chat.');
                    appendMessage(message, 'system');
                    return;
                }

                window.location.href = homeUrl;
            } catch (_) {
                appendMessage('Error al reabrir el chat. Intenta de nuevo.', 'system');
            } finally {
                reopenButton.disabled = false;
            }
        });
    }

    form.addEventListener('submit', async (event) => {
        event.preventDefault();

        if (chatClosed) {
            appendMessage('El chat está cerrado por inactividad. Pulsa "Reabrir chat".', 'system');
            return;
        }

        const question = questionInput.value.trim();
        if (question === '') {
            return;
        }

        touchActivity();
        appendMessage(question, 'user');
        questionInput.value = '';
        questionInput.focus();
        appendTyping();

        if (askButton instanceof HTMLButtonElement) {
            askButton.disabled = true;
        }
        questionInput.disabled = true;

        const body = new FormData(form);
        body.set('pregunta', question);

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                body,
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                credentials: 'same-origin'
            });

            let payload = {};
            try {
                payload = await response.json();
            } catch (_) {
                payload = {};
            }

            removeTyping();
            if (!response.ok || !payload || payload.ok !== true) {
                const message = String((payload && payload.message) || 'No fue posible obtener respuesta del asistente.');
                appendMessage(message, 'system');

                if (String(payload && payload.code || '') === 'chat_idle_timeout' || response.status === 440) {
                    setChatClosed(true, 'La sesión de chat se cerró por inactividad.');
                }
                return;
            }

            const answer = String(payload.answer || '').trim();
            appendMessage(answer !== '' ? answer : 'No hubo contenido en la respuesta.', 'bot');
            touchActivity();
        } catch (_) {
            removeTyping();
            appendMessage('Error de conexión con el asistente IA. Intenta nuevamente.', 'system');
        } finally {
            if (askButton instanceof HTMLButtonElement) {
                askButton.disabled = false;
            }
            questionInput.disabled = false;
            if (chatClosed || !assistantReady) {
                setControlsState(false);
            }
        }
    });

    ['click', 'keydown', 'mousemove', 'touchstart'].forEach((eventName) => {
        document.addEventListener(eventName, touchActivity, { passive: true });
    });

    window.setInterval(() => {
        if (!assistantReady || chatClosed) {
            return;
        }

        const idleMs = Date.now() - lastActivityAt;
        if (idleMs >= idleTimeoutSeconds * 1000) {
            setChatClosed(true, 'Chat cerrado automáticamente por inactividad.');
        }
    }, 10000);
});
</script>
