<?php
/**
 * index.php — front controller único. Todas las URLs amigables pasan por aquí
 * (ver .htaccess). Nunca se expone .php ni ?module= en las URLs.
 */
include_once __DIR__ . '/config.php';

// --- Rutas públicas / especiales (sin el chrome de la app) ---
if ($_module === 'logout') {
    $auth->logout();
    App::redirect('/login/');
}
if ($_module === 'login' || $_module === 'register') {
    include __DIR__ . '/modules/auth/' . $_module . '.php';
    exit;
}
// OAuth (KamiQuery): páginas standalone (sin chrome). authorize exige login (se autoprotege).
if ($_module === 'oauth') {
    $sec = in_array($_section, array('authorize', 'token'), true) ? $_section : 'authorize';
    include __DIR__ . '/modules/oauth/' . $sec . '.php';
    exit;
}
// Descarga pública: enlace estable que SIEMPRE redirige a la última versión.
if ($_module === 'download') {
    $u  = '';
    $mf = __DIR__ . '/_files/extension/latest.json';
    if (is_file($mf)) {
        $m = json_decode((string)file_get_contents($mf), true);
        if (is_array($m)) { $u = (string)($m['url'] ?? ''); }
    }
    if ($u === '') { http_response_code(404); die('404'); }
    header('Location: ' . $u, true, 302);
    exit;
}

// API pública (telemetría de la extensión).
if ($_module === 'api') {
    $sec = in_array($_section, array('telemetry'), true) ? $_section : '';
    if ($sec === '') { http_response_code(404); die('404'); }
    include __DIR__ . '/modules/api/' . $sec . '.php';
    exit;
}

// Admin solo para administradores.
if ($_module === 'admin' && empty($_user['is_admin'])) {
    App::redirect('/chat/');
}

// Organización solo para cuentas de organización (o admins, que pueden ver todo).
if ($_module === 'org' && empty($_user['is_org']) && empty($_user['is_admin'])) {
    App::redirect('/chat/');
}

// --- Resolución segura de la sección (requiere sesión, garantizada por config) ---
$base = __DIR__ . '/modules/' . $_module;
$file = $base . '/' . $_section . '.php';
if (!is_file($file)) {
    $file = is_file($base . '/index.php') ? $base . '/index.php'
                                          : __DIR__ . '/modules/home/index.php';
    if (!is_file($file)) { http_response_code(404); die('404'); }
}

$page_title    = '';
$page_subtitle = '';
$page_actions  = '';

ob_start();
include $file;
$content = ob_get_clean();

if ($page_title === '') $page_title = App::t($headers->titleKey($_module, $_section));
$lang     = App::locale();
$langpath = App::url($_path !== '' ? $_path : 'chat');

// Productos / navegación: [module, url, label-key, icono svg].
$svg = 'xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5 shrink-0"';
$nav = array(
    array('chat',    '/chat/',    'nav.chat',    '<svg ' . $svg . '><path stroke-linecap="round" stroke-linejoin="round" d="M21 11.5a8.4 8.4 0 0 1-8.5 8.5 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7A8.4 8.4 0 0 1 12.5 3 8.4 8.4 0 0 1 21 11.5z"/></svg>'),
    array('code',    '/code/',    'nav.code',    '<svg ' . $svg . '><path stroke-linecap="round" stroke-linejoin="round" d="m16 18 6-6-6-6M8 6l-6 6 6 6"/></svg>'),
);
$initial = strtoupper(mb_substr($_user['name'], 0, 1));

// En el área de admin el sidebar de productos se reemplaza por el de admin.
$isAdminArea = ($_module === 'admin');
$navAdmin = array(
    array('/admin/usage/',  'usage',  'admin.menu_usage',  '<svg ' . $svg . '><path stroke-linecap="round" stroke-linejoin="round" d="M3 3v18h18M7 14l3-3 3 3 5-6"/></svg>'),
    array('/admin/users/',  'users',  'admin.menu_users',  '<svg ' . $svg . '><path stroke-linecap="round" stroke-linejoin="round" d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path stroke-linecap="round" stroke-linejoin="round" d="M22 21v-2a4 4 0 0 0-3-3.87"/></svg>'),
    array('/admin/plans/',  'plans',  'admin.menu_plans',  '<svg ' . $svg . '><rect x="2" y="5" width="20" height="14" rx="2"/><path stroke-linecap="round" stroke-linejoin="round" d="M2 10h20"/></svg>'),
    array('/admin/config/', 'config',  'admin.menu_config', '<svg ' . $svg . '><circle cx="12" cy="12" r="3"/><path stroke-linecap="round" stroke-linejoin="round" d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>'),
);

