<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

$page_title = 'Inbox - Vale';
ob_start();
?>
<div class="dashboard-container<?php echo $selected_conversation ? ' inbox-open' : ''; ?>">
    <!-- Sidebar Navigation -->
    <?php $activeNav = 'mensajes'; require __DIR__ . '/partials/sidebar.php'; ?>

    <!-- Main Content Area -->
    <main class="main-content">
        <?php if (!empty($_SESSION['impersonated_by_admin'])): ?>
            <div style="background:#E0A33E;color:#221C18;padding:.5rem 1rem;font-size:.85rem;display:flex;justify-content:space-between;align-items:center;">
                <span>Estás viendo como <strong><?php echo htmlspecialchars($_SESSION['tenant_name'] ?? 'negocio'); ?></strong> (impersonación de admin).</span>
                <a href="/admin/stop-impersonate" style="color:#A8331A;font-weight:600;">Salir de impersonación</a>
            </div>
        <?php endif; ?>
        <!-- Header Bar -->
        <header class="header-bar">
            <h2>Mensajes del Negocio</h2>
            <div class="tenant-badge">
                <?php echo htmlspecialchars($_SESSION['tenant_name'] ?? 'Negocio'); ?>
            </div>
        </header>

        <!-- Inbox Grid -->
        <div class="inbox-grid <?php echo $selected_conversation ? 'has-selection' : ''; ?>">
            <!-- Left Pane: Conversations List -->
            <div class="conversations-pane">
                <div class="pane-title">Conversaciones Recientes</div>
                <ul class="conversation-list">
                    <?php if (empty($conversations)): ?>
                        <li class="pane-empty">
                            <svg width="44" height="44" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" 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"></path>
                            </svg>
                            <p>Todavía no hay conversaciones.<br>Vale las irá capturando solas.</p>
                        </li>
                    <?php else: ?>
                        <?php foreach ($conversations as $conv): ?>
                            <?php
                            $isActive = $selected_conversation && $selected_conversation['id'] == $conv['id'];
                            $lastMsg = $conv['last_message_body'] ?: '(Sin mensajes)';
                            $timeStr = $conv['last_message_time'] ? date('H:i', strtotime($conv['last_message_time'])) : '';
                            $displayName = $conv['contact_name'] ?: $conv['contact_phone'] ?: '?';
                            $nameParts = preg_split('/\s+/', trim($displayName));
                            $ini = mb_substr($nameParts[0], 0, 1);
                            if (count($nameParts) > 1) { $ini .= mb_substr(end($nameParts), 0, 1); }
                            ?>
                            <li class="conversation-item <?php echo $isActive ? 'active' : ''; ?>">
                                <a href="/inbox?conversation_id=<?php echo (int)$conv['id']; ?>">
                                    <div class="avatar"><?php echo htmlspecialchars($ini); ?></div>
                                    <div class="conv-body">
                                        <div class="conv-header">
                                            <span class="conv-name"><?php echo htmlspecialchars($displayName); ?></span>
                                            <span class="conv-time"><?php echo htmlspecialchars($timeStr); ?></span>
                                        </div>
                                        <div class="conv-meta">
                                            <span class="conv-last-msg"><?php echo htmlspecialchars($lastMsg); ?></span>
                                            <?php
                                            $listStatusMap = ['open'=>'Activa','closed'=>'Cerrada','needs_owner'=>'Revisión'];
                                            $listStatusLabel = $listStatusMap[$conv['status']] ?? ucfirst($conv['status']);
                                            ?>
                                            <span class="badge badge-<?php echo htmlspecialchars($conv['status']); ?>">
                                                <?php echo htmlspecialchars($listStatusLabel); ?>
                                            </span>
                                        </div>
                                    </div>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
            </div>

            <!-- Right Pane: Active Chat Window -->
            <div class="chat-pane">
                <?php if (!$selected_conversation): ?>
                    <div class="chat-empty">
                        <svg style="width: 64px; height: 64px; color: var(--color-border); margin-bottom: 1.5rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" 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"></path>
                        </svg>
                        <h3>No hay chat seleccionado</h3>
                        <p>Selecciona una conversación de la lista para ver el historial.</p>
                    </div>
                <?php else: ?>
                    <!-- Active Chat Header -->
                    <?php
                    $chatName = $contact['name'] ?: ($contact['phone'] ?? 'Cliente');
                    $chatParts = preg_split('/\s+/', trim($chatName));
                    $chatIni = mb_substr($chatParts[0], 0, 1);
                    if (count($chatParts) > 1) { $chatIni .= mb_substr(end($chatParts), 0, 1); }
                    ?>
                    <div class="chat-header">
                        <div style="display:flex;align-items:center;gap:0.75rem;min-width:0;">
                            <a href="/inbox" class="mobile-back" aria-label="Volver">&larr;</a>
                            <div class="avatar avatar-sm"><?php echo htmlspecialchars($chatIni); ?></div>
                            <div class="chat-contact-info">
                                <h3><?php echo htmlspecialchars($contact['name'] ?? 'Cliente'); ?></h3>
                                <p><?php echo htmlspecialchars($contact['phone'] ?? ''); ?></p>
                            </div>
                        </div>
                        <?php
                        $convStatusMap = ['open'=>'Activa','closed'=>'Cerrada','needs_owner'=>'En revisión'];
                        $convStatusLabel = $convStatusMap[$selected_conversation['status']] ?? ucfirst($selected_conversation['status']);
                        ?>
                        <div>
                            <span class="badge badge-<?php echo htmlspecialchars($selected_conversation['status']); ?>">
                                <?php echo htmlspecialchars($convStatusLabel); ?>
                            </span>
                        </div>
                    </div>

                    <!-- Chat Message Logs -->
                    <div class="chat-history">
                        <?php if (empty($messages)): ?>
                            <div style="text-align: center; color: var(--color-text-muted); padding: 2rem;">
                                No hay mensajes en esta conversación.
                            </div>
                        <?php else: ?>
                            <?php foreach ($messages as $msg): ?>
                                <?php 
                                $isInbound = $msg['direction'] === 'inbound';
                                $bubbleClass = $isInbound ? 'msg-inbound' : 'msg-outbound';
                                $senderName = $isInbound ? ($contact['name'] ?: 'Cliente') : 'Vale';
                                if (!$isInbound && $msg['sender'] === 'human') {
                                    $senderName = 'Soporte';
                                }
                                $msgTime = date('H:i', strtotime($msg['created_at']));
                                ?>
                                <div class="message-bubble <?php echo $bubbleClass; ?>">
                                    <p style="white-space: pre-wrap;"><?php echo htmlspecialchars($msg['body']); ?></p>
                                    <div class="msg-meta">
                                        <span class="msg-sender-badge"><?php echo htmlspecialchars($senderName); ?></span>
                                        <div style="display: flex; gap: 8px; align-items: center;">
                                            <?php if (!$isInbound && $msg['model_tokens']): ?>
                                                <span class="tokens-badge"><?php echo (int)$msg['model_tokens']; ?> tkn</span>
                                            <?php endif; ?>
                                            <span><?php echo htmlspecialchars($msgTime); ?></span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>
<script>
  (function () {
    var hasSelection = <?php echo $selected_conversation ? 'true' : 'false'; ?>;
    if (hasSelection) {
      // Hide bottom nav so it doesn't overlap the chat
      var bn = document.querySelector('.bottom-nav');
      if (bn) bn.classList.add('hidden');

      // Scroll chat to the most recent message
      var history = document.querySelector('.chat-history');
      if (history) history.scrollTop = history.scrollHeight;
    } else {
      setTimeout(function () { window.location.reload(); }, 30000);
    }
  })();
</script>
<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/views/layout.php';
