<?php
/**
 * TechShop Perú - Header Global
 * 
 * Cabecera común con navbar, buscador, carrito y menú de categorías.
 * 
 * @package TechShop Perú
 * @version 1.0
 */

if (!defined('SECURE_ACCESS')) {
    define('SECURE_ACCESS', true);
}
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/database.php';
require_once __DIR__ . '/functions.php';

// Obtener categorías activas para el menú
try {
    $stmt_cats = db()->query('SELECT id, nombre, slug, icono FROM categorias WHERE activo = 1 ORDER BY orden');
    $categorias_menu = $stmt_cats->fetchAll();
} catch (PDOException $e) {
    $categorias_menu = [];
}

$cart_items = cart_count();
$cart_subtotal = cart_total();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="TechShop Perú - Tienda de tecnología con envíos a todo el Perú. Laptops, computadoras, componentes, celulares y más.">
    <meta name="keywords" content="tecnología Perú, laptops, computadoras, celulares, componentes, gaming, tienda tech">
    <meta name="author" content="TechShop Perú">
    <meta name="robots" content="index, follow">
    <meta property="og:title" content="TechShop Perú - Tecnología al alcance de todo el Perú">
    <meta property="og:description" content="Tienda de productos tecnológicos con cobertura nacional. Las mejores marcas y precios.">
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?= BASE_URL ?>">
    <title><?= isset($page_title) ? e($page_title) . ' | ' : '' ?>TechShop Perú - Tecnología al alcance de todo el Perú</title>

    <!-- PWA (Progressive Web App) -->
    <link rel="manifest" href="<?= BASE_URL ?>/manifest.json">
    <meta name="theme-color" content="#2563eb">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="TechShop PE">

    <!-- Google Fonts (Outfit & Inter) -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@600;700;800&display=swap" rel="stylesheet">

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Estilos personalizados (v=filemtime para invalidar caché al actualizar) -->
    <?php $cssVersion = @filemtime(ROOT_PATH . 'assets/css/styles.css'); ?>
    <link href="<?= ASSETS_URL ?>/css/styles.css?v=<?= $cssVersion ?: '1' ?>" rel="stylesheet">
    <!-- Favicon -->
    <link rel="icon" type="image/svg+xml" href="<?= ASSETS_URL ?>/images/favicon.svg">
    <!-- CSRF Token para peticiones AJAX -->
    <meta name="csrf-token" content="<?= csrf_token() ?>">

    <script>
      // Dark mode: aplicar ANTES del primer render para evitar flash
      (function(){
        var t = localStorage.getItem('ts-theme');
        if (t === 'dark' || (!t && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
          document.documentElement.setAttribute('data-dark', '1');
        }
      })();
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('<?= BASE_URL ?>/sw.js').catch(function(){});
        });
      }
    </script>
</head>
<body data-base-url="<?= BASE_URL ?>">
<script>if(document.documentElement.getAttribute('data-dark')==='1'){document.body.classList.add('dark-theme');}</script>

<!-- ════ BANNER GLOBAL DE ANUNCIOS (Mejora 19) ════════════════ -->
<?php
$announcementBar = null;
try {
    $cfgTable = config_table_name();
    $stmtBanner = db()->query("SELECT valor FROM `{$cfgTable}` WHERE clave = 'announcement_bar' LIMIT 1");
    if ($stmtBanner) $announcementBar = $stmtBanner->fetchColumn();
} catch (Exception $e) { $announcementBar = null; }
if (!empty($announcementBar)):
    $barData = json_decode($announcementBar, true);
    if (!empty($barData['activo']) && !empty($barData['texto'])):
?>
<div class="global-announcement-bar" id="global-announcement-bar" role="alert">
    <i class="bi bi-megaphone-fill me-2"></i>
    <?= htmlspecialchars_decode(e($barData['texto'])) ?>
    <?php if (!empty($barData['link_url']) && !empty($barData['link_texto'])): ?>
    <a href="<?= e($barData['link_url']) ?>" class="ms-2"><?= e($barData['link_texto']) ?></a>
    <?php endif; ?>
    <button class="btn-close-bar" id="close-announcement-bar" aria-label="Cerrar anuncio" title="Cerrar">
        <i class="bi bi-x-lg"></i>
    </button>
</div>
<script>
(function(){
    var bar = document.getElementById('global-announcement-bar');
    var closeBtn = document.getElementById('close-announcement-bar');
    if (bar && closeBtn) {
        if (sessionStorage.getItem('ts-ann-closed')) { bar.style.display = 'none'; }
        closeBtn.addEventListener('click', function() {
            bar.style.display = 'none';
            sessionStorage.setItem('ts-ann-closed', '1');
        });
    }
})();
</script>
<?php endif; endif; ?>