// Área de Organización (cuentas is_org): gestiona sus cuentas y ve su uso.
$isOrgArea = ($_module === 'org');
$navOrg = array(
    array('/org/',       'index', 'org.accounts',    '<svg ' . $svg . '><path stroke-linecap="round" stroke-linejoin="round" d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path stroke-linecap="round" stroke-linejoin="round" d="M22 21v-2a4 4 0 0 0-3-3.87"/></svg>'),
    array('/org/usage/', 'usage', 'org.usage_title', '<svg ' . $svg . '><path stroke-linecap="round" stroke-linejoin="round" d="M3 3v18h18M7 14l3-3 3 3 5-6"/></svg>'),
);

// En Perfil, el sidebar también muestra sus secciones (mismo patrón que Admin, sin borde).
$isProfileArea = ($_module === 'profile');
$navProfile = array(
    array('/profile/',          'index',    'menu.preferences', '<svg ' . $svg . '><circle cx="12" cy="12" r="3"/><path stroke-linecap="round" stroke-linejoin="round" d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>'),
    array('/profile/sessions/', 'sessions', 'menu.sessions',    '<svg ' . $svg . '><rect x="2" y="3" width="20" height="14" rx="2"/><path stroke-linecap="round" stroke-linejoin="round" d="M8 21h8M12 17v4"/></svg>'),
);
if (!empty($_user['is_admin'])) {
    $navProfile[] = array('/profile/invites/', 'invites', 'menu.invites', '<svg ' . $svg . '><rect x="3" y="5" width="18" height="14" rx="2"/><path stroke-linecap="round" stroke-linejoin="round" d="m3 7 9 6 9-6"/></svg>');
}

