{{-- resources/views/layouts/app.blade.php --}}
<!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>@yield('title', config('app.username', 'Seminario'))</title>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />

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

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Scripts -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])

    <style>
        :root {
            --sidebar-bg: #2c3e50;
            --sidebar-hover: #34495e;
            --sidebar-text: #ecf0f1;
            --primary-color: #3498db;
            --secondary-color: #2ecc71;
        }

        .sidebar {
            min-height: 100vh;
            background: var(--sidebar-bg);
            color: var(--sidebar-text);
            transition: all 0.3s;
        }

        .sidebar .nav-link {
            color: var(--sidebar-text);
            padding: 10px 20px;
            transition: all 0.3s;
        }

        .sidebar .nav-link:hover {
            background: var(--sidebar-hover);
            padding-left: 25px;
        }

        .sidebar .nav-link.active {
            background: var(--primary-color);
        }

        .sidebar .submenu {
            padding-left: 30px;
            background: rgba(0,0,0,0.1);
        }

        .sidebar .submenu .nav-link {
            font-size: 0.9rem;
        }

        .menu-icon {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        .toggle-submenu {
            float: right;
            transition: transform 0.3s;
        }

        .toggle-submenu.rotated {
            transform: rotate(90deg);
        }

        .main-content {
            padding: 20px;
            background: #f8f9fa;
            min-height: 100vh;
        }

        .config-panel {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav class="col-md-3 col-lg-2 d-md-block sidebar p-0">
            <div class="position-sticky">
                <div class="p-3 text-center border-bottom">
                    <h4 class="mb-1">Usuario:</h4>
                    @if(Auth::check())
                        @php
                            $usuarioAuth = Auth::user();
                            $textoUsuario = $usuarioAuth->dni
                                ? $usuarioAuth->dni . ': ' . $usuarioAuth->nombres
                                : ($usuarioAuth->username ?? 'Usuario');
                            $textoSede = !empty($usuarioAuth->id_sede)
                                ? (optional($usuarioAuth->sede)->sede ?? '')
                                : 'SUPER ADMINISTRADOR';
                        @endphp
                        <small class="d-block">{{ $textoUsuario }}</small>
                        <small class="d-block mt-1">{{ $textoSede }}</small>
                    @else
                        <small class="d-block">Invitado</small>
                    @endif
                </div>

                <!-- Configuración Visual -->
                <div class="m-1">
                    <a class="nav-link d-flex align-items-center justify-content-between"
                       href="#"
                       onclick="toggleSubmenu(event, 'configSubmenu', 'configArrow')">
                        <span>
                            <i class="fas fa-palette me-2 menu-icon"></i>
                            Configuración Visual
                        </span>
                        <i class="fas fa-chevron-right toggle-submenu" id="configArrow"></i>
                    </a>

                    <div class="config-panel" id="configSubmenu" style="display:none;">
                        <div class="mb-2">
                            <label class="form-label">Color Principal</label>
                            <input type="color" class="form-control form-control-color" id="primaryColor" value="#3498db">
                        </div>

                        <div class="mb-2">
                            <label class="form-label">Color Secundario</label>
                            <input type="color" class="form-control form-control-color" id="secondaryColor" value="#2ecc71">
                        </div>

                        <button class="btn btn-sm btn-primary w-100" onclick="applyColors()">
                            <i class="fas fa-check me-2"></i>Aplicar
                        </button>
                    </div>
                </div>

                @php
                    $u = Auth::user();

                    /*
                    |--------------------------------------------------------------------------
                    | 1) NORMALIZAR sidebarMenus
                    |--------------------------------------------------------------------------
                    */
                    $rawMenus = $sidebarMenus ?? [];

                    if ($rawMenus instanceof \Illuminate\Support\Collection) {
                        $rawMenus = $rawMenus->toArray();
                    }

                    $normalizeMenus = function ($items) use (&$normalizeMenus) {
                        $result = [];

                        foreach (($items ?? []) as $item) {
                            if ($item instanceof \Illuminate\Database\Eloquent\Model) {
                                $item = $item->toArray();
                            } elseif (is_object($item)) {
                                $item = (array) $item;
                            }

                            if (!is_array($item)) {
                                continue;
                            }

                            $children = $item['children'] ?? [];
                            if ($children instanceof \Illuminate\Support\Collection) {
                                $children = $children->toArray();
                            }

                            $item = array_merge([
                                'id' => 'm_' . md5(
                                    ($item['nombre'] ?? 'menu') . '|' .
                                    ($item['route_name'] ?? '') . '|' .
                                    ($item['route_pattern'] ?? '') . '|' .
                                    ($item['url'] ?? '')
                                ),
                                'nombre' => '',
                                'icon' => 'fas fa-link',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => [],
                            ], $item);

                            $item['children'] = $normalizeMenus($children);
                            $result[] = $item;
                        }

                        return $result;
                    };

                    $menus = $normalizeMenus($rawMenus);

                    /*
                    |--------------------------------------------------------------------------
                    | 2) FILTRAR SEGÚN PRIVILEGIOS
                    |--------------------------------------------------------------------------
                    */
                    $filterVisibleMenus = function ($items) use (&$filterVisibleMenus, $u) {
                        $result = [];

                        foreach (($items ?? []) as $item) {
                            $children = $filterVisibleMenus($item['children'] ?? []);

                            $routePattern = $item['route_pattern'] ?? null;
                            $routeName    = $item['route_name'] ?? null;
                            $url          = $item['url'] ?? null;

                            $visible = false;

                            if (!empty($children)) {
                                $visible = true;
                            } else {
                                if ($u) {
                                    if (!empty($routePattern)) {
                                        $visible = $u->canSeeMenu($routePattern);
                                    } elseif (!empty($routeName)) {
                                        $visible = $u->canSeeMenu($routeName)
                                                || $u->canSeeMenu($routeName . '.*');
                                    } elseif (!empty($url)) {
                                        $visible = true;
                                    }
                                }
                            }

                            if ($visible) {
                                $item['children'] = $children;
                                $result[] = $item;
                            }
                        }

                        return $result;
                    };

                    $menus = $filterVisibleMenus($menus);

                    /*
                    |--------------------------------------------------------------------------
                    | 3) FALLBACK MANUAL CORREGIDO
                    |    IMPORTANTE: CAJA USA admin.* COMO EN EL DASHBOARD
                    |--------------------------------------------------------------------------
                    */
                    $buildFallbackMenus = function () use ($u) {
                        $adminChildren = [];
                        $codigoChildren = [];
                        $proyectosChildren = [];
                        $cuentasChildren = [];
                        $bancoChildren = [];
                        $parametrosChildren = [];
                        $cajaChildren = [];

                        // ===== ADMIN =====
                        if ($u && $u->canSeeMenu('admin.sede.*')) {
                            $adminChildren[] = [
                                'id' => 9101,
                                'nombre' => 'Sede',
                                'icon' => 'fas fa-building',
                                'route_name' => 'admin.sede.index',
                                'url' => null,
                                'route_pattern' => 'admin.sede.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.tipo-usuario.*')) {
                            $adminChildren[] = [
                                'id' => 9106,
                                'nombre' => 'Tipo Usuario',
                                'icon' => 'fas fa-tag',
                                'route_name' => 'admin.tipo-usuario.index',
                                'url' => null,
                                'route_pattern' => 'admin.tipo-usuario.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.usuario.*')) {
                            $adminChildren[] = [
                                'id' => 9102,
                                'nombre' => 'Usuarios',
                                'icon' => 'fas fa-users',
                                'route_name' => 'admin.usuario.index',
                                'url' => null,
                                'route_pattern' => 'admin.usuario.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.menu.*')) {
                            $adminChildren[] = [
                                'id' => 9103,
                                'nombre' => 'Menús',
                                'icon' => 'fas fa-sitemap',
                                'route_name' => 'admin.menu.index',
                                'url' => null,
                                'route_pattern' => 'admin.menu.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.privilegios.*')) {
                            $adminChildren[] = [
                                'id' => 9104,
                                'nombre' => 'Privilegios',
                                'icon' => 'fas fa-key',
                                'route_name' => 'admin.privilegios.index',
                                'url' => null,
                                'route_pattern' => 'admin.privilegios.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.auditoria.*')) {
                            $adminChildren[] = [
                                'id' => 9105,
                                'nombre' => 'Auditoría',
                                'icon' => 'fas fa-clipboard-list',
                                'route_name' => 'admin.auditoria.index',
                                'url' => null,
                                'route_pattern' => 'admin.auditoria.*',
                                'children' => [],
                            ];
                        }

                        // ===== CAJA =====
                        if ($u && $u->canSeeMenu('admin.apertura-cierre.*')) {
                            $cajaChildren[] = [
                                'id' => 9601,
                                'nombre' => 'Apertura',
                                'icon' => 'fas fa-box-open',
                                'route_name' => 'admin.apertura-cierre.index',
                                'url' => null,
                                'route_pattern' => 'admin.apertura-cierre.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.cierre.*')) {
                            $cajaChildren[] = [
                                'id' => 9602,
                                'nombre' => 'Cierre',
                                'icon' => 'fas fa-door-closed',
                                'route_name' => 'admin.cierre.index',
                                'url' => null,
                                'route_pattern' => 'admin.cierre.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.ingreso.*')) {
                            $cajaChildren[] = [
                                'id' => 9603,
                                'nombre' => 'Ingresos',
                                'icon' => 'fas fa-circle-plus',
                                'route_name' => 'admin.ingreso.index',
                                'url' => null,
                                'route_pattern' => 'admin.ingreso.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.egreso.*')) {
                            $cajaChildren[] = [
                                'id' => 9604,
                                'nombre' => 'Egresos',
                                'icon' => 'fas fa-circle-minus',
                                'route_name' => 'admin.egreso.index',
                                'url' => null,
                                'route_pattern' => 'admin.egreso.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.ingreso-anular.*')) {
                            $cajaChildren[] = [
                                'id' => 9605,
                                'nombre' => 'Ingreso anular',
                                'icon' => 'fas fa-trash-can',
                                'route_name' => 'admin.ingreso-anular.index',
                                'url' => null,
                                'route_pattern' => 'admin.ingreso-anular.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.salida-anular.*')) {
                            $cajaChildren[] = [
                                'id' => 9606,
                                'nombre' => 'Salida anular',
                                'icon' => 'fas fa-trash-can',
                                'route_name' => 'admin.salida-anular.index',
                                'url' => null,
                                'route_pattern' => 'admin.salida-anular.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.reporte-movimientos.*')) {
                            $cajaChildren[] = [
                                'id' => 9607,
                                'nombre' => 'Reporte Ingreso y Egresos',
                                'icon' => 'fas fa-chart-column',
                                'route_name' => 'admin.reporte-movimientos.index',
                                'url' => '/admin/reporte-movimientos',
                                'route_pattern' => 'admin.reporte-movimientos.*',
                                'children' => [],
                            ];
                        }

                        // ===== CÓDIGOS =====
                        if ($u && $u->canSeeMenu('admin.codigo-ingreso.*')) {
                            $codigoChildren[] = [
                                'id' => 9201,
                                'nombre' => 'Código Ingreso',
                                'icon' => 'fas fa-arrow-right',
                                'route_name' => 'admin.codigo-ingreso.index',
                                'url' => null,
                                'route_pattern' => 'admin.codigo-ingreso.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.codigo-ingreso-detalle.*')) {
                            $codigoChildren[] = [
                                'id' => 9202,
                                'nombre' => 'Código Ingreso Detalle',
                                'icon' => 'fas fa-arrow-right',
                                'route_name' => 'admin.codigo-ingreso-detalle.index',
                                'url' => null,
                                'route_pattern' => 'admin.codigo-ingreso-detalle.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.codigo-egreso.*')) {
                            $codigoChildren[] = [
                                'id' => 9203,
                                'nombre' => 'Código Egreso',
                                'icon' => 'fas fa-arrow-left',
                                'route_name' => 'admin.codigo-egreso.index',
                                'url' => null,
                                'route_pattern' => 'admin.codigo-egreso.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.codigo-egreso-detalle.*')) {
                            $codigoChildren[] = [
                                'id' => 9204,
                                'nombre' => 'Código Egreso Detalle',
                                'icon' => 'fas fa-arrow-left',
                                'route_name' => 'admin.codigo-egreso-detalle.index',
                                'url' => null,
                                'route_pattern' => 'admin.codigo-egreso-detalle.*',
                                'children' => [],
                            ];
                        }

                        // ===== PROYECTOS =====
                        if ($u && $u->canSeeMenu('admin.proyecto.*')) {
                            $proyectosChildren[] = [
                                'id' => 9301,
                                'nombre' => 'Proyecto',
                                'icon' => 'fas fa-diagram-project',
                                'route_name' => 'admin.proyecto.index',
                                'url' => null,
                                'route_pattern' => 'admin.proyecto.*',
                                'children' => [],
                            ];
                        }

                        // ===== CUENTAS =====
                        if ($u && $u->canSeeMenu('admin.cuenta.*')) {
                            $cuentasChildren[] = [
                                'id' => 9401,
                                'nombre' => 'Cuentas',
                                'icon' => 'fas fa-credit-card',
                                'route_name' => 'admin.cuenta.index',
                                'url' => null,
                                'route_pattern' => 'admin.cuenta.*',
                                'children' => [],
                            ];
                        }

                        // ===== BANCO =====
                        if ($u && $u->canSeeMenu('admin.migrardatos.*')) {
                            $bancoChildren[] = [
                                'id' => 9451,
                                'nombre' => 'Migrar Datos',
                                'icon' => 'fas fa-database',
                                'route_name' => 'admin.migrardatos.index',
                                'url' => null,
                                'route_pattern' => 'admin.migrardatos.*',
                                'children' => [],
                            ];
                        }

                        if ($u && $u->canSeeMenu('admin.reportedemigracion.*')) {
                            $bancoChildren[] = [
                                'id' => 9453,
                                'nombre' => 'Reporte De Migracion',
                                'icon' => 'fas fa-clipboard-list',
                                'route_name' => 'admin.reportedemigracion.index',
                                'url' => null,
                                'route_pattern' => 'admin.reportedemigracion.*',
                                'children' => [],
                            ];
                        }

                        // ===== PARAMETROS =====
                        if ($u && $u->canSeeMenu('admin.comprobante.*')) {
                            $parametrosChildren[] = [
                                'id' => 9501,
                                'nombre' => 'Parametros',
                                'icon' => 'fas fa-sliders',
                                'route_name' => 'admin.comprobante.index',
                                'url' => null,
                                'route_pattern' => 'admin.comprobante.*',
                                'children' => [],
                            ];
                        }

                        $fallback = [];

                        if ($u && $u->canSeeMenu('dashboard')) {
                            $fallback[] = [
                                'id' => 9001,
                                'nombre' => 'Panel de Control',
                                'icon' => 'fas fa-home',
                                'route_name' => 'dashboard',
                                'url' => null,
                                'route_pattern' => 'dashboard',
                                'children' => [],
                            ];
                        }

                        if (!empty($cajaChildren)) {
                            $fallback[] = [
                                'id' => 9600,
                                'nombre' => 'Caja',
                                'icon' => 'fas fa-cash-register',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => $cajaChildren,
                            ];
                        }

                        if (!empty($bancoChildren)) {
                            $fallback[] = [
                                'id' => 9452,
                                'nombre' => 'Banco',
                                'icon' => 'fas fa-piggy-bank',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => $bancoChildren,
                            ];
                        }

                        if (!empty($adminChildren)) {
                            $fallback[] = [
                                'id' => 9002,
                                'nombre' => 'Administrar',
                                'icon' => 'fas fa-cog',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => $adminChildren,
                            ];
                        }

                        if (!empty($codigoChildren)) {
                            $fallback[] = [
                                'id' => 9004,
                                'nombre' => 'Códigos',
                                'icon' => 'fas fa-file-code',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => $codigoChildren,
                            ];
                        }

                        if (!empty($proyectosChildren)) {
                            $fallback[] = [
                                'id' => 9005,
                                'nombre' => 'Proyectos',
                                'icon' => 'fas fa-folder-tree',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => $proyectosChildren,
                            ];
                        }

                        if (!empty($cuentasChildren)) {
                            $fallback[] = [
                                'id' => 9402,
                                'nombre' => 'Cuentas',
                                'icon' => 'fas fa-piggy-bank',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => $cuentasChildren,
                            ];
                        }

                        if (!empty($parametrosChildren)) {
                            $fallback[] = [
                                'id' => 9502,
                                'nombre' => 'Parametros',
                                'icon' => 'fas fa-print',
                                'route_name' => null,
                                'url' => null,
                                'route_pattern' => null,
                                'children' => $parametrosChildren,
                            ];
                        }

                        if ($u && $u->canSeeMenu('profile.*')) {
                            $fallback[] = [
                                'id' => 9003,
                                'nombre' => 'Perfil',
                                'icon' => 'fas fa-user',
                                'route_name' => 'profile.edit',
                                'url' => null,
                                'route_pattern' => 'profile.*',
                                'children' => [],
                            ];
                        }

                        return $fallback;
                    };

                    $fallbackMenus = $buildFallbackMenus();

                    /*
                    |--------------------------------------------------------------------------
                    | 4) SI NO HAY MENÚS, USAR FALLBACK
                    |--------------------------------------------------------------------------
                    */
                    if (blank($menus)) {
                        $menus = $fallbackMenus;
                    } else {
                        /*
                        |--------------------------------------------------------------------------
                        | 5) COMPLETAR MENÚS INCOMPLETOS DESDE FALLBACK
                        |--------------------------------------------------------------------------
                        */
                        foreach ($fallbackMenus as $fm) {
                            $foundIndex = null;

                            foreach ($menus as $idx => $existingMenu) {
                                if (mb_strtolower(trim($existingMenu['nombre'] ?? '')) === mb_strtolower(trim($fm['nombre'] ?? ''))) {
                                    $foundIndex = $idx;
                                    break;
                                }
                            }

                            if ($foundIndex === null) {
                                $menus[] = $fm;
                                continue;
                            }

                            // Si existe el padre, completamos hijos faltantes
                            if (!empty($fm['children'])) {
                                $existingChildren = $menus[$foundIndex]['children'] ?? [];
                                $existingKeys = [];

                                foreach ($existingChildren as $child) {
                                    $key = mb_strtolower(
                                        trim(($child['route_name'] ?? '') . '|' . ($child['route_pattern'] ?? '') . '|' . ($child['nombre'] ?? ''))
                                    );
                                    $existingKeys[] = $key;
                                }

                                foreach ($fm['children'] as $fallbackChild) {
                                    $fallbackKey = mb_strtolower(
                                        trim(($fallbackChild['route_name'] ?? '') . '|' . ($fallbackChild['route_pattern'] ?? '') . '|' . ($fallbackChild['nombre'] ?? ''))
                                    );

                                    if (!in_array($fallbackKey, $existingKeys, true)) {
                                        $existingChildren[] = $fallbackChild;
                                    }
                                }

                                $menus[$foundIndex]['children'] = $existingChildren;
                            }
                        }
                    }

                    $sortByFallbackOrder = function (array $items, array $referenceItems) use (&$sortByFallbackOrder): array {
                        $orderMap = [];
                        foreach (array_values($referenceItems) as $index => $referenceItem) {
                            $orderMap[mb_strtolower(trim((string) ($referenceItem['nombre'] ?? '')))] = $index;
                        }

                        foreach ($items as $index => &$item) {
                            $item['__original_index'] = $index;

                            $referenceChildren = [];
                            foreach ($referenceItems as $referenceItem) {
                                if (mb_strtolower(trim((string) ($referenceItem['nombre'] ?? ''))) === mb_strtolower(trim((string) ($item['nombre'] ?? '')))) {
                                    $referenceChildren = $referenceItem['children'] ?? [];
                                    break;
                                }
                            }

                            $item['children'] = $sortByFallbackOrder($item['children'] ?? [], $referenceChildren);
                        }
                        unset($item);

                        usort($items, function ($a, $b) use ($orderMap) {
                            $nameA = mb_strtolower(trim((string) ($a['nombre'] ?? '')));
                            $nameB = mb_strtolower(trim((string) ($b['nombre'] ?? '')));
                            $rankA = $orderMap[$nameA] ?? 9999;
                            $rankB = $orderMap[$nameB] ?? 9999;

                            if ($rankA === $rankB) {
                                return ((int) ($a['__original_index'] ?? 0)) <=> ((int) ($b['__original_index'] ?? 0));
                            }

                            return $rankA <=> $rankB;
                        });

                        foreach ($items as &$item) {
                            unset($item['__original_index']);
                        }
                        unset($item);

                        return $items;
                    };

                    $menus = $sortByFallbackOrder($menus, $fallbackMenus);

                    /*
                    |--------------------------------------------------------------------------
                    | 6) DETERMINAR ACTIVO
                    |--------------------------------------------------------------------------
                    */
                    $isActive = function(array $m) use (&$isActive): bool {
                        if (!empty($m['route_pattern']) && request()->routeIs($m['route_pattern'])) {
                            return true;
                        }

                        if (!empty($m['route_name']) && request()->routeIs($m['route_name'])) {
                            return true;
                        }

                        foreach (($m['children'] ?? []) as $c) {
                            if ($isActive($c)) {
                                return true;
                            }
                        }

                        return false;
                    };
                @endphp

                <ul class="nav flex-column">
                    @foreach($menus as $m)
                        @php
                            $hasChildren = !empty($m['children']);
                            $submenuId = 'submenu_' . $m['id'];
                            $arrowId = 'arrow_' . $m['id'];
                            $active = $isActive($m);

                            $href = '#';
                            if (!$hasChildren) {
                                if (!empty($m['route_name']) && \Illuminate\Support\Facades\Route::has($m['route_name'])) {
                                    $href = route($m['route_name']);
                                } elseif (!empty($m['url'])) {
                                    $href = $m['url'];

                                    if (!\Illuminate\Support\Str::startsWith($href, ['http://', 'https://'])) {
                                        if (!\Illuminate\Support\Str::startsWith($href, '/')) {
                                            $href = '/' . $href;
                                        }
                                        $href = url($href);
                                    }
                                }
                            }
                        @endphp

                        <li class="nav-item">
                            @if($hasChildren)
                                <a class="nav-link {{ $active ? 'active' : '' }}"
                                   href="#"
                                   onclick="toggleSubmenu(event, '{{ $submenuId }}', '{{ $arrowId }}')">
                                    <i class="{{ $m['icon'] ?? 'fas fa-folder' }} menu-icon"></i>
                                    {{ $m['nombre'] }}
                                    <i class="fas fa-chevron-right toggle-submenu {{ $active ? 'rotated' : '' }}" id="{{ $arrowId }}"></i>
                                </a>

                                <ul class="nav flex-column submenu" id="{{ $submenuId }}" style="display: {{ $active ? 'block' : 'none' }};">
                                    @foreach($m['children'] as $c)
                                        @php
                                            $childHref = '#';

                                            if (!empty($c['route_name']) && \Illuminate\Support\Facades\Route::has($c['route_name'])) {
                                                $childHref = route($c['route_name']);
                                            } elseif (!empty($c['url'])) {
                                                $childHref = $c['url'];

                                                if (!\Illuminate\Support\Str::startsWith($childHref, ['http://', 'https://'])) {
                                                    if (!\Illuminate\Support\Str::startsWith($childHref, '/')) {
                                                        $childHref = '/' . $childHref;
                                                    }
                                                    $childHref = url($childHref);
                                                }
                                            }

                                            $childActive =
                                                (!empty($c['route_pattern']) && request()->routeIs($c['route_pattern'])) ||
                                                (!empty($c['route_name']) && request()->routeIs($c['route_name']));
                                        @endphp

                                        <li class="nav-item">
                                            <a class="nav-link {{ $childActive ? 'active' : '' }}" href="{{ $childHref }}">
                                                <i class="{{ $c['icon'] ?? 'fas fa-link' }} menu-icon"></i>
                                                {{ $c['nombre'] }}
                                            </a>
                                        </li>
                                    @endforeach
                                </ul>
                            @else
                                <a class="nav-link {{ $active ? 'active' : '' }}" href="{{ $href }}">
                                    <i class="{{ $m['icon'] ?? 'fas fa-link' }} menu-icon"></i>
                                    {{ $m['nombre'] }}
                                </a>
                            @endif
                        </li>
                    @endforeach

                    @auth
                        <li class="nav-item">
                            <form method="POST" action="{{ route('logout') }}">
                                @csrf
                                <a class="nav-link" href="#"
                                   onclick="event.preventDefault(); this.closest('form').submit();">
                                    <i class="fas fa-sign-out-alt menu-icon"></i>
                                    Cerrar Sesión
                                </a>
                            </form>
                        </li>
                    @endauth
                </ul>
            </div>
        </nav>

        <!-- Main content -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
            @if(session('success') && !request()->routeIs('admin.apertura-cierre.index') && !request()->routeIs('admin.cierre.index'))
                <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
                    {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            @endif

            @if($errors->any())
                <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert">
                    <ul class="mb-0">
                        @foreach($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            @endif

            @yield('content')
            {{ $slot ?? '' }}
        </main>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
    function toggleSubmenu(event, submenuId, arrowId) {
        event.preventDefault();

        const submenu = document.getElementById(submenuId);
        const arrow = arrowId ? document.getElementById(arrowId) : null;

        if (!submenu) return;

        const isHidden = submenu.style.display === 'none' || submenu.style.display === '';
        submenu.style.display = isHidden ? 'block' : 'none';

        if (arrow) {
            arrow.classList.toggle('rotated', isHidden);
        }
    }

    function applyColors() {
        const primary = document.getElementById('primaryColor').value;
        const secondary = document.getElementById('secondaryColor').value;

        document.documentElement.style.setProperty('--primary-color', primary);
        document.documentElement.style.setProperty('--secondary-color', secondary);

        localStorage.setItem('primaryColor', primary);
        localStorage.setItem('secondaryColor', secondary);
    }

    window.addEventListener('load', function () {
        const primary = localStorage.getItem('primaryColor');
        const secondary = localStorage.getItem('secondaryColor');

        if (primary) {
            document.documentElement.style.setProperty('--primary-color', primary);
            const el = document.getElementById('primaryColor');
            if (el) el.value = primary;
        }

        if (secondary) {
            document.documentElement.style.setProperty('--secondary-color', secondary);
            const el = document.getElementById('secondaryColor');
            if (el) el.value = secondary;
        }
    });
</script>

</body>
</html>
