<!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') ?> - Panel Administrador</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= base_url('css/style.css') ?>">
    <style>
        .autocomplete-list {
            position: absolute;
            background: var(--admin-surface);
            border: 1px solid var(--admin-border);
            border-top: none;
            border-radius: 0 0 12px 12px;
            max-height: 280px;
            overflow-y: auto;
            width: calc(100% - 2px);
            left: 1px;
            top: 48px;
            z-index: 1000;
            display: none;
        }

        .autocomplete-list.active {
            display: block;
        }

        .autocomplete-item {
            padding: 10px 14px;
            cursor: pointer;
            border-bottom: 1px solid var(--admin-border);
            transition: background 0.15s ease;
        }

        .autocomplete-item:hover,
        .autocomplete-item.selected {
            background: var(--admin-accent-soft);
        }

        .autocomplete-item:last-child {
            border-bottom: none;
        }

        .search-box-wrapper {
            position: relative;
        }
        .menu-item {
            padding: 14px 20px;
            display: flex;
            align-items: center;
            gap: 14px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 0.95rem;
            font-weight: 600;
            border-radius: 16px;
            transition: all 0.2s ease;
            margin-bottom: 8px;
        }
        .menu-item.active { background: var(--accent); color: #0d0d0d; box-shadow: 0 12px 24px -12px rgba(212,245,66,0.45); }
        .menu-section { padding: 24px 20px 10px; font-size: 0.75rem; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: 1.4px; }
        @media (max-width: 1024px) {
            .sidebar { width: 90px; }
            .sidebar h1, .sidebar-menu span, .menu-section { display: none; }
            .main-content { margin-left: 90px; }
            .menu-item { justify-content: center; padding: 18px; }
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <aside class="admin-sidebar">
            <div class="admin-brand">Cine<span>Plex</span></div>
            <div class="admin-user">
                <div class="admin-avatar">A</div>
                <div>
                    <strong><?= esc(session()->get('user_nombres') ?? 'Admin') ?></strong>
                    <p>Administrador</p>
                </div>
            </div>

            <nav class="admin-nav">
                <a href="<?= base_url('/') ?>" class="menu-item home-link">
                🏠 <span>Ver Cartelera</span></a>
                
                <div class="menu-section">Gestión</div>
                <a href="<?= base_url('admin/peliculas') ?>" class="menu-item <?= url_is('admin/peliculas*') ? 'active' : '' ?>">🎬 Películas</a>
                <a href="<?= base_url('admin/funciones') ?>" class="menu-item <?= url_is('admin/funciones*') ? 'active' : '' ?>">⏰ Funciones</a>
                <a href="<?= base_url('admin/usuarios') ?>" class="menu-item <?= url_is('admin/usuarios*') ? 'active' : '' ?>">👤 Usuarios</a>
                <a href="<?= base_url('admin/membresias') ?>" class="menu-item <?= url_is('admin/membresias*') ? 'active' : '' ?>">💳 Membresías</a>
                <a href="<?= base_url('admin/generos') ?>" class="menu-item <?= url_is('admin/generos*') ? 'active' : '' ?>">🎨 Géneros</a>
                <a href="<?= base_url('admin/locales') ?>" class="menu-item <?= url_is('admin/locales*') ? 'active' : '' ?>">🏢 Locales</a>
                <a href="<?= base_url('admin/salas') ?>" class="menu-item <?= url_is('admin/salas*') ? 'active' : '' ?>">🎞️ Salas</a>
                <a href="<?= base_url('admin/productos') ?>" class="menu-item <?= url_is('admin/productos*') ? 'active' : '' ?>">📦 Productos</a>
                <a href="<?= base_url('admin/promociones') ?>" class="menu-item <?= url_is('admin/promociones*') ? 'active' : '' ?>">🎁 Promociones</a>
                <a href="<?= base_url('admin/pagos') ?>" class="menu-item <?= url_is('admin/pagos*') ? 'active' : '' ?>">🎟️ Pagos</a>

            </nav>
            <a href="<?= base_url('logout') ?>" class="admin-logout">Cerrar sesión</a>
        </aside>

        <main class="admin-content">
            <?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 class="admin-footer">
                <p>&copy; <?= date('Y') ?> CinePlex - Panel Administrativo</p>
            </footer>
        </main>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchInputs = document.querySelectorAll('.search-box input[name="q"]');
            
            searchInputs.forEach(input => {
                const wrapper = input.closest('.search-box');
                if (!wrapper) return;

                const panelSection = wrapper.closest('section');
                const table = panelSection ? panelSection.querySelector('table') : null;

                if (table) {
                    const rows = Array.from(table.querySelectorAll('tbody tr'));
                    const applyLiveFilter = () => {
                        const query = input.value.trim().toLowerCase();
                        rows.forEach(row => {
                            const text = row.textContent.toLowerCase();
                            row.style.display = text.includes(query) ? '' : 'none';
                        });
                    };

                    input.addEventListener('input', debounce(applyLiveFilter, 180));
                    applyLiveFilter();
                }

                // Detectar módulo actual
                const currentModule = window.location.pathname.split('/')[2] || 'usuarios';
                const autocompleteEndpoint = `<?= base_url('admin') ?>/${currentModule}/autocomplete`;

                let autocompleteList = null;
                let selectedIndex = -1;

                // Crear contenedor de autocompletado si es usuarios
                if (currentModule === 'usuarios') {
                    const searchBoxWrapper = document.createElement('div');
                    searchBoxWrapper.className = 'search-box-wrapper';
                    input.parentNode.insertBefore(searchBoxWrapper, input);
                    searchBoxWrapper.appendChild(input);

                    autocompleteList = document.createElement('div');
                    autocompleteList.className = 'autocomplete-list';
                    searchBoxWrapper.appendChild(autocompleteList);

                    input.addEventListener('input', debounce(async (e) => {
                        const query = e.target.value.trim();
                        
                        if (query.length < 1) {
                            autocompleteList.classList.remove('active');
                            return;
                        }

                        try {
                            const response = await fetch(`${autocompleteEndpoint}?q=${encodeURIComponent(query)}`);
                            const results = await response.json();

                            autocompleteList.innerHTML = '';
                            selectedIndex = -1;

                            if (results.length > 0) {
                                results.forEach((item, index) => {
                                    const div = document.createElement('div');
                                    div.className = 'autocomplete-item';
                                    div.textContent = item.text;
                                    div.dataset.value = item.value;
                                    div.dataset.id = item.id;

                                    div.addEventListener('click', () => {
                                        input.value = item.value;
                                        autocompleteList.classList.remove('active');
                                    });

                                    autocompleteList.appendChild(div);
                                });
                                autocompleteList.classList.add('active');
                            } else {
                                autocompleteList.classList.remove('active');
                            }
                        } catch (error) {
                            console.error('Error en autocompletado:', error);
                        }
                    }, 300));

                    input.addEventListener('keydown', (e) => {
                        const items = autocompleteList.querySelectorAll('.autocomplete-item');
                        
                        if (e.key === 'ArrowDown') {
                            e.preventDefault();
                            selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
                            updateSelection(items);
                        } else if (e.key === 'ArrowUp') {
                            e.preventDefault();
                            selectedIndex = Math.max(selectedIndex - 1, -1);
                            updateSelection(items);
                        } else if (e.key === 'Enter' && selectedIndex >= 0) {
                            e.preventDefault();
                            items[selectedIndex].click();
                        }
                    });

                    function updateSelection(items) {
                        items.forEach((item, index) => {
                            if (index === selectedIndex) {
                                item.classList.add('selected');
                                item.scrollIntoView({ block: 'nearest' });
                            } else {
                                item.classList.remove('selected');
                            }
                        });
                    }

                    input.addEventListener('focus', () => {
                        if (input.value.trim().length > 0 && autocompleteList.children.length > 0) {
                            autocompleteList.classList.add('active');
                        }
                    });

                    document.addEventListener('click', (e) => {
                        if (!searchBoxWrapper.contains(e.target)) {
                            autocompleteList.classList.remove('active');
                        }
                    });
                }
            });

            function debounce(func, delay) {
                let timeoutId;
                return function(...args) {
                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(() => func.apply(this, args), delay);
                };
            }
        });
    </script>
</body>
</html>
