<?php
/**
 * modules/chat/index.php — conversación.
 * ?new=1 -> chat nuevo · ?id=N -> abre la conversación N.
 */
if (!defined('IN_APP')) { die('Acceso denegado'); }

$chat = new Chat($mysqli, $_config);
$id   = (int)$_id;   // /chat -> nuevo · /chat/{id} -> conversación

// Enviar mensaje.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $res = $chat->send($_user['id_user'], $id, $_POST['message']);
    if ($res !== null) App::redirect('/chat/' . $res[0] . '/');
}

$messages = $id ? $chat->messages($id, $_user['id_user']) : array();

$page_title   = App::t('chat.title');
$post_url     = $id ? '/chat/' . $id . '/' : '/chat/';
$page_actions = '<a href="/chat/history/" class="rounded-lg border border-gray-200 px-3 py-1.5 text-sm hover:bg-gray-50 dark:border-ink-700 dark:hover:bg-ink-800">'
              . App::e(App::t('nav.history')) . '</a>';
?>
<div class="mx-auto flex h-full max-w-3xl flex-col">

  <!-- Hilo -->
  <div data-chat-thread class="flex-1 space-y-6 overflow-y-auto px-4 py-6">
    <?php if (!$messages): ?>
      <div class="flex h-full min-h-[40vh] items-center justify-center text-center">
        <p class="text-lg text-gray-dark dark:text-gray-light"><?= App::e(App::t('chat.empty')) ?></p>
      </div>
    <?php else: foreach ($messages as $m):
      $isUser = ($m['role'] === 'user'); ?>
      <div class="flex gap-3 <?= $isUser ? 'flex-row-reverse' : '' ?>">
        <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold <?= $isUser ? 'bg-ink-700 text-white' : 'bg-primary-600 text-white' ?>">
          <?= $isUser ? App::e(mb_substr($_user['name'], 0, 1)) : 'k' ?>
        </div>
        <div class="max-w-[80%] rounded-lg px-4 py-2 text-sm leading-relaxed <?= $isUser
              ? 'bg-primary-600 text-white'
              : 'border border-gray-200 bg-white text-ink-900 dark:border-ink-700 dark:bg-ink-900 dark:text-paper' ?>">
          <?= nl2br(App::e($m['content'])) ?>
        </div>
      </div>
    <?php endforeach; endif; ?>
  </div>

  <!-- Barra de entrada -->
  <div class="sticky bottom-0 border-t border-gray-200 bg-paper/90 px-4 py-3 backdrop-blur-md dark:border-ink-700 dark:bg-ink-950/90">
    <form method="post" action="<?= App::e($post_url) ?>" class="flex items-end gap-2">
      <textarea name="message" data-autosize rows="1" required
                placeholder="<?= App::e(App::t('chat.placeholder')) ?>"
                class="max-h-40 flex-1 resize-none rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm outline-none focus:border-primary-600 dark:border-ink-700 dark:bg-ink-900"></textarea>
      <button type="submit"
              class="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700">
        <?= App::e(App::t('chat.send')) ?>
      </button>
    </form>
  </div>
</div>
