<?php /* filepath: resources\views\AutoGestionCliente\productos.blade.php */ ?>


<?php $__env->startSection('content'); ?>

<?php /* 1. Se incluye la librería de SweetAlert2 */ ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<?php /* 2. Disparadores de SweetAlert2 para mensajes de sesión (éxito/error tras recarga) */ ?>
<?php if(session('alert-success')): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                title: '¡Éxito!',
                html: "<?php echo session('alert-success'); ?>",
                icon: 'success',
                confirmButtonText: 'Aceptar'
            });
        });
    </script>
<?php endif; ?>

<?php if(session('alert-danger')): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                title: '¡Error!',
                html: "<?php echo session('alert-danger'); ?>",
                icon: 'error',
                confirmButtonText: 'Aceptar'
            });
        });
    </script>
<?php endif; ?>

<style>
    .sticky-top-custom {
        position: -webkit-sticky; /* Para compatibilidad con Safari */
        position: sticky;
        top: 20px; /* Ajusta este valor según el espacio que quieras dejar en la parte superior */
        z-index: 1020; /*Bootstrap usa 1030 para navbars fijas, 1020 es seguro*/
    }

    /* --- INICIO: CÓDIGO PARA RESPONSIVE --- */

    /* Se aplica a pantallas con un ancho máximo de 989px */
    @media (max-width: 991px) {
        
        /* Hacemos que la fila principal se comporte como una columna flexible */
        .container-fluid > .row {
            display: flex;
            flex-direction: column;
        }

        /* Le decimos al carrito (col-md-5) que vaya primero */
        .container-fluid > .row > .col-md-5 {
            order: 1;
        }
        
        /* Le decimos a los productos (col-md-7) que vayan segundos */
        .container-fluid > .row > .col-md-7 {
            order: 2;
        }

        /* En la vista móvil, desactivamos el 'sticky-top' y añadimos un margen inferior
           para separarlo de la lista de productos que vendrá después. */
        .sticky-top-custom {
            position: static !important; /* !important es para sobreescribir la clase de Bootstrap */
            margin-bottom: 1.5rem; /* Un poco de espacio antes de la lista de productos */
        }
    }
    /* --- FIN: CÓDIGO PARA RESPONSIVE --- */
</style>


