<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $this->renderSection('title') ?> - CinePlex</title>
    <link rel="stylesheet" href="<?= base_url('css/style.css') ?>">
</head>
<body>
    <header class="site-header">
        <div class="topbar">
            <a href="<?= base_url('/') ?>" class="brand">Cine<span>Plex</span></a>
            <nav class="main-nav">
                <a href="<?= base_url('cines') ?>">Cartelera</a>
                <a href="<?= base_url('alimentos') ?>">Alimentos y Bebidas</a>
                <a href="<?= base_url('promociones') ?>">Promociones</a>
                <a href="<?= base_url('membresia') ?>">Membresía</a>
                <button type="button" class="nav-pick-cine" id="btn-elegir-cine">
                    📍 Elegir Cine <span class="chev">▾</span>
                </button>
                <?php if (session()->get('isLoggedIn')): ?>
                    <span class="user-pill">Hola, <strong><?= esc(session()->get('user_nombres')) ?></strong></span>
                    <a href="<?= base_url('mis-compras') ?>" style="display:inline-flex;align-items:center;gap:5px;">🎟️ Mis Compras</a>
                    <?php if ((int)session()->get('user_id_rol') === 1): ?>
                        <a href="<?= base_url('admin/peliculas') ?>">Panel Admin</a>
                    <?php endif; ?>
                    <a href="<?= base_url('logout') ?>" class="login-link">Salir</a>
                <?php else: ?>
                    <a href="<?= base_url('login') ?>" class="login-link">Inicio de sesión</a>
                <?php endif; ?>
            </nav>
        </div>
    </header>

    <!-- Sidebar: Elegir Cine -->
    <div class="cp-overlay" id="cine-overlay"></div>
    <aside class="cp-drawer cp-drawer-left" id="cine-drawer" aria-hidden="true">
        <div class="cp-drawer-header">
            <h3>Elige tu cine<span class="cp-drawer-sub">Selecciona un local para ver su cartelera</span></h3>
            <button type="button" class="cp-drawer-close" id="cine-drawer-close">✕</button>
        </div>
        <div class="cp-drawer-body">
            <input type="text" class="cine-search" id="cine-search" placeholder="Buscar por cine o distrito...">
            <div id="cine-drawer-list">
                <p class="cine-empty-msg">Cargando cines...</p>
            </div>
        </div>
    </aside>

    <main class="page-shell">
        <?php if (session()->getFlashdata('error')): ?>
            <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
        <?php endif; ?>

        <?php if (session()->getFlashdata('success')): ?>
            <div class="alert alert-success"><?= session()->getFlashdata('success') ?></div>
        <?php endif; ?>

        <?= $this->renderSection('content') ?>

        <footer>
            <p>&copy; <?= date('Y') ?> CinePlex - Experiencia de cine moderna y divertida.</p>
        </footer>
    </main>

    <script>
    (function () {
        var overlay = document.getElementById('cine-overlay');
        var drawer = document.getElementById('cine-drawer');
        var openBtn = document.getElementById('btn-elegir-cine');
        var closeBtn = document.getElementById('cine-drawer-close');
        var listEl = document.getElementById('cine-drawer-list');
        var searchEl = document.getElementById('cine-search');
        var localesCache = null;

        function openDrawer() {
            overlay.classList.add('is-open');
            drawer.classList.add('is-open');
            drawer.setAttribute('aria-hidden', 'false');
            document.body.style.overflow = 'hidden';
            if (!localesCache) {
                cargarLocales();
            }
        }

        function closeDrawer() {
            overlay.classList.remove('is-open');
            drawer.classList.remove('is-open');
            drawer.setAttribute('aria-hidden', 'true');
            document.body.style.overflow = '';
        }

        function renderLocales(locales) {
            if (!locales.length) {
                listEl.innerHTML = '<p class="cine-empty-msg">No hay cines disponibles por el momento.</p>';
                return;
            }
            var grupos = {};
            locales.forEach(function (local) {
                var ciudad = local.ciudad || 'Otros';
                if (!grupos[ciudad]) grupos[ciudad] = [];
                grupos[ciudad].push(local);
            });
            var html = '';
            Object.keys(grupos).forEach(function (ciudad) {
                html += '<div class="cine-city-group"><p class="cine-city-title">' + ciudad + '</p>';
                grupos[ciudad].forEach(function (local) {
                    html += '<a class="cine-item" href="' + local.url + '" data-search="' +
                        (local.nombre + ' ' + local.distrito + ' ' + local.ciudad).toLowerCase() + '">' +
                        '<span><span class="cine-item-name">' + local.nombre + '</span>' +
                        '<span class="cine-item-addr">' + (local.direccion || '') + (local.distrito ? ' · ' + local.distrito : '') + '</span></span>' +
                        '<span class="cine-item-arrow">›</span></a>';
                });
                html += '</div>';
            });
            listEl.innerHTML = html;
        }

        function cargarLocales() {
            listEl.innerHTML = '<p class="cine-empty-msg">Cargando cines...</p>';
            fetch('<?= base_url('api/locales') ?>')
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    localesCache = data.locales || [];
                    renderLocales(localesCache);
                })
                .catch(function () {
                    listEl.innerHTML = '<p class="cine-empty-msg">No se pudo cargar la lista de cines.</p>';
                });
        }

        openBtn.addEventListener('click', openDrawer);
        closeBtn.addEventListener('click', closeDrawer);
        overlay.addEventListener('click', function (e) {
            if (e.target === overlay) closeDrawer();
        });
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') closeDrawer();
        });

        searchEl.addEventListener('input', function () {
            var q = searchEl.value.trim().toLowerCase();
            var items = listEl.querySelectorAll('.cine-item');
            items.forEach(function (item) {
                var match = !q || item.dataset.search.indexOf(q) !== -1;
                item.style.display = match ? '' : 'none';
            });
            listEl.querySelectorAll('.cine-city-group').forEach(function (group) {
                var visible = group.querySelectorAll('.cine-item:not([style*="display: none"])').length;
                group.style.display = visible ? '' : 'none';
            });
        });
    })();
    </script>
</body>
</html>