<!-- ════ TICKER DE OFERTAS ════════════════════════════════ -->
<div class="offers-ticker d-none d-md-flex overflow-hidden align-items-center" style="height:32px;">
  <div class="ticker-track">
    <?php for($ti=0;$ti<2;$ti++): ?>
    <span class="ticker-item"><i class="bi bi-truck me-1"></i> Envío gratis a Lima en pedidos +S/&nbsp;199</span>
    <span class="ticker-item"><i class="bi bi-lightning-charge-fill me-1"></i> Hasta 30% OFF en laptops seleccionadas</span>
    <span class="ticker-item"><i class="bi bi-shield-check me-1"></i> Garantía oficial en todos los productos</span>
    <span class="ticker-item"><i class="bi bi-box-seam me-1"></i> Entrega 24-48h en Lima</span>
    <span class="ticker-item"><i class="bi bi-credit-card me-1"></i> Hasta 12 cuotas sin intereses</span>
    <span class="ticker-item"><i class="bi bi-controller me-1"></i> Nueva colección gaming disponible</span>
    <?php endfor; ?>
  </div>
</div>


<!-- ════ TOP BAR ════════════════════════════════════════════ -->
<div class="top-bar text-white py-1 d-none d-md-block">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-5">
                <small>
                    <a href="tel:<?= e(preg_replace('/[^0-9+]/', '', TIENDA_TELEFONO)) ?>" class="text-white-50 text-decoration-none">
                        <i class="bi bi-telephone me-1"></i> <?= TIENDA_TELEFONO ?>
                    </a>
                    &nbsp;|&nbsp;
                    <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', TIENDA_WHATSAPP) ?>" target="_blank" rel="noopener" class="text-white-50 text-decoration-none">
                        <i class="bi bi-whatsapp me-1"></i> <?= TIENDA_WHATSAPP ?>
                    </a>
                </small>
            </div>
            <div class="col-md-7 text-end d-flex align-items-center justify-content-end gap-3">
                <small class="d-flex gap-3">
                    <a href="<?= url('pages/comparar.php') ?>" class="text-white-50 text-decoration-none"><i class="bi bi-arrow-left-right me-1"></i>Comparar (<span id="compare-count"><?= count($_SESSION['comparar'] ?? []) ?></span>)</a>
                    <a href="<?= url('pages/nosotros.php') ?>" class="text-white-50 text-decoration-none">Nosotros</a>
                    <a href="<?= url('pages/soporte.php') ?>" class="text-white-50 text-decoration-none">Soporte</a>
                </small>
                <!-- Toggle Dark/Light -->
                <div class="d-flex align-items-center gap-2">
                    <i class="bi bi-sun text-warning" style="font-size:.85rem;"></i>
                    <button id="darkModeToggle" aria-label="Cambiar a modo oscuro/claro" title="Alternar tema"></button>
                    <i class="bi bi-moon-stars-fill text-white-50" style="font-size:.85rem;"></i>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- ============================================
     NAVBAR PRINCIPAL
     ============================================ -->