<div class="container-fluid mt-4">
    <div class="row">
        <?php /* Columna izquierda: Productos/Combos */ ?>
        <div class="col-md-7">
            <div class="card shadow-sm">
                <div class="card-header text-white text-center">
                    <h4 class="mb-0">Seleccione sus Productos o Combos</h4>
                </div>

                <div class="btn-group mb-3 d-flex" style="margin-top: 2%;" role="group">
                    <button class="btn btn-info flex-fill" onclick="cargarItems('producto')" style="margin-bottom: 5%;margin-right: 12px;">Ver Productos</button>
                    <button class="btn btn-warning flex-fill" onclick="cargarItems('combo')">Ver Combos</button>
                    <form class="navbar-form navbar-left" style="margin-top: 0%;" role="search" id="search-form" onsubmit="return false;">
                        <div class="form-group">
                            <input type="text" class="form-control" id="search-input" placeholder="Search" style="background-color: azure;">
                        </div>
                        <button type="submit" id="btn-search-submit" class="btn btn-default">Buscar</button>
                        <button type="button" id="btn-search-clear" class="btn btn-secondary" title="Limpiar búsqueda">Limpiar búsqueda</button>
                    </form> 
                </div>
                <div class="card-body">
                    <?php /* Filtros de categorías, solo para productos */ ?>
                    <div id="filtros-categorias" class="mb-4" style="display:none;">
                        <div class="categoria-wrapper">

                            <button class="categoria-arrow left" aria-label="Desplazar izquierda" type="button">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="15 18 9 12 15 6"></polyline>
                                </svg>
                            </button>

                            <div class="categoria-scroll" tabindex="0" role="list">
                                <?php foreach($categorias as $cat): ?>
                                    <button class="btn btn-categoria" data-categoria="<?php echo e($cat->idCategoria); ?>" role="listitem">
                                        <i class="fas fa-tag me-1"></i> <?php echo e($cat->nombre_categoria); ?>

                                    </button>
                                <?php endforeach; ?>
                                <button class="btn btn-categoria" data-categoria="todos" role="listitem">
                                    <i class="fas fa-th-large me-1"></i> Todos
                                </button>
                            </div>

                            <button class="categoria-arrow right" aria-label="Desplazar derecha" type="button">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="9 18 15 12 9 6"></polyline>
                                </svg>
                            </button>
                        </div>
                    </div>

                    <style>
                        .categoria-arrow svg {
                        display: block;
                    }
                    /* Wrapper horizontal con flechas visibles cuando haga overflow */
        
                    .categoria-wrapper {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        width: 96%;
                    }

                    /* Flechas */
                    .categoria-arrow {
                        flex: 0 0 auto;
                        align-items: center;
                        justify-content: center;
                        border: none;
                        background: linear-gradient(135deg, #007BFF, #0056b3);
                        padding: 10px 12px;
                        border-radius: 50%;
                        box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3);
                        cursor: pointer;
                        color: white;
                        transition: transform 0.2s ease, box-shadow 0.2s ease;
                    }
                    .categoria-arrow:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 8px 20px rgba(0, 123, 255, 0.5);
                    }


                    .categoria-arrow svg {
                        stroke: white;
                    }
                    /* Contenedor scroll */
                    .categoria-scroll {
                        display: flex;
                        gap: 10px;
                        overflow-x: auto;
                        flex: 1 1 auto;
                        padding: 6px 4px;
                        scroll-behavior: smooth;
                        -webkit-overflow-scrolling: touch; /* mejora en iOS */
                    }

                    /* ocultar scrollbar visual en Chrome/Safari (dejamos pequeño scrollbar para accesibilidad si se desea) */
                    .categoria-scroll::-webkit-scrollbar { height: 6px; }
                    .categoria-scroll::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.12); border-radius: 3px; }

                    /* Botones 'pill' */
                    

                    .btn-categoria {
                        flex: 0 0 auto;
                        border-radius: 50px;
                        background: linear-gradient(135deg, #f8f9fa, #cde3fc);
                        border: none;
                        color: #495057;
                        font-weight: bold;
                        padding: 10px 18px;
                        transition: all 0.2s ease-in-out;
                    }
                    .btn-categoria:hover {
                        background: linear-gradient(135deg, #007BFF, #0056b3);
                        color: white;
                        box-shadow: 0 8px 20px rgba(0, 123, 255, 0.4);
                    }
                    .btn-categoria.active {
                        background: linear-gradient(135deg, #0056b3, #003f88);
                        color: white;
                        box-shadow: 0 8px 20px rgba(0, 86, 179, 0.5);
                    }

                    /* Pequeño ajuste para que en pantallas muy pequeñas las flechas no ocupen demasiado */
                    @media (max-width: 480px) {
                        .categoria-arrow { padding: 6px; font-size: 0.95rem; }
                    }
                    </style>

                    <script>
                    document.addEventListener('DOMContentLoaded', function () {
                        const scrollContainer = document.querySelector('.categoria-scroll');
                        const btnLeft = document.querySelector('.categoria-arrow.left');
                        const btnRight = document.querySelector('.categoria-arrow.right');
                        const filtrosPadre = document.getElementById('filtros-categorias');

                        if (!scrollContainer || !btnLeft || !btnRight) return;

                        function updateArrows() {
                            // ¿Hay overflow horizontal?
                            const hasOverflow = scrollContainer.scrollWidth > scrollContainer.clientWidth + 1;
                            if (!hasOverflow) {
                                btnLeft.style.display = 'none';
                                btnRight.style.display = 'none';
                                return;
                            }
                            btnLeft.style.display = (scrollContainer.scrollLeft > 0) ? 'inline-flex' : 'none';
                            btnRight.style.display = (scrollContainer.scrollLeft < scrollContainer.scrollWidth - scrollContainer.clientWidth - 1) ? 'inline-flex' : 'none';
                        }

                        // Scroll por porciones grandes (60% del ancho visible)
                        function scrollLeft() { scrollContainer.scrollBy({ left: -Math.round(scrollContainer.clientWidth * 0.6), behavior: 'smooth' }); }
                        function scrollRight() { scrollContainer.scrollBy({ left: Math.round(scrollContainer.clientWidth * 0.6), behavior: 'smooth' }); }

                        btnLeft.addEventListener('click', scrollLeft);
                        btnRight.addEventListener('click', scrollRight);
                        scrollContainer.addEventListener('scroll', updateArrows);
                        window.addEventListener('resize', updateArrows);

                        // Soporte teclado cuando el contenedor está enfocado
                        scrollContainer.addEventListener('keydown', (e) => {
                            if (e.key === 'ArrowRight') { e.preventDefault(); scrollRight(); }
                            if (e.key === 'ArrowLeft')  { e.preventDefault(); scrollLeft(); }
                        });

                        // Observador para detectar cambios en visibilidad / contenido (por ejemplo cuando se hace display: '' desde tu JS)
                        const mo = new MutationObserver(() => updateArrows());
                        mo.observe(scrollContainer, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
                        if (filtrosPadre) mo.observe(filtrosPadre, { attributes: true, attributeFilter: ['style', 'class'] });

                        // Llamadas iniciales (recalcula un poco después por si el contenedor se muestra después)
                        setTimeout(updateArrows, 50);
                        setTimeout(updateArrows, 350);
                    });
                    </script>


                    <div id="contenedor-items" style="margin-right: 2%;">
                        <?php /* Contenido dinámico (productos/combos) se carga aquí */ ?>
                    </div>
                    
                    <!-- Contenedor para los enlaces de paginación -->
                    <div id="pagination-container" class="d-flex justify-content-center mt-4" style="display: block;text-align: center;">
                        <?php /* Los enlaces de paginación se cargarán aquí vía AJAX */ ?>
                    </div>
                </div>
            </div>
        </div>

        <?php /* Columna derecha: Carrito */ ?>
        <div class="col-md-5 sticky-top-custom">
            <div class="card shadow-sm">
                <div class="card-header text-white text-center">
                    <h4 class="mb-0">
                        <i class="fas fa-shopping-cart mr-2"></i>Mi Pedido
                        <span id="nombre-cliente-display" class="badge badge-light float-right mt-1"></span>
                    </h4>
                </div>
                <div class="card-body">
                    <?php if(!session('cliente_autogestion')): ?>
                        <div id="seccion-cliente-form">
                            <p class="text-center text-muted">Ingrese su nombre para comenzar</p>
                            <input type="text" id="nombre_cliente_manual" class="form-control form-control-lg text-center mb-2" placeholder="Nombre completo">
                            <button id="btn-guardar-cliente" class="btn btn-primary btn-block" disabled>
                                <i class="fas fa-save mr-2"></i>Iniciar Pedido
                            </button>
                        </div>
                    <?php endif; ?>

                    <?php /* <?php if(session('cliente_autogestion')): ?>
                    <div class="mb-3 text-center">
                         <button id="btn-cancelar-pedido" class="btn btn-sm btn-outline-danger">
                            <i class="fas fa-sync-alt mr-1"></i> Cancelar y Empezar de Nuevo
                        </button>
                    </div>
                    <?php endif; ?> */ ?>

                    <hr id="carrito-hr" <?php if(!session('cliente_autogestion')): ?> class="d-none" <?php endif; ?>>

                    <div id="carrito-contenedor">
                        <?php /* El carrito se carga vía AJAX aquí. Si no hay sesión, se muestra vacío. */ ?>
                    </div>
                </div>
                <div class="card-footer">
                    <button id="btn-confirmar-pedido" class="btn btn-primary btn-block" disabled>
                        <i class="fas fa-check-circle mr-1"></i> Confirmar Pedido
                    </button>
                    <button id="btn-cancelar-pedido" class="btn btn-danger btn-block" style="margin-top: 10px;" <?php if(!session('cliente_autogestion')): ?> disabled title="Inicie pedido primero" <?php endif; ?>>
                        <i class="fas fa-sync-alt mr-1"></i> Cancelar y Empezar de Nuevo
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', function () {
    let clienteHaGuardadoNombre = <?php echo e(session('cliente_autogestion') ? 'true' : 'false'); ?>;
    let currentView = 'producto';

    // --- SECCIÓN: TEMPORIZADOR DE INACTIVIDAD ---
    let inactivityTimer;
    const INACTIVITY_TIMEOUT = 30000; // 1 minutos (100000 ms)

    function resetInactivityTimer() {
        if (!clienteHaGuardadoNombre) return;
        clearTimeout(inactivityTimer);
        inactivityTimer = setTimeout(logoutPorInactividad, INACTIVITY_TIMEOUT);
    }

    function logoutPorInactividad() {
        let forceLogoutTimer;
        const GRACE_PERIOD_TIMEOUT = 20000;
        forceLogoutTimer = setTimeout(() => {
            Swal.close();
            limpiarSesionYRedirigir();
        }, GRACE_PERIOD_TIMEOUT);

        Swal.fire({
            title: '¿Sigues ahí?',
            html: `Detectamos inactividad. La sesión se cerrará automáticamente en <b></b> segundos. <br/><br/> Haz clic en 'Seguir aquí' para cancelar el cierre.`,
            icon: 'warning',
            confirmButtonText: 'Seguir aquí', 
            allowOutsideClick: false,
            timer: GRACE_PERIOD_TIMEOUT,
            timerProgressBar: true,
            didOpen: () => {
                const b = Swal.getHtmlContainer().querySelector('b');
                timerInterval = setInterval(() => {
                    b.textContent = Math.ceil(Swal.getTimerLeft() / 1000)
                }, 100)
            },
            willClose: () => {
                clearInterval(timerInterval)
            }
        }).then((result) => {
            if (result.isConfirmed) {
                clearTimeout(forceLogoutTimer);
                resetInactivityTimer();
                Toast.fire({ icon: 'success', title: '¡Sesión extendida!' });
            }
        });
    }
    window.onload = resetInactivityTimer;
    document.onmousemove = resetInactivityTimer;
    document.onclick = resetInactivityTimer;
    document.onkeypress = resetInactivityTimer;
    document.addEventListener('touchstart', resetInactivityTimer, false);

    // --- Toast de SweetAlert2 ---
    const Toast = Swal.mixin({
      toast: true,
      position: 'top-end',
      showConfirmButton: false,
      timer: 3000,
      timerProgressBar: true,
      didOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer);
        toast.addEventListener('mouseleave', Swal.resumeTimer);
      }
    });

    // --- INICIAR PEDIDO ---
    const nombreInput = document.getElementById('nombre_cliente_manual');
    const btnGuardar = document.getElementById('btn-guardar-cliente');
    if (btnGuardar) {
        nombreInput.addEventListener('input', () => {
            btnGuardar.disabled = nombreInput.value.trim().length < 3;
        });

        btnGuardar.addEventListener('click', () => {
            Swal.fire({
                title: '¿Iniciar pedido?',
                text: `Se iniciará un pedido a nombre de "${nombreInput.value.trim()}".`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Sí, iniciar',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('<?php echo e(route("autogestion.iniciar")); ?>', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'},
                        body: JSON.stringify({nombre_cliente_manual: nombreInput.value.trim()})
                    })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            window.location.reload();
                        } else {
                            Swal.fire('Error', data.message, 'error');
                        }
                    });
                }
            });
        });
    }

    // --- CARGA DE ITEMS Y PAGINACIÓN ---
    function fetchAndRenderItems(url) {
        fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(r => r.json())
            .then(data => {
                document.getElementById('contenedor-items').innerHTML = data.html;
                document.getElementById('pagination-container').innerHTML = data.pagination;
            })
            .catch(error => {
                console.error("Error al cargar items:", error);
                document.getElementById('contenedor-items').innerHTML = "<div class='alert alert-danger'>Error al cargar. Intente de nuevo.</div>";
            });
    }

    window.cargarItems = function(tipo, categoria = 'todos') {
        currentView = tipo; // Actualizamos la vista actual
        
        // ¡IMPORTANTE! Leemos el valor del campo de búsqueda CADA VEZ que cargamos ítems.
        const terminoBusqueda = document.getElementById('search-input').value;

        if(tipo === 'producto') {
            document.getElementById('filtros-categorias').style.display = '';
        } else {
            document.getElementById('filtros-categorias').style.display = 'none';
        }
        
        // Construimos la URL con el nuevo parámetro de búsqueda. `encodeURIComponent` es por seguridad.
        const url = `/autogestion/cargar/${tipo}?categoria=${categoria}&search=${encodeURIComponent(terminoBusqueda)}`;
        fetchAndRenderItems(url);
    };

    document.getElementById('pagination-container').addEventListener('click', function(e) {
        const link = e.target.closest('.pagination a');
        if (link) {
            e.preventDefault();
            const url = link.href;
            if (url) {
                fetchAndRenderItems(url);
            }
        }
    });

