<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title', 'Colegio Windsor')</title>
    <style>
        :root {
            --brand-top: #c4d0c1;
            --brand-bot: #c4d0c1;
            --paper: #ffffff;
            --frame: #0d6f8f;
            --ink: #0f1f2f;
            --muted: #607080;
            --line: #d2dce5;
            --active: #004f6a;
            --fs-title-global: 22px;
            --fs-box-head-global: 16px;
            --fs-subtitle-global: 18px;
            --fs-table-head-global: 14px;
            --fs-table-cell-global: 13px;
            --fs-total-global: 13px;
            --fs-label-global: 14px;
            --fs-input-global: 13px;
            --fs-button-global: 14px;
            --fs-menu-main: 14px;
            --fs-menu-sub: 14px;
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: "Segoe UI", Tahoma, sans-serif;
            background: #e8eef3;
            color: var(--ink);
        }
        .wrap {
            width: min(1280px, 100%);
            margin: 0 auto;
            min-height: 100vh;
            border: 6px solid var(--frame);
            background: var(--paper);
        }
        .head {
            background: linear-gradient(180deg, var(--brand-top), var(--brand-bot));
            color: #fff;
            padding: 12px 18px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            flex-wrap: wrap;
        }
        .head-left { display:flex; align-items:center; gap:10px; }
        .head-left-text strong { display: block; font-size: 14px; opacity: .92; }
        .head-left-text span { font-size: 20px; line-height: 1.1; font-weight: 700; }
        .head-mid { font-size: 15px; }
        .head-mid b { color: #ffd166; }
        .head-right { text-align: right; font-size: 14px; }
        .logout-btn {
            background: transparent;
            border: 1px solid rgba(255,255,255,.5);
            color: #fff;
            padding: 7px 10px;
            border-radius: 6px;
            cursor: pointer;
            margin-top: 6px;
        }
        .menu {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
            border-bottom: 2px dotted #2a9ab8;
            padding: 6px 8px;
            background: #fff;
        }
        .menu a, .menu .menu-parent {
            text-decoration: none;
            color: #000;
            padding: 6px 8px;
            border-radius: 6px;
            font-weight: 400;
            display: inline-block;
            font-size: var(--fs-menu-main);
            line-height: 1.1;
        }
        .menu a.active, .menu a:hover, .menu .menu-parent:hover {
            background: #eaf6fa;
            color: var(--active);
        }
        .menu-item {
            position: relative;
        }
        .submenu {
            display: none;
            position: absolute;
            left: 0;
            top: 100%;
            min-width: 220px;
            background: #e6e9ee;
            border: 1px solid #4f4f4f;
            z-index: 15;
            box-shadow: 0 8px 18px rgba(0, 0, 0, 0.18);
        }
        .submenu a {
            display: block;
            padding: 8px 12px;
            border-radius: 0;
            font-size: var(--fs-menu-sub);
            color: #000;
            line-height: 1.15;
            font-weight: 400;
            text-decoration: none;
        }
        .submenu a:hover {
            background: #d4dae2;
            color: #000;
        }
        .submenu-item {
            position: relative;
        }
        .submenu-level2 {
            display: none;
            position: absolute;
            left: 100%;
            top: -1px;
            min-width: 240px;
            background: #eef1f5;
            border: 1px solid #4f4f4f;
            z-index: 20;
            box-shadow: 0 8px 18px rgba(0, 0, 0, 0.18);
        }
        .submenu-item:hover .submenu-level2 {
            display: block;
        }
        .menu-item:hover .submenu {
            display: block;
        }
        .subbar {
            padding: 6px 12px;
            display: flex;
            justify-content: space-between;
            gap: 8px;
            color: #1b2b3a;
            flex-wrap: wrap;
            font-size: 14px;
        }
        .years a {
            color: #9aa6b2;
            text-decoration: none;
            margin-left: 6px;
            font-weight: 700;
        }
        .years a.active {
            color: #006a8f;
            text-decoration: underline;
            text-underline-offset: 2px;
        }
        .content { padding: 20px 14px 24px; min-height: 70vh; }
        .panel { background: #fff; border: 1px solid var(--line); border-radius: 10px; padding: 14px; }
        .cards { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 14px; }
        .card { background: #fff; border: 1px solid var(--line); border-radius: 10px; padding: 12px; }
        .card .k { font-size: 12px; color: var(--muted); margin-bottom: 6px; text-transform: uppercase; }
        .card .v { font-size: 26px; color: #0b7285; font-weight: 700; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 10px; border-bottom: 1px solid #ebf0f5; text-align: left; font-size: 14px; }
        th { color: var(--muted); background: #f8fafc; }
        .toolbar { margin-bottom: 12px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
        input, select, textarea {
            border: 1px solid #c7d2de;
            border-radius: 8px;
            padding: 8px 10px;
            font-size: var(--fs-input-global);
        }
        button {
            background: #0b7285;
            color: #fff;
            border-color: #0b7285;
            cursor: pointer;
            font-size: var(--fs-button-global);
        }
        .pagination { margin-top: 12px; }
        .pagination nav { display: block; }
        .pagination ul {
            list-style: none;
            margin: 0;
            padding: 0;
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            align-items: center;
        }
        .pagination li { margin: 0; padding: 0; }
        .pagination li a,
        .pagination li span {
            display: inline-block;
            min-width: 30px;
            padding: 4px 8px;
            text-align: center;
            text-decoration: none;
            border: 1px solid #9ab1bf;
            background: #eef4f7;
            color: #0f5068;
            border-radius: 3px;
            font-size: 12px;
            line-height: 1.2;
        }
        .pagination li.active span {
            background: #0d6f8f;
            border-color: #0d6f8f;
            color: #fff;
            font-weight: 700;
        }
        .pagination li.disabled span {
            background: #f2f2f2;
            border-color: #d4dbe0;
            color: #8a98a3;
        }
        .pagination p {
            margin: 8px 0 0;
            font-size: 12px;
            color: #334a59;
        }
        .ui-title { font-size: var(--fs-title-global) !important; }
        .ui-subtitle { font-size: var(--fs-subtitle-global) !important; }
        .ui-box-head { font-size: var(--fs-box-head-global) !important; }
        .ui-table-title { font-size: var(--fs-box-head-global) !important; }
        .legacy-title { font-size: var(--fs-title-global) !important; }
        .box-head, .table-title { font-size: var(--fs-box-head-global) !important; }
        .section-title { font-size: var(--fs-subtitle-global) !important; }
        .ui-table th { font-size: var(--fs-table-head-global) !important; }
        .ui-table td { font-size: var(--fs-table-cell-global) !important; }
        .legacy-table th { font-size: var(--fs-table-head-global) !important; }
        .legacy-table td { font-size: var(--fs-table-cell-global) !important; }
        .ui-total { font-size: var(--fs-total-global) !important; }
        .ui-label, .ui-label label { font-size: var(--fs-label-global) !important; }
        @media (max-width: 900px) { .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
        @media (max-width: 560px) {
            .cards { grid-template-columns: 1fr; }
            .head-left-text span { font-size: 16px; }
        }
    </style>
</head>
<body>
@php
    $currentRole = \Illuminate\Support\Str::lower((string) session('admin_role', 'admin'));
    $sessionUserId = (int) session('admin_user_id', 0);
    $roleLabelMap = [
        'admin' => 'Administrador',
        'superadmin' => 'Super Administrador',
        'coordinadores' => 'Coordinador',
        'secretarias' => 'Secretaria',
        'docentes' => 'Docente',
    ];
    $currentRoleLabel = $roleLabelMap[$currentRole] ?? ucfirst($currentRole ?: 'Usuario');
    $isAdmin = in_array($currentRole, ['admin', 'superadmin'], true);
    $canGeneral = $isAdmin || in_array($currentRole, ['coordinadores', 'secretarias'], true);
    $canMatriculas = $canGeneral;
    $canMensajeria = $canGeneral;
    $canAcademia = $isAdmin || in_array($currentRole, ['coordinadores'], true);
    $canCalificaciones = $isAdmin || in_array($currentRole, ['coordinadores'], true);
    $canObservador = true;
    $canCartera = $isAdmin || in_array($currentRole, ['coordinadores', 'secretarias'], true);
    $canContabilidad = $isAdmin;

    $menuBeforeAcademia = [];
    if ($canMatriculas) {
        $menuBeforeAcademia['Matrículas'] = route('admin.section', ['section' => 'matriculas']);
    }
    if ($canMensajeria) {
        $menuBeforeAcademia['Mensajería'] = route('admin.section', ['section' => 'mensajeria']);
    }

    $menuAfterAcademia = [];
    if ($canCartera) {
        $menuAfterAcademia['Cartera'] = route('admin.cartera.index');
    }
    if ($canContabilidad) {
        $menuAfterAcademia['Contabilidad'] = route('admin.section', ['section' => 'contabilidad']);
    }
    $generalMenu = [
        'Estudiantes' => route('admin.estudiantes.index'),
        'Profesores' => route('admin.profesores.index'),
        'Grupos Familiares ->' => route('admin.general.item', ['item' => 'grupos-familiares']),
        'Grados ->' => route('admin.general.grados.item', ['item' => 'todos']),
        'Cursos ->' => route('admin.general.cursos.item', ['item' => 'todos']),
        'Cambio de Clave' => route('admin.general.item', ['item' => 'cambio-clave']),
    ];
    $generalGradosMenu = [
        'todos' => ['label' => 'Todos', 'url' => route('admin.general.grados.item', ['item' => 'todos'])],
    ];
    $generalCursosMenu = [
        'todos' => ['label' => 'Todos', 'url' => route('admin.general.cursos.item', ['item' => 'todos'])],
        'listas-curso' => ['label' => 'Listas de Curso', 'url' => route('admin.general.cursos.item', ['item' => 'listas-curso'])],
    ];
    $generalGruposMenu = [
        'acudientes' => ['label' => 'Acudientes', 'url' => route('admin.general.grupos.item', ['item' => 'acudientes'])],
        'grupos-familiares' => ['label' => 'Grupos Familiares', 'url' => route('admin.general.grupos.item', ['item' => 'grupos-familiares'])],
    ];
    $academiaMenu = [
        'asignaturas' => ['label' => 'Asignaturas', 'url' => route('admin.academia.item', ['item' => 'asignaturas'])],
        'areas-academicas' => ['label' => 'Áreas Académicas', 'url' => route('admin.academia.item', ['item' => 'areas-academicas'])],
        'periodos-academicos' => ['label' => 'Períodos Académicos', 'url' => route('admin.academia.item', ['item' => 'periodos-academicos'])],
    ];
    $academiaAsignacionMenu = [
        'estado-actual' => ['label' => 'Estado Actual', 'url' => route('admin.academia.asignacion.item', ['item' => 'estado-actual'])],
        'por-curso' => ['label' => 'Por Curso', 'url' => route('admin.academia.asignacion.item', ['item' => 'por-curso'])],
        'por-profesor-asignatura' => ['label' => 'Por Profesor y Asignatura', 'url' => route('admin.academia.asignacion.item', ['item' => 'por-profesor-asignatura'])],
    ];
    $calificacionesMenu = [
        'niveles-calificaciones' => ['label' => 'Niveles de Calificaciones', 'url' => route('admin.calificaciones.item', ['item' => 'niveles-calificaciones'])],
        'logros' => ['label' => 'Logros', 'url' => route('admin.calificaciones.item', ['item' => 'logros'])],
        'calificaciones-faltantes' => ['label' => 'Calificaciones Faltantes', 'url' => route('admin.calificaciones.item', ['item' => 'calificaciones-faltantes'])],
        'registro-calificaciones' => ['label' => 'Registro de Calificaciones', 'url' => route('admin.calificaciones.item', ['item' => 'registro-calificaciones'])],
        'generacion-boletines' => ['label' => 'Generación de Boletines ->', 'url' => route('admin.calificaciones.item', ['item' => 'generacion-boletines'])],
        'reportes' => ['label' => 'Reportes ->', 'url' => route('admin.calificaciones.item', ['item' => 'reportes'])],
    ];
    if ($isAdmin || $currentRole === 'coordinadores') {
        $calificacionesMenu = collect($calificacionesMenu)
            ->prepend(['label' => 'Apertura de Notas', 'url' => route('admin.calificaciones.item', ['item' => 'periodos-notas'])], 'periodos-notas')
            ->all();
    }
    if (in_array($currentRole, ['docentes', 'coordinadores'], true)) {
        $calificacionesMenu = collect($calificacionesMenu)
            ->prepend(['label' => 'Mi Carga Académica', 'url' => route('admin.academia.asignacion.item', ['item' => 'estado-actual'])], 'mi-carga-academica')
            ->all();
    }
    if ($isAdmin || in_array($currentRole, ['docentes', 'coordinadores'], true)) {
        $calificacionesMenu = collect($calificacionesMenu)
            ->prepend(['label' => 'Dirección de grupo', 'url' => route('admin.calificaciones.item', ['item' => 'curso-a-cargo'])], 'curso-a-cargo')
            ->all();
    }
    $academicYears = \Illuminate\Support\Facades\Cache::remember('ui_academic_years', 3600, function () {
        return \Illuminate\Support\Facades\DB::table('sweb_notas_v2')
            ->distinct()
            ->orderByDesc('annio')
            ->pluck('annio');
    });
    $selectedYear = (int) request('annio', date('Y'));
    $isDocenteDirectorGrupo = false;
    if ($currentRole === 'docentes' && $sessionUserId > 0) {
        $isDocenteDirectorGrupo = \Illuminate\Support\Facades\DB::table('sweb_salones')
            ->where('is_active', 1)
            ->where('director_id', $sessionUserId)
            ->exists();
    }
@endphp
<div class="wrap">
    <header class="head">
        <div class="head-left">
            <div class="head-left-text">
                <strong>Colegio</strong>
                <span>Windsor</span>
            </div>
        </div>
        <div class="head-mid">
            Usuario: <b>{{ session('admin_display_name', session('admin_email', 'admin@schoolnext.local')) }}</b>
        </div>
        <div class="head-right">
            <div>soporte@windsorschool.edu.co</div>
            <form method="POST" action="{{ route('logout') }}">
                @csrf
                <button type="submit" class="logout-btn">SALIR</button>
            </form>
        </div>
    </header>

    <nav class="menu">
        <a href="{{ route('admin.dashboard') }}" class="{{ request()->routeIs('admin.dashboard') ? 'active' : '' }}">Inicio</a>
        @if($currentRole === 'docentes')
            <a href="{{ route('admin.academia.asignacion.item', ['item' => 'estado-actual']) }}"
               class="{{ request()->routeIs('admin.academia.asignacion.item') ? 'active' : '' }}">
                Carga académica
            </a>
            @if($isDocenteDirectorGrupo)
                <a href="{{ route('admin.calificaciones.item', ['item' => 'curso-a-cargo']) }}"
                   class="{{ request()->routeIs('admin.calificaciones.item') && request()->route('item') === 'curso-a-cargo' ? 'active' : '' }}">
                    Dirección de grupo
                </a>
            @endif
        @endif
        @if($canGeneral)
            <div class="menu-item">
                <a href="{{ route('admin.section', ['section' => 'general']) }}"
                   class="menu-parent {{ request()->routeIs('admin.general.item') || request()->routeIs('admin.estudiantes.*') || request()->routeIs('admin.profesores.*') || request()->fullUrlIs('*section/general*') ? 'active' : '' }}">
                    General
                </a>
                <div class="submenu">
                    @foreach($generalMenu as $label => $url)
                        @if($label === 'Cursos ->')
                            <div class="submenu-item">
                                <a href="{{ $url }}">{{ $label }}</a>
                                <div class="submenu-level2">
                                    @foreach($generalCursosMenu as $item)
                                        <a href="{{ $item['url'] }}">{{ $item['label'] }}</a>
                                    @endforeach
                                </div>
                            </div>
                        @elseif($label === 'Grados ->')
                            <div class="submenu-item">
                                <a href="{{ $url }}">{{ $label }}</a>
                                <div class="submenu-level2">
                                    @foreach($generalGradosMenu as $item)
                                        <a href="{{ $item['url'] }}">{{ $item['label'] }}</a>
                                    @endforeach
                                </div>
                            </div>
                        @elseif($label === 'Grupos Familiares ->')
                            <div class="submenu-item">
                                <a href="{{ $url }}">{{ $label }}</a>
                                <div class="submenu-level2">
                                    @foreach($generalGruposMenu as $item)
                                        <a href="{{ $item['url'] }}">{{ $item['label'] }}</a>
                                    @endforeach
                                </div>
                            </div>
                        @else
                            <a href="{{ $url }}">{{ $label }}</a>
                        @endif
                    @endforeach
                </div>
            </div>
        @endif

        @foreach($menuBeforeAcademia as $label => $url)
            <a href="{{ $url }}" class="{{ url()->current() === $url ? 'active' : '' }}">{{ $label }}</a>
        @endforeach

        @if($canAcademia)
            <div class="menu-item">
                <a href="{{ route('admin.section', ['section' => 'academia']) }}"
                   class="menu-parent {{ request()->routeIs('admin.academia.*') || request()->fullUrlIs('*section/academia*') ? 'active' : '' }}">
                    Academia
                </a>
                <div class="submenu">
                    <div class="submenu-item">
                        <a href="{{ route('admin.academia.asignacion.item', ['item' => 'estado-actual']) }}">Asignación Académica -></a>
                        <div class="submenu-level2">
                            @foreach($academiaAsignacionMenu as $item)
                                <a href="{{ $item['url'] }}">{{ $item['label'] }}</a>
                            @endforeach
                        </div>
                    </div>
                    @foreach($academiaMenu as $item)
                        <a href="{{ $item['url'] }}">{{ $item['label'] }}</a>
                    @endforeach
                </div>
            </div>
        @endif

        @if($canCalificaciones)
            <div class="menu-item">
                <a href="{{ route('admin.section', ['section' => 'calificaciones']) }}"
                   class="menu-parent {{ request()->routeIs('admin.calificaciones.*') || request()->routeIs('admin.academia.asignacion.item') || request()->fullUrlIs('*section/calificaciones*') ? 'active' : '' }}">
                    Calificaciones
                </a>
                <div class="submenu">
                    @foreach($calificacionesMenu as $item)
                        <a href="{{ $item['url'] }}">{{ $item['label'] }}</a>
                    @endforeach
                </div>
            </div>
        @endif

        @if($canObservador && $currentRole === 'docentes')
            <a href="{{ route('admin.observador.observaciones.index') }}"
               class="{{ request()->routeIs('admin.observador.observaciones.*') ? 'active' : '' }}">
                Observaciones Generales
            </a>
            @if($isDocenteDirectorGrupo)
                <a href="{{ route('admin.observador.registro_academico.index') }}"
                   class="{{ request()->routeIs('admin.observador.registro_academico.*') ? 'active' : '' }}">
                    Registro Académico
                </a>
            @endif
        @elseif($canObservador)
            <div class="menu-item">
                <a href="{{ route('admin.observador.observaciones.index') }}"
                   class="menu-parent {{ request()->routeIs('admin.observador.*') ? 'active' : '' }}">
                    Observador
                </a>
                <div class="submenu">
                    <a href="{{ route('admin.observador.observaciones.index') }}">Observaciones Generales</a>
                    @if(in_array($currentRole, ['admin', 'superadmin', 'coordinadores'], true))
                        <a href="{{ route('admin.observador.registro_academico.index') }}">Registro Academico</a>
                    @endif
                </div>
            </div>
        @endif

        @foreach($menuAfterAcademia as $label => $url)
            <a href="{{ $url }}" class="{{ url()->current() === $url ? 'active' : '' }}">{{ $label }}</a>
        @endforeach
    </nav>

    <div class="subbar">
        <div>Rol: <strong>{{ $currentRoleLabel }}</strong></div>
        @if($currentRole !== 'docentes')
            <div class="years">
                Año académico:
                @foreach($academicYears as $year)
                    <a class="{{ (int)$year === $selectedYear ? 'active' : '' }}" href="{{ request()->fullUrlWithQuery(['annio' => $year]) }}">{{ $year }}</a>
                @endforeach
            </div>
        @endif
    </div>

    <main class="content">
        @yield('content')
    </main>
</div>
</body>
</html>