<nav class="navbar navbar-expand-lg bg-white shadow-sm sticky-top main-navbar">
    <div class="container">
        <!-- Logo -->
        <a class="navbar-brand d-flex align-items-center gap-2" href="<?= url('') ?>">
            <span class="brand-icon"><i class="bi bi-cpu"></i></span>
            <span class="brand-text">
                <span class="brand-name">TechShop</span>
                <span class="brand-country">PERÚ</span>
            </span>
        </a>

        <!-- Toggler móvil -->
        <button class="navbar-toggler border-0" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu" aria-controls="mobileMenu">
            <span class="navbar-toggler-icon"></span>
        </button>

        <!-- Menú desktop -->
        <div class="collapse navbar-collapse" id="mainNav">
            <ul class="navbar-nav mx-auto mb-2 mb-lg-0">
                <li class="nav-item">
                    <a class="nav-link <?= is_active('index.php') ?>" href="<?= url('') ?>">Inicio</a>
                </li>
                <li class="nav-item dropdown dropdown-mega">
                    <a class="nav-link dropdown-toggle <?= is_active('pages/productos.php') ?>" href="<?= url('pages/productos.php') ?>" role="button">
                        Productos
                    </a>
                    <div class="dropdown-menu mega-menu p-3">
                        <div class="row g-2">
                            <?php foreach ($categorias_menu as $cat): ?>
                            <div class="col-6 col-md-3">
                                <a href="<?= url('pages/productos.php?categoria=' . $cat['slug']) ?>" 
                                   class="mega-item text-decoration-none d-block p-2 rounded">
                                    <i class="bi bi-<?= e($cat['icono'] ?? 'tag') ?> fs-5 me-2"></i>
                                    <?= e($cat['nombre']) ?>
                                </a>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="text-center mt-2 pt-2 border-top">
                            <a href="<?= url('pages/productos.php') ?>" class="btn btn-sm btn-primary">Ver todos los productos</a>
                        </div>
                    </div>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= is_active('pages/ofertas.php') ?>" href="<?= url('pages/ofertas.php') ?>">Ofertas</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= is_active('pages/marcas.php') ?>" href="<?= url('pages/marcas.php') ?>">Marcas</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= is_active('pages/contacto.php') ?>" href="<?= url('pages/contacto.php') ?>">Contacto</a>
                </li>
            </ul>

            <!-- Buscador con Live Search + Historial de Búsquedas (Mejora 6) -->
            <form class="d-flex me-2 position-relative search-nav-form" action="<?= url('pages/productos.php') ?>" method="GET" role="search" id="search-form-main">
                <div class="input-group search-group">
                    <span class="input-group-text search-prefix"><i class="bi bi-search"></i></span>
                    <input class="form-control" type="search" name="buscar" id="global-search-input" placeholder="Buscar laptops, celulares, componentes..." 
                           aria-label="Buscar" value="<?= e($_GET['buscar'] ?? '') ?>" autocomplete="off">
                    <button class="btn btn-primary" type="submit">
                        Buscar
                    </button>
                </div>
                <div id="search-suggest-box" class="dropdown-menu w-100 shadow border-0 mt-1 p-2" style="display:none; max-height: 400px; overflow-y: auto; z-index: 1050;"></div>
                <div id="search-history-box" class="dropdown-menu w-100 shadow border-0 mt-1 p-0" style="display:none; z-index: 1050; min-width:280px;">
                    <div class="px-3 pt-3 pb-1 d-flex justify-content-between align-items-center">
                        <small class="text-muted fw-semibold"><i class="bi bi-clock-history me-1"></i>Búsquedas recientes</small>
                        <button type="button" class="btn btn-link btn-sm text-danger p-0" id="clear-search-history" style="font-size:.78rem;">Limpiar</button>
                    </div>
                    <ul class="list-group list-group-flush" id="search-history-list"></ul>
                    <div class="px-3 pt-2 pb-1 border-top mt-1">
                        <small class="text-muted fw-semibold"><i class="bi bi-fire me-1 text-danger"></i>Tendencias</small>
                    </div>
                    <ul class="list-group list-group-flush" id="search-trends-list">
                        <?php foreach (['Laptop Gaming', 'Audífonos RGB', 'Monitor 4K', 'SSD NVMe', 'Teclado Mecánico'] as $trend): ?>
                        <li class="list-group-item list-group-item-action py-1 px-3 border-0 search-history-item" data-q="<?= e($trend) ?>" style="cursor:pointer;font-size:.87rem;">
                            <i class="bi bi-trending-up me-2 text-primary"></i><?= e($trend) ?>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </form>

            <!-- Iconos de usuario y carrito -->
            <div class="d-flex align-items-center gap-2">
                <?php if (is_logged_in()): ?>
                    <!-- Usuario autenticado -->
                    <div class="dropdown">
                        <button class="btn btn-outline-dark btn-sm dropdown-toggle d-flex align-items-center gap-1" 
                                type="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i>
                            <span class="d-none d-lg-inline"><?= e($_SESSION['usuario_nombre'] ?? 'Cuenta') ?></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="<?= url('pages/cuenta.php') ?>"><i class="bi bi-person me-2"></i>Mi Cuenta</a></li>
                            <li><a class="dropdown-item" href="<?= url('pages/cuenta.php?tab=pedidos') ?>"><i class="bi bi-box-seam me-2"></i>Mis Pedidos</a></li>
                            <li><a class="dropdown-item" href="<?= url('pages/mis-direcciones.php') ?>"><i class="bi bi-geo-alt me-2"></i>Mis Direcciones</a></li>
                            <li><a class="dropdown-item" href="<?= url('pages/cuenta.php?tab=favoritos') ?>"><i class="bi bi-heart me-2"></i>Favoritos</a></li>
                            <li><a class="dropdown-item" href="<?= url('pages/soporte.php') ?>"><i class="bi bi-headset me-2"></i>Soporte</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="<?= url('pages/logout.php') ?>"><i class="bi bi-box-arrow-right me-2"></i>Cerrar Sesión</a></li>
                        </ul>

                    </div>
                <?php else: ?>
                    <!-- Usuario invitado -->
                    <a href="<?= url('pages/login.php') ?>" class="btn btn-outline-dark btn-sm d-flex align-items-center gap-1">
                        <i class="bi bi-person"></i>
                        <span class="d-none d-lg-inline">Ingresar</span>
                    </a>
                <?php endif; ?>

                <!-- Carrito -->
                <a href="<?= url('pages/carrito.php') ?>" class="btn btn-primary btn-sm position-relative cart-btn">
                    <i class="bi bi-cart3"></i>
                    <?php if ($cart_items > 0): ?>
                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger cart-badge">
                        <?= $cart_items ?>
                    </span>
                    <?php endif; ?>
                </a>
            </div>
        </div>
    </div>