document.getElementById('search-form').addEventListener('submit', function(e) {
        e.preventDefault();
        cargarItems(currentView, 'todos');

        if (currentView === 'productos') {
            document.querySelectorAll('.btn-categoria').forEach(b => b.classList.remove('active'));
            const btnTodos = document.querySelector('.btn-categoria[data-categoria="todos"]');
            if (btnTodos) {
                btnTodos.classList.add('active');
            }
        }
    });

    // 2. Evento para el botón de "Limpiar"
    document.getElementById('btn-search-clear').addEventListener('click', function() {
        document.getElementById('search-input').value = ''; // Vaciamos el campo de texto
        const categoriaActiva = document.querySelector('.btn-categoria.active')?.dataset.categoria || 'todos';
        // Volvemos a llamar a cargarItems. Como el input está vacío, mostrará todos los ítems.
        cargarItems(currentView, categoriaActiva);
    });


    // --- MANEJO DEL CARRITO ---
    window.refrescarCarrito = function() {
        fetch('<?php echo e(route("autogestion.verPedido")); ?>')
            .then(r => r.json())
            .then(data => {
                document.getElementById('carrito-contenedor').innerHTML = data.html_carrito;
                document.getElementById('btn-confirmar-pedido').disabled = !(data.item_count > 0 && clienteHaGuardadoNombre);
            });
    };

    // --- EVENTOS DE LOS BOTONES ---

    // 1. Agregar item (Delegación de evento en contenedor de items)
    document.getElementById('contenedor-items').addEventListener('click', function(e) {
        const btn = e.target.closest('.btn-agregar-item');
        if (!btn) return;

        fetch('<?php echo e(route("autogestion.agregarItem")); ?>', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'},
            body: JSON.stringify({tipo: btn.dataset.tipo, id: btn.dataset.id})
        })
        .then(r => r.json()).then(data => {
            if (data.success) {
                document.getElementById('carrito-contenedor').innerHTML = data.html_carrito;
                document.getElementById('btn-confirmar-pedido').disabled = !(data.item_count > 0 && clienteHaGuardadoNombre);
                Toast.fire({ icon: 'success', title: data.message });
            } else {
                 Swal.fire('Error', data.message || 'Ocurrió un error', 'error');
            }
        });
    });

    // 2. Delegación de eventos para el carrito (actualizar/eliminar)
    document.getElementById('carrito-contenedor').addEventListener('click', function(e) {
        const target = e.target;
        const fila = target.closest('tr');
        if (!fila) return;

        const cartItemId = fila.dataset.cartItemId;
        if (!cartItemId) return;

        const cantidadInput = fila.querySelector('.cantidad-input-def');
        let cantidad = parseInt(cantidadInput.value);

        if (target.classList.contains('btn-plus-def')) {
            cantidadInput.value = ++cantidad;
            actualizarCantidad(cartItemId, cantidad);
        } else if (target.classList.contains('btn-minus-def')) {
             if (cantidad > 1) {
                cantidadInput.value = --cantidad;
                actualizarCantidad(cartItemId, cantidad);
             } else {
                Swal.fire({
                    title: '¿Eliminar ítem?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6', confirmButtonText: 'Sí, eliminar', cancelButtonText: 'Cancelar'
                }).then((result) => { if (result.isConfirmed) eliminarItem(cartItemId); });
             }
        } else if (target.classList.contains('btn-eliminar')) {
            Swal.fire({
                title: '¿Eliminar ítem?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6', confirmButtonText: 'Sí, eliminar', cancelButtonText: 'Cancelar'
            }).then((result) => { if (result.isConfirmed) eliminarItem(cartItemId); });
        }
    });

    // 3. Evento para confirmar pedido
    document.getElementById('btn-confirmar-pedido').addEventListener('click', function(e) {
        e.preventDefault();
        const self = this;
        Swal.fire({
            title: '¿Confirmar el pedido?', text: "Se enviará a preparación.", icon: 'info',
            showCancelButton: true, confirmButtonColor: '#28a745', cancelButtonColor: '#d33',
            confirmButtonText: 'Sí, confirmar', cancelButtonText: 'Volver'
        }).then((result) => {
            if (result.isConfirmed) {
                self.disabled = true;
                self.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Procesando...';
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '<?php echo e(route("autogestion.confirmarPedido")); ?>';
                const csrfTokenInput = document.createElement('input');
                csrfTokenInput.type = 'hidden';
                csrfTokenInput.name = '_token';
                csrfTokenInput.value = '<?php echo e(csrf_token()); ?>';
                form.appendChild(csrfTokenInput);
                document.body.appendChild(form);
                form.submit();
            }
        });
    });
    
    // 4. Evento para el botón de cancelar y empezar de nuevo
    const btnCancelarPedido = document.getElementById('btn-cancelar-pedido');
    if(btnCancelarPedido) {
        btnCancelarPedido.addEventListener('click', function() {
            Swal.fire({
                title: '¿Estás seguro?',
                text: "Se eliminará el pedido actual y tendrás que empezar de nuevo.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Sí, empezar de nuevo',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.isConfirmed) {
                    limpiarSesionYRedirigir();
                }
            });
        });
    }

    // --- FUNCIONES AJAX AUXILIARES ---
    function actualizarCantidad(cartItemId, cantidad) {
         fetch('<?php echo e(route("autogestion.actualizarCantidad")); ?>', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'},
            body: JSON.stringify({cart_item_id: cartItemId, cantidad: cantidad})
        })
        .then(r => r.json()).then(data => { if(data.success) refrescarCarrito(); });
    }

    function eliminarItem(cartItemId) {
        fetch('<?php echo e(route("autogestion.eliminarItem")); ?>', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'},
            body: JSON.stringify({cart_item_id: cartItemId})
        })
        .then(r => r.json()).then(data => { if(data.success) refrescarCarrito(); });
    }

    function limpiarSesionYRedirigir() {
        fetch('<?php echo e(route("autogestion.limpiarSesion")); ?>', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'}
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                // ***** ¡ESTE ES EL CAMBIO PRINCIPAL! *****
                // Se redirige a la ruta de la página de inicio en lugar de la de productos.
                window.location.href = '<?php echo e(route("autogestion.InicioAutoGestion")); ?>';
            } else {
                Swal.fire('Error', 'No se pudo reiniciar la sesión. Se redirigirá a la página de inicio.', 'error')
                     .then(() => {
                         window.location.href = '<?php echo e(route("autogestion.InicioAutoGestion")); ?>';
                     });
            }
        }).catch(() => {
            Swal.fire('Error de Conexión', 'No se pudo comunicar con el servidor. Se redirigirá a la página de inicio.', 'error')
                 .then(() => {
                     window.location.href = '<?php echo e(route("autogestion.InicioAutoGestion")); ?>';
                 });
        });
    }

    // --- Filtros de categorías ---
    document.getElementById('filtros-categorias').addEventListener('click', function(e) {
        const btn = e.target.closest('.btn-categoria');
        if(btn) {
            // Damos feedback visual al usuario sobre qué filtro está activo
            document.querySelectorAll('.btn-categoria').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');

            let categoria = btn.getAttribute('data-categoria');
            // La función cargarItems ahora sabe cómo obtener el término de búsqueda por sí misma.
            cargarItems('producto', categoria);
        }
    });

    
document.getElementById('search-input').value = '';
    // --- Carga inicial ---
    cargarItems('producto', 'todos');
    if (clienteHaGuardadoNombre) {
        refrescarCarrito();
        document.getElementById('nombre-cliente-display').textContent = "<?php echo e(session('cliente_nombre', '')); ?>";
        resetInactivityTimer();
    }
});
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>