<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ $negocio->nombre ?? config('app.name', 'Laravel') }}</title>

    <link rel="dns-prefetch" href="//fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">

    @vite(['resources/sass/app.scss', 'resources/js/app.js'])

    <style>
        :root {
            --sidebar-width: 260px;
        }
        body {
            background-color: #f4f6f9;
        }
        #wrapper {
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: var(--sidebar-width);
            flex-shrink: 0;
            background: #fff;
            border-right: 1px solid rgba(0,0,0,.08);
            box-shadow: 0 0 12px rgba(0,0,0,.03);
            position: sticky;
            top: 0;
            height: 100vh;
            z-index: 1030;
            transition: margin-left .25s ease;
        }
        .sidebar-brand {
            padding: 1rem;
            text-align: center;
            border-bottom: 1px solid rgba(0,0,0,.06);
        }
        .sidebar-brand img { max-height: 44px; max-width: 100%; }
        .sidebar-brand span { font-weight: 700; font-size: 1.05rem; }

        .sidebar-user {
            padding: .9rem 1rem;
            display: flex;
            align-items: center;
            gap: .6rem;
            border-bottom: 1px solid rgba(0,0,0,.06);
        }
        .sidebar-user .avatar {
            width: 40px; height: 40px; border-radius: 50%;
            background: linear-gradient(135deg, #4e73df, #6f42c1);
            color: #fff; display: flex; align-items: center; justify-content: center;
            font-weight: 700; font-size: 1rem; flex-shrink: 0;
        }
        .sidebar-user .name { font-weight: 600; font-size: .92rem; line-height: 1.1; }
        .sidebar-user .role { font-size: .74rem; color: #6c757d; }

        .sidebar-nav {
            padding: .6rem;
            overflow-y: auto;
            flex: 1 1 auto;
        }

        .sidebar-btn {
            display: flex;
            align-items: center;
            gap: .65rem;
            width: 100%;
            padding: .55rem .75rem;
            border: none;
            background: transparent;
            color: #3a3b45;
            border-radius: .5rem;
            font-size: .89rem;
            font-weight: 600;
            text-decoration: none;
            margin-bottom: .15rem;
            transition: background-color .12s ease, color .12s ease;
        }
        .sidebar-btn:hover { background: #eef1f8; color: #2f3040; }
        .sidebar-btn.active, .sidebar-btn.group-active {
            background: #4e73df;
            color: #fff;
        }
        .sidebar-btn .bi { font-size: 1.05rem; width: 1.2rem; text-align: center; }
        .sidebar-btn .chevron { margin-left: auto; transition: transform .2s ease; font-size: .8rem; }
        .sidebar-btn[aria-expanded="true"] .chevron { transform: rotate(180deg); }
        .sidebar-btn .badge-count {
            margin-left: auto;
            font-size: .68rem;
            font-weight: 700;
        }
        .sidebar-btn.group-active .badge-count { background: rgba(255,255,255,.25) !important; }
        .sidebar-btn .chevron + .badge-count,
        .sidebar-btn .badge-count + .chevron { margin-left: .4rem; }

        .sidebar-submenu {
            padding-left: .5rem;
            margin-bottom: .3rem;
        }
        .sidebar-sublink {
            display: flex;
            align-items: center;
            gap: .6rem;
            padding: .45rem .75rem .45rem 1.6rem;
            border-radius: .5rem;
            font-size: .84rem;
            font-weight: 500;
            color: #565968;
            text-decoration: none;
            border: none;
            background: transparent;
            width: 100%;
            text-align: left;
            margin-bottom: .1rem;
        }
        .sidebar-sublink:hover { background: #eef1f8; color: #2f3040; }
        .sidebar-sublink.active { background: #e8edfc; color: #4e73df; font-weight: 700; }
        .sidebar-sublink .bi { font-size: .85rem; width: 1rem; text-align: center; }

        .sidebar-footer {
            padding: .6rem;
            border-top: 1px solid rgba(0,0,0,.06);
        }

        /* Topbar */
        .topbar {
            background: #fff;
            border-bottom: 1px solid rgba(0,0,0,.06);
            padding: .6rem 1rem;
            display: flex;
            align-items: center;
            gap: .75rem;
        }

        .content-wrapper {
            min-width: 0;
        }

        @media (max-width: 767.98px) {
            .sidebar {
                position: fixed;
                left: 0;
                margin-left: calc(-1 * var(--sidebar-width));
            }
            .sidebar.show { margin-left: 0; }
            .sidebar-backdrop {
                display: none;
                position: fixed; inset: 0; background: rgba(0,0,0,.35); z-index: 1020;
            }
            .sidebar-backdrop.show { display: block; }
        }
    </style>
</head>
<body>
    <div id="app">
        <div id="wrapper" class="d-flex">
            @auth
            <div class="sidebar-backdrop" id="sidebarBackdrop"></div>
            <nav class="sidebar d-flex flex-column" id="sidebar">
                <div class="sidebar-brand">
                    @if (isset($negocio) && $negocio->logoUrl())
                        <img src="{{ $negocio->logoUrl() }}" alt="{{ $negocio->nombre }}">
                    @else
                        <span>{{ $negocio->nombre ?? config('app.name', 'Sistema de Facturación') }}</span>
                    @endif
                </div>

                <div class="sidebar-user">
                    <div class="avatar">{{ strtoupper(substr(Auth::user()->name, 0, 1)) }}</div>
                    <div>
                        <div class="name">{{ Auth::user()->name }} {{ Auth::user()->apellido }}</div>
                        <div class="role">{{ Auth::user()->role->nombre ?? '—' }}</div>
                    </div>
                </div>

                <div class="sidebar-nav">
                    @if (auth()->user()->puede('pos.acceso'))
                    <a class="sidebar-btn {{ request()->routeIs('facturacion.*') ? 'active' : '' }}" href="{{ route('facturacion.index') }}">
                        <i class="bi bi-cash-coin"></i> Facturar
                    </a>
                    @endif

                    @php
                        $catalogosActive = request()->routeIs('clientes.*', 'proveedores.*', 'categorias.*', 'departamentos.*', 'unidades.*', 'tipos-impuesto.*', 'configuracion.*');
                        $inventarioActive = request()->routeIs('inventario.*', 'entradas.create', 'entradas.store', 'ajustes.*', 'reposicion.*');
                        $cajaActive = request()->routeIs('notascredito.*', 'cortecaja.*');
                        $consultasActive = request()->routeIs('facturas.*', 'consultas.*');
                        $adminActive = request()->routeIs('operadores.*', 'roles.*', 'auditoria.*', 'cupones.*', 'backup.*');
                    @endphp

                    @if (auth()->user()->puede('catalogos.gestionar'))
                    <button class="sidebar-btn {{ $catalogosActive ? 'group-active' : '' }}" type="button" data-bs-toggle="collapse" data-bs-target="#navCatalogos" aria-expanded="{{ $catalogosActive ? 'true' : 'false' }}">
                        <i class="bi bi-tags"></i> Catálogos
                        <span class="badge bg-secondary badge-count">7</span>
                        <i class="bi bi-chevron-down chevron"></i>
                    </button>
                    <div class="collapse sidebar-submenu {{ $catalogosActive ? 'show' : '' }}" id="navCatalogos">
                        <a class="sidebar-sublink {{ request()->routeIs('clientes.*') ? 'active' : '' }}" href="{{ route('clientes.index') }}"><i class="bi bi-people"></i> Clientes</a>
                        <a class="sidebar-sublink {{ request()->routeIs('proveedores.*') ? 'active' : '' }}" href="{{ route('proveedores.index') }}"><i class="bi bi-truck"></i> Proveedores</a>
                        <a class="sidebar-sublink {{ request()->routeIs('categorias.*') ? 'active' : '' }}" href="{{ route('categorias.index') }}"><i class="bi bi-bookmark"></i> Categorías / Familias</a>
                        <a class="sidebar-sublink {{ request()->routeIs('departamentos.*') ? 'active' : '' }}" href="{{ route('departamentos.index') }}"><i class="bi bi-diagram-3"></i> Departamentos</a>
                        <a class="sidebar-sublink {{ request()->routeIs('unidades.*') ? 'active' : '' }}" href="{{ route('unidades.index') }}"><i class="bi bi-rulers"></i> Unidades</a>
                        <a class="sidebar-sublink {{ request()->routeIs('tipos-impuesto.*') ? 'active' : '' }}" href="{{ route('tipos-impuesto.index') }}"><i class="bi bi-percent"></i> Tipos de impuesto</a>
                        <a class="sidebar-sublink {{ request()->routeIs('configuracion.*') ? 'active' : '' }}" href="{{ route('configuracion.edit') }}"><i class="bi bi-building-gear"></i> Datos del negocio</a>
                    </div>
                    @endif

                    @if (auth()->user()->puede('inventario.gestionar'))
                    <button class="sidebar-btn {{ $inventarioActive ? 'group-active' : '' }}" type="button" data-bs-toggle="collapse" data-bs-target="#navInventario" aria-expanded="{{ $inventarioActive ? 'true' : 'false' }}">
                        <i class="bi bi-box-seam"></i> Inventario
                        <span class="badge bg-secondary badge-count">4</span>
                        <i class="bi bi-chevron-down chevron"></i>
                    </button>
                    <div class="collapse sidebar-submenu {{ $inventarioActive ? 'show' : '' }}" id="navInventario">
                        <a class="sidebar-sublink {{ request()->routeIs('inventario.*') ? 'active' : '' }}" href="{{ route('inventario.index') }}"><i class="bi bi-list-ul"></i> Productos</a>
                        <a class="sidebar-sublink {{ request()->routeIs('entradas.*') ? 'active' : '' }}" href="{{ route('entradas.create') }}"><i class="bi bi-box-arrow-in-down"></i> Entrada de inventario</a>
                        <a class="sidebar-sublink {{ request()->routeIs('ajustes.*') ? 'active' : '' }}" href="{{ route('ajustes.create') }}"><i class="bi bi-sliders"></i> Ajuste de inventario</a>
                        <a class="sidebar-sublink {{ request()->routeIs('reposicion.*') ? 'active' : '' }}" href="{{ route('reposicion.index') }}"><i class="bi bi-exclamation-triangle"></i> Reposición de inventario</a>
                    </div>
                    @endif

                    @if (auth()->user()->puede('caja.gestionar'))
                    <button class="sidebar-btn {{ $cajaActive ? 'group-active' : '' }}" type="button" data-bs-toggle="collapse" data-bs-target="#navCaja" aria-expanded="{{ $cajaActive ? 'true' : 'false' }}">
                        <i class="bi bi-safe"></i> Caja
                        <span class="badge bg-secondary badge-count">2</span>
                        <i class="bi bi-chevron-down chevron"></i>
                    </button>
                    <div class="collapse sidebar-submenu {{ $cajaActive ? 'show' : '' }}" id="navCaja">
                        <a class="sidebar-sublink {{ request()->routeIs('notascredito.*') ? 'active' : '' }}" href="{{ route('notascredito.index') }}"><i class="bi bi-receipt-cutoff"></i> Notas de crédito</a>
                        <a class="sidebar-sublink {{ request()->routeIs('cortecaja.*') ? 'active' : '' }}" href="{{ route('cortecaja.index') }}"><i class="bi bi-cash-stack"></i> Corte de caja</a>
                    </div>
                    @endif

                    @if (auth()->user()->puede('facturas.consultar') || auth()->user()->puede('reportes.ver'))
                    <button class="sidebar-btn {{ $consultasActive ? 'group-active' : '' }}" type="button" data-bs-toggle="collapse" data-bs-target="#navConsultas" aria-expanded="{{ $consultasActive ? 'true' : 'false' }}">
                        <i class="bi bi-search"></i> Consultas
                        <span class="badge bg-secondary badge-count">7</span>
                        <i class="bi bi-chevron-down chevron"></i>
                    </button>
                    <div class="collapse sidebar-submenu {{ $consultasActive ? 'show' : '' }}" id="navConsultas">
                        <a class="sidebar-sublink {{ request()->routeIs('facturas.index') ? 'active' : '' }}" href="{{ route('facturas.index') }}"><i class="bi bi-receipt"></i> Facturas General</a>
                        <a class="sidebar-sublink" href="{{ route('facturas.index') }}"><i class="bi bi-calendar-range"></i> Facturas por Fecha</a>
                        <a class="sidebar-sublink {{ request()->routeIs('clientes.*') ? 'active' : '' }}" href="{{ route('clientes.index') }}"><i class="bi bi-people"></i> Clientes</a>
                        <a class="sidebar-sublink {{ request()->routeIs('consultas.facturasFamilia') ? 'active' : '' }}" href="{{ route('consultas.facturasFamilia') }}"><i class="bi bi-bookmark-star"></i> Facturas / Familias</a>
                        <a class="sidebar-sublink {{ request()->routeIs('consultas.entradas') ? 'active' : '' }}" href="{{ route('consultas.entradas') }}"><i class="bi bi-box-arrow-in-down"></i> Entradas Inventario</a>
                        <a class="sidebar-sublink {{ request()->routeIs('reposicion.*') ? 'active' : '' }}" href="{{ route('reposicion.index') }}"><i class="bi bi-exclamation-triangle"></i> Reposición de Inventario</a>
                        <a class="sidebar-sublink {{ request()->routeIs('consultas.inventarioFamilia') ? 'active' : '' }}" href="{{ route('consultas.inventarioFamilia') }}"><i class="bi bi-box-seam"></i> Inventario por Familia</a>
                    </div>
                    @endif

                    @if (auth()->user()->puede('reportes.ver'))
                    <a class="sidebar-btn {{ request()->routeIs('reportes.index', 'reportes.ventas', 'reportes.compras', 'reportes.inventario') ? 'active' : '' }}" href="{{ route('reportes.index') }}">
                        <i class="bi bi-bar-chart-line"></i> Reportes
                    </a>

                    <a class="sidebar-btn {{ request()->routeIs('reportes.estadisticas*') ? 'active' : '' }}" href="{{ route('reportes.estadisticas') }}">
                        <i class="bi bi-graph-up"></i> Estadísticas
                    </a>
                    @endif

                    @php
                        $mostrarAdmin = auth()->user()->esAdmin() || auth()->user()->puede('cupones.gestionar') || auth()->user()->puede('auditoria.ver') || auth()->user()->puede('backup.gestionar');
                    @endphp
                    @if ($mostrarAdmin)
                        <button class="sidebar-btn {{ $adminActive ? 'group-active' : '' }}" type="button" data-bs-toggle="collapse" data-bs-target="#navAdmin" aria-expanded="{{ $adminActive ? 'true' : 'false' }}">
                            <i class="bi bi-shield-lock"></i> Administración
                            <i class="bi bi-chevron-down chevron"></i>
                        </button>
                        <div class="collapse sidebar-submenu {{ $adminActive ? 'show' : '' }}" id="navAdmin">
                            @if (auth()->user()->esAdmin())
                                <a class="sidebar-sublink {{ request()->routeIs('operadores.*') ? 'active' : '' }}" href="{{ route('operadores.index') }}"><i class="bi bi-person-badge"></i> Operadores</a>
                                <a class="sidebar-sublink {{ request()->routeIs('roles.*') ? 'active' : '' }}" href="{{ route('roles.index') }}"><i class="bi bi-key"></i> Roles y permisos</a>
                            @endif
                            @if (auth()->user()->puede('auditoria.ver'))
                                <a class="sidebar-sublink {{ request()->routeIs('auditoria.*') ? 'active' : '' }}" href="{{ route('auditoria.index') }}"><i class="bi bi-journal-text"></i> Auditoría</a>
                            @endif
                            @if (auth()->user()->puede('cupones.gestionar'))
                                <a class="sidebar-sublink {{ request()->routeIs('cupones.*') ? 'active' : '' }}" href="{{ route('cupones.index') }}"><i class="bi bi-ticket-perforated"></i> Cupones de descuento</a>
                            @endif
                            @if (auth()->user()->puede('backup.gestionar'))
                                <a class="sidebar-sublink {{ request()->routeIs('backup.*') ? 'active' : '' }}" href="{{ route('backup.index') }}"><i class="bi bi-hdd-network"></i> Backup de base de datos</a>
                            @endif
                        </div>
                    @endif
                </div>

                <div class="sidebar-footer">
                    <a class="sidebar-btn {{ request()->routeIs('perfil.*') ? 'active' : '' }}" href="{{ route('perfil.edit') }}">
                        <i class="bi bi-person-circle"></i> Mi perfil
                    </a>
                    <form action="{{ route('logout') }}" method="POST">
                        @csrf
                        <button type="submit" class="sidebar-btn text-danger">
                            <i class="bi bi-box-arrow-right"></i> Cerrar sesión
                        </button>
                    </form>
                </div>
            </nav>
            @endauth

            <div class="content-wrapper flex-grow-1">
                @auth
                    <div class="topbar">
                        <button class="btn btn-light d-md-none" id="sidebarToggle" type="button">
                            <i class="bi bi-list fs-5"></i>
                        </button>
                        <div class="ms-auto text-muted small">{{ Auth::user()->name }}</div>
                    </div>
                @endauth

                <main class="py-4 px-3 px-md-4">
                    @yield('content')
                </main>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var toggle = document.getElementById('sidebarToggle');
            var sidebar = document.getElementById('sidebar');
            var backdrop = document.getElementById('sidebarBackdrop');
            function closeSidebar() {
                sidebar && sidebar.classList.remove('show');
                backdrop && backdrop.classList.remove('show');
            }
            if (toggle && sidebar) {
                toggle.addEventListener('click', function () {
                    sidebar.classList.toggle('show');
                    backdrop && backdrop.classList.toggle('show');
                });
            }
            backdrop && backdrop.addEventListener('click', closeSidebar);
        });
    </script>
</body>
</html>