</nav>

<!-- ============================================
     MENÚ MÓVIL (Offcanvas)
     ============================================ -->
<div class="offcanvas offcanvas-start" tabindex="-1" id="mobileMenu" aria-labelledby="mobileMenuLabel">
    <div class="offcanvas-header bg-primary text-white">
        <h5 class="offcanvas-title" id="mobileMenuLabel">
            <i class="bi bi-cpu me-2"></i>TechShop Perú
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Cerrar"></button>
    </div>
    <div class="offcanvas-body">
        <!-- Buscador móvil -->
        <form class="mb-3" action="<?= url('pages/productos.php') ?>" method="GET">
            <div class="input-group">
                <input class="form-control" type="search" name="buscar" placeholder="Buscar...">
                <button class="btn btn-primary"><i class="bi bi-search"></i></button>
            </div>
        </form>

        <ul class="list-group list-group-flush">
            <li><a href="<?= url('') ?>" class="list-group-item list-group-item-action"><i class="bi bi-house me-2"></i>Inicio</a></li>
            <li><a href="<?= url('pages/productos.php') ?>" class="list-group-item list-group-item-action"><i class="bi bi-grid me-2"></i>Todos los Productos</a></li>
            <li><a href="<?= url('pages/ofertas.php') ?>" class="list-group-item list-group-item-action"><i class="bi bi-tag me-2"></i>Ofertas</a></li>
            <li><a href="<?= url('pages/marcas.php') ?>" class="list-group-item list-group-item-action"><i class="bi bi-building me-2"></i>Marcas</a></li>
            <li><a href="<?= url('pages/contacto.php') ?>" class="list-group-item list-group-item-action">Contacto</a></li>
            <li class="list-group-item fw-bold text-muted small">Categorías</li>
            <?php foreach ($categorias_menu as $cat): ?>
            <li>
                <a href="<?= url('pages/productos.php?categoria=' . $cat['slug']) ?>" class="list-group-item list-group-item-action ps-4">
                    <i class="bi bi-<?= e($cat['icono'] ?? 'tag') ?> me-2"></i><?= e($cat['nombre']) ?>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>

        <hr>
        <?php if (is_logged_in()): ?>
            <div class="d-grid gap-2">
                <a href="<?= url('pages/cuenta.php') ?>" class="btn btn-outline-primary btn-sm">Mi Cuenta</a>
                <a href="<?= url('pages/logout.php') ?>" class="btn btn-outline-danger btn-sm">Cerrar Sesión</a>
            </div>
        <?php else: ?>
            <div class="d-grid gap-2">
                <a href="<?= url('pages/login.php') ?>" class="btn btn-primary btn-sm">Iniciar Sesión</a>
                <a href="<?= url('pages/registro.php') ?>" class="btn btn-outline-primary btn-sm">Registrarse</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- ============================================
     CONTENEDOR PRINCIPAL
     ============================================ -->
<main class="main-content">

<!-- ============================================
     MODAL QUICK VIEW (Vista Rápida - Mejora 7)
     ============================================ -->
<div class="modal fade" id="quickViewModal" tabindex="-1" aria-labelledby="quickViewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content rounded-4 shadow-lg border-0">
      <div class="modal-header border-0 pb-0">
        <h5 class="modal-title fw-bold" id="quickViewModalLabel">Vista Rápida</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body p-4" id="quick-view-body">
        <div class="text-center py-5">
          <div class="spinner-border text-primary" role="status"></div>
          <p class="mt-2 text-muted small">Cargando producto...</p>
        </div>
      </div>
    </div>
  </div>
</div>