// Áreas que reemplazan el sidebar de productos y muestran "Volver a la app".
$isAreaNav = $isAdminArea || $isProfileArea || $isOrgArea;
$areaTitle = $isAdminArea ? 'nav.admin' : ($isOrgArea ? 'org.title' : ($isProfileArea ? 'profile.title' : 'app.name'));
$areaNav   = $isAdminArea ? $navAdmin : ($isOrgArea ? $navOrg : $navProfile);
// "Modelos" es una pestaña dentro de Configuración → resalta Configuración en el lateral.
$activeSection = ($isAdminArea && $_section === 'models') ? 'config' : $_section;
?><!doctype html>
<html lang="<?= App::e($lang) ?>" class="h-full">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/assets/favicon.svg">
<title><?= App::e($headers->title($_module, $_section)) ?></title>
<script>
// Día/noche + estado del menú antes de pintar (sin parpadeo).
(function () {
  var t = localStorage.getItem('theme');
  if (t === 'dark' || (!t && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
    document.documentElement.classList.add('dark');
  }
  if (localStorage.getItem('sidebar') === 'collapsed') {
    document.documentElement.classList.add('sidebar-collapsed');
  }
})();
</script>
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body class="h-full bg-paper text-ink-900 dark:bg-ink-950 dark:text-paper">
<div class="flex h-full">

  <!-- Sidebar (productos, o Admin con borde verde de 4px) -->
  <aside class="flex w-64 shrink-0 flex-col border-r border-gray-200 bg-white text-ink-900 transition-all duration-200 collapsed:w-16 max-md:hidden dark:border-ink-700 dark:bg-ink-900 dark:text-paper<?= ($isAdminArea || $isOrgArea) ? ' border-l-4 border-l-primary-600' : '' ?>">

    <!-- Logo + botón colapsar -->
    <div class="flex items-center px-3 py-4 collapsed:justify-center">
      <a href="/chat/" class="flex items-center gap-2 collapsed:hidden">
        <span class="flex h-8 w-8 items-center justify-center rounded-lg bg-primary-600 font-bold text-white">k</span>
        <span class="font-semibold"><?= App::e(App::t($areaTitle)) ?></span>
      </a>
      <button type="button" data-sidebar-toggle title="<?= App::e(App::t('sidebar.toggle')) ?>" aria-label="<?= App::e(App::t('sidebar.toggle')) ?>"
              class="ml-auto flex h-8 w-8 items-center justify-center rounded-md text-gray-dark hover:bg-gray-100 hover:text-ink-900 collapsed:ml-0 dark:text-gray-light dark:hover:bg-ink-800 dark:hover:text-white">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5 transition-transform collapsed:rotate-180"><path stroke-linecap="round" stroke-linejoin="round" d="m15 18-6-6 6-6"/></svg>
      </button>
    </div>

    <?php if ($isAreaNav): ?>
      <!-- Navegación del área (Admin / Perfil) -->
      <nav class="flex-1 space-y-1 px-3 py-2 text-sm">
        <?php foreach ($areaNav as $it):
          $active = ($activeSection === $it[1]); ?>
          <a href="<?= $it[0] ?>" title="<?= App::e(App::t($it[2])) ?>"
             class="flex items-center gap-3 rounded-md px-3 py-2 collapsed:justify-center <?= $active
                  ? 'bg-primary-50 font-medium text-primary-700 dark:bg-primary-900/30 dark:text-primary-300'
                  : 'text-gray-dark hover:bg-gray-100 hover:text-ink-900 dark:text-gray-light dark:hover:bg-ink-800 dark:hover:text-white' ?>">
            <?= $it[3] ?>
            <span class="collapsed:hidden"><?= App::e(App::t($it[2])) ?></span>
          </a>
        <?php endforeach; ?>
      </nav>
    <?php else: ?>
      <!-- Nuevo chat -->
      <a href="/chat/" title="<?= App::e(App::t('nav.new_chat')) ?>"
         class="mx-3 mb-2 flex items-center justify-center gap-2 rounded-lg bg-primary-600 px-3 py-2 text-sm font-medium text-white hover:bg-primary-700 collapsed:mx-2 collapsed:px-0">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5 shrink-0"><path stroke-linecap="round" stroke-linejoin="round" d="M12 5v14M5 12h14"/></svg>
        <span class="collapsed:hidden"><?= App::e(App::t('nav.new_chat')) ?></span>
      </a>
      <nav class="flex-1 space-y-1 px-3 py-2 text-sm">
        <?php foreach ($nav as $it):
          $active = ($_module === $it[0]); ?>
          <a href="<?= $it[1] ?>" title="<?= App::e(App::t($it[2])) ?>"
             class="flex items-center gap-3 rounded-md px-3 py-2 collapsed:justify-center <?= $active
                  ? 'bg-primary-50 font-medium text-primary-700 dark:bg-primary-900/30 dark:text-primary-300'
                  : 'text-gray-dark hover:bg-gray-100 hover:text-ink-900 dark:text-gray-light dark:hover:bg-ink-800 dark:hover:text-white' ?>">
            <?= $it[3] ?>
            <span class="collapsed:hidden"><?= App::e(App::t($it[2])) ?></span>
          </a>
        <?php endforeach; ?>
      </nav>
    <?php endif; ?>

    <div class="border-t border-gray-200 px-3 py-3 dark:border-ink-700">
      <?php if ($isAreaNav): ?>
      <!-- Volver a la app, encima del nombre -->
      <a href="/chat/" title="<?= App::e(App::t('admin.back')) ?>"
         class="mb-1 flex items-center gap-2 rounded-md px-2 py-2 text-sm text-gray-dark hover:bg-gray-100 hover:text-ink-900 collapsed:justify-center collapsed:px-0 dark:text-gray-light dark:hover:bg-ink-800 dark:hover:text-white">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5 shrink-0"><path stroke-linecap="round" stroke-linejoin="round" d="m15 18-6-6 6-6"/></svg>
        <span class="collapsed:hidden"><?= App::e(App::t('admin.back')) ?></span>
      </a>
      <?php else: ?>
        <?php if (!empty($_user['is_admin'])): ?>
        <!-- Admin (solo administradores), encima del nombre -->
        <a href="/admin/config/" title="<?= App::e(App::t('nav.admin')) ?>"
           class="mb-1 flex items-center gap-2 rounded-md px-2 py-2 text-sm text-gray-dark hover:bg-gray-100 hover:text-ink-900 collapsed:justify-center collapsed:px-0 dark:text-gray-light dark:hover:bg-ink-800 dark:hover:text-white">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5 shrink-0"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3l7 4v5c0 4.4-3 7.5-7 9-4-1.5-7-4.6-7-9V7l7-4z"/></svg>
          <span class="collapsed:hidden"><?= App::e(App::t('nav.admin')) ?></span>
        </a>
        <?php endif; ?>
        <?php if (!empty($_user['is_org'])): ?>
        <!-- Organización (cuentas is_org), encima del nombre -->
        <a href="/org/" title="<?= App::e(App::t('org.title')) ?>"
           class="mb-1 flex items-center gap-2 rounded-md px-2 py-2 text-sm text-gray-dark hover:bg-gray-100 hover:text-ink-900 collapsed:justify-center collapsed:px-0 dark:text-gray-light dark:hover:bg-ink-800 dark:hover:text-white">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-5 w-5 shrink-0"><path stroke-linecap="round" stroke-linejoin="round" d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path stroke-linecap="round" stroke-linejoin="round" d="M22 21v-2a4 4 0 0 0-3-3.87"/></svg>
          <span class="collapsed:hidden"><?= App::e(App::t('org.title')) ?></span>
        </a>
        <?php endif; ?>
      <?php endif; ?>

      <!-- Cuenta: avatar + nombre + ruedita -> desplegable (tema, idioma, preferencias, API, salir) -->
      <div class="relative">
        <button type="button" data-account-toggle
                class="flex w-full items-center gap-2 rounded-md px-2 py-2 hover:bg-gray-100 collapsed:justify-center collapsed:px-0 dark:hover:bg-ink-800">
          <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-600 text-xs font-bold text-white"><?= App::e($initial) ?></span>
          <span class="min-w-0 flex-1 truncate text-left text-sm collapsed:hidden"><?= App::e($_user['name']) ?></span>
          <svg class="h-4 w-4 shrink-0 text-gray-dark collapsed:hidden dark:text-gray-light" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path stroke-linecap="round" stroke-linejoin="round" d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
        </button>
        <div data-account-menu class="absolute bottom-full left-0 mb-2 hidden w-56 overflow-hidden rounded-lg border border-gray-200 bg-white py-1 text-sm shadow-lg dark:border-ink-700 dark:bg-ink-800">

          <!-- Modo día / noche -->
          <button type="button" data-theme-toggle class="flex w-full items-center justify-between px-4 py-2 hover:bg-gray-100 dark:hover:bg-ink-700">
            <span class="flex items-center gap-2">
              <svg data-theme-dark xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="h-4 w-4"><path stroke-linecap="round" stroke-linejoin="round" d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"/></svg>
              <svg data-theme-light class="hidden h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="4"/><path stroke-linecap="round" stroke-linejoin="round" d="M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
              <span data-theme-dark><?= App::e(App::t('theme.dark')) ?></span>
              <span data-theme-light class="hidden"><?= App::e(App::t('theme.light')) ?></span>
            </span>
          </button>

          <!-- Idioma -->
          <div class="flex items-center justify-between px-4 py-2">
            <span class="text-gray-dark dark:text-gray-light"><?= App::e(App::t('lang.label')) ?></span>
            <span class="flex items-center gap-1">
              <?php foreach (($_config['locales'] ?? array()) as $lc): $on = ($lc === $lang); ?>
                <a href="<?= App::e($langpath) ?>?lang=<?= App::e($lc) ?>"
                   class="rounded px-2 py-0.5 text-xs font-semibold <?= $on
                        ? 'bg-primary-50 text-primary-700 dark:bg-primary-900/30 dark:text-primary-300'
                        : 'text-gray-dark hover:bg-gray-100 dark:text-gray-light dark:hover:bg-ink-700' ?>">
                  <?= strtoupper(App::e($lc)) ?>
                </a>
              <?php endforeach; ?>
            </span>
          </div>

          <div class="my-1 border-t border-gray-200 dark:border-ink-700"></div>

          <a href="/profile/" class="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-ink-700"><?= App::e(App::t('menu.preferences')) ?></a>
          <a href="/logout/" class="block px-4 py-2 text-danger hover:bg-danger/10"><?= App::e(App::t('nav.logout')) ?></a>
        </div>
      </div>
    </div>
  </aside>

  <!-- Columna principal -->
  <div class="flex min-w-0 flex-1 flex-col">
    <header class="sticky top-0 z-30 border-b border-gray-200 bg-white/80 px-4 py-3 backdrop-blur-md dark:border-ink-700 dark:bg-ink-900/80">
      <div class="flex items-center justify-between gap-3">
        <div class="min-w-0">
          <h1 class="truncate text-lg font-semibold"><?= App::e($page_title) ?></h1>
          <?php if ($page_subtitle): ?><p class="truncate text-sm text-gray-dark dark:text-gray-light"><?= App::e($page_subtitle) ?></p><?php endif; ?>
        </div>
        <div class="flex items-center gap-2"><?= $page_actions ?></div>
      </div>
    </header>

    <main class="min-h-0 flex-1 overflow-y-auto"><?= $content ?></main>
  </div>
</div>

<script src="/assets/js/app.js"></script>
</body>
</html>
