<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title', 'Panel Admin') - WebSoft Solutions</title>
    <meta name="description" content="Panel de administración WebSoft Solutions">
    <link rel="icon"
        href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚙️</text></svg>">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="{{ asset('css/admin.css') }}">
    @yield('styles')
</head>

<body>

    {{-- ======================== SIDEBAR ======================== --}}
    <aside class="admin-sidebar" id="adminSidebar">

        {{-- Brand --}}
        <div class="sidebar-brand">
            <div class="sidebar-logo">W</div>
            <div>
                <div class="sidebar-brand-name">WebSoft Solutions</div>
                <div class="sidebar-brand-sub">Panel Administrativo</div>
            </div>
        </div>

        {{-- Admin info --}}
        <div class="sidebar-admin">
            <div class="sidebar-admin-avatar">
                {{ strtoupper(substr(session('admin_nombre', 'A'), 0, 1)) }}
            </div>
            <div style="min-width:0;">
                <div class="sidebar-admin-name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                    {{ session('admin_nombre', 'Administrador') }}
                </div>
                <div class="sidebar-admin-role">Administrador</div>
            </div>
        </div>

        {{-- Navigation --}}
        <nav class="sidebar-nav">

            <div class="sidebar-nav-section">Principal</div>
            <a href="{{ route('admin.dashboard') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.dashboard') ? 'active' : '' }}">
                <i class="bi bi-speedometer2"></i> Dashboard
            </a>

            <div class="sidebar-nav-section">Contenido</div>
            <a href="{{ route('admin.sliders.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.sliders.*') ? 'active' : '' }}">
                <i class="bi bi-images"></i> Sliders / Carrusel
            </a>
            <a href="{{ route('admin.noticias.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.noticias.*') ? 'active' : '' }}">
                <i class="bi bi-newspaper"></i> Noticias / Comunicados
            </a>
            <a href="{{ route('admin.ticker.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.ticker.*') ? 'active' : '' }}">
                <i class="bi bi-megaphone-fill"></i> News Ticker
            </a>

            <div class="sidebar-nav-section">Servicios</div>
            <a href="{{ route('admin.servicios.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.servicios.*') ? 'active' : '' }}">
                <i class="bi bi-grid-fill"></i> Nuestros Servicios
            </a>

            <div class="sidebar-nav-section">Reconocimientos</div>
            <a href="{{ route('admin.premios.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.premios.*') ? 'active' : '' }}">
                <i class="bi bi-trophy-fill"></i> Premios
            </a>

            <div class="sidebar-nav-section">Olimpiadas</div>
            <a href="{{ route('admin.concursos.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.concursos.*') ? 'active' : '' }}">
                <i class="bi bi-award-fill"></i> Concursos / Resultados
            </a>

            <div class="sidebar-nav-section">Comunidad</div>
            <a href="{{ route('admin.testimonios.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.testimonios.*') ? 'active' : '' }}">
                <i class="bi bi-people-fill"></i> Testimonios
            </a>

            <div class="sidebar-nav-section">Estadísticas</div>
            <a href="{{ route('admin.estadisticas.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.estadisticas.*') ? 'active' : '' }}">
                <i class="bi bi-bar-chart-fill"></i> Estadísticas
            </a>

            <div class="sidebar-nav-section">Sitio Web</div>
            <a href="{{ route('admin.menu-items.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.menu-items.*') ? 'active' : '' }}">
                <i class="bi bi-list-ul"></i> Menú de Navegación
            </a>
            <a href="{{ route('admin.paginas.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.paginas.*') ? 'active' : '' }}">
                <i class="bi bi-file-earmark-text-fill"></i> Páginas
            </a>

            <div class="sidebar-nav-section">Configuración</div>
            <a href="{{ route('admin.configuracion.index') }}"
                class="sidebar-nav-item {{ request()->routeIs('admin.configuracion.*') ? 'active' : '' }}">
                <i class="bi bi-gear-fill"></i> Configuración
            </a>

        </nav>

        {{-- Footer sidebar --}}
        <div class="sidebar-footer">
            <a href="#" class="sidebar-nav-item" id="btnLogoutSidebar" style="color:rgba(239,68,68,.8);"
                data-href="{{ route('admin.logout') }}">
                <i class="bi bi-box-arrow-right"></i> Cerrar Sesión
            </a>
        </div>
    </aside>

    {{-- Overlay (clic para cerrar sidebar en mobile) --}}
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    {{-- ======================== MAIN ======================== --}}
    <div class="admin-main" id="adminMain">

        {{-- Topbar --}}
        <header class="admin-topbar">
            <div class="topbar-left">
                {{-- Hamburger (solo mobile) --}}
                <button class="topbar-hamburger" id="topbarHamburger" aria-label="Abrir menú">
                    <i class="bi bi-list" id="hamburgerIcon"></i>
                </button>

                <div class="topbar-page-title">
                    <i class="bi bi-@yield('icon', 'grid')"></i>
                    <span>@yield('page-title', 'Dashboard')</span>
                </div>
            </div>

            <div class="topbar-actions">
                <a href="{{ route('home') }}" class="topbar-site-link" target="_blank" rel="noopener"
                    title="Ver Sitio Web">
                    <i class="bi bi-box-arrow-up-right"></i>
                    <span class="label">Ver Sitio</span>
                </a>
                <a href="#" class="topbar-logout" id="btnLogoutTopbar" data-href="{{ route('admin.logout') }}"
                    title="Cerrar sesión">
                    <i class="bi bi-box-arrow-right"></i>
                    <span class="label">Salir</span>
                </a>
            </div>
        </header>

        {{-- Content --}}
        <main class="admin-content">

            {{-- Flash messages (procesados por SweetAlert2 en el script de abajo) --}}
            @if(session('success'))
                <div id="swal-success" data-msg="{{ session('success') }}" hidden></div>
            @endif
            @if(session('error'))
                <div id="swal-error" data-msg="{{ session('error') }}" hidden></div>
            @endif
            @if(session('warning'))
                <div id="swal-warning" data-msg="{{ session('warning') }}" hidden></div>
            @endif
            @if(session('info'))
                <div id="swal-info" data-msg="{{ session('info') }}" hidden></div>
            @endif
            @if($errors->any())
                <div id="swal-errors" data-errors="{{ json_encode($errors->all()) }}" hidden></div>
            @endif

            @yield('content')
        </main>
    </div>

    {{-- ======================== SCRIPTS ======================== --}}
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        (function () {

            /* ── Sidebar toggle ─────────────────────────────────── */
            const sidebar = document.getElementById('adminSidebar');
            const overlay = document.getElementById('sidebarOverlay');
            const hamburger = document.getElementById('topbarHamburger');
            const icon = document.getElementById('hamburgerIcon');

            function openSidebar() { sidebar.classList.add('open'); overlay.classList.add('active'); icon.className = 'bi bi-x-lg'; document.body.style.overflow = 'hidden'; }
            function closeSidebar() { sidebar.classList.remove('open'); overlay.classList.remove('active'); icon.className = 'bi bi-list'; document.body.style.overflow = ''; }
            function toggleSidebar() { sidebar.classList.contains('open') ? closeSidebar() : openSidebar(); }

            if (hamburger) hamburger.addEventListener('click', toggleSidebar);
            if (overlay) overlay.addEventListener('click', closeSidebar);
            document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeSidebar(); });
            sidebar.querySelectorAll('.sidebar-nav-item').forEach(function (link) {
                link.addEventListener('click', function () { if (window.innerWidth <= 900) closeSidebar(); });
            });
            window.addEventListener('resize', function () {
                if (window.innerWidth > 900) { closeSidebar(); document.body.style.overflow = ''; }
            });

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

            /* ── Flash messages via SweetAlert2 ─────────────────── */
            var elSuccess = document.getElementById('swal-success');
            var elError = document.getElementById('swal-error');
            var elWarning = document.getElementById('swal-warning');
            var elInfo = document.getElementById('swal-info');
            var elErrors = document.getElementById('swal-errors');

            if (elSuccess) Toast.fire({ icon: 'success', title: elSuccess.dataset.msg });
            if (elError) Toast.fire({ icon: 'error', title: elError.dataset.msg, timer: 6000 });
            if (elWarning) Toast.fire({ icon: 'warning', title: elWarning.dataset.msg, timer: 5000 });
            if (elInfo) Toast.fire({ icon: 'info', title: elInfo.dataset.msg });

            if (elErrors) {
                var errs = JSON.parse(elErrors.dataset.errors || '[]');
                if (errs.length) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Errores en el formulario',
                        html: '<ul style="text-align:left;padding-left:1.2rem;margin:0;">' +
                            errs.map(function (e) { return '<li style="margin-bottom:.3rem;">' + e + '</li>'; }).join('') +
                            '</ul>',
                        confirmButtonColor: '#ef4444',
                        confirmButtonText: 'Entendido',
                        customClass: { popup: 'swal-admin-popup' }
                    });
                }
            }

            /* ── Confirmar Logout ───────────────────────────────── */
            function confirmLogout(href) {
                Swal.fire({
                    title: '¿Cerrar sesión?',
                    text: 'Se cerrará tu sesión de administrador.',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#ef4444',
                    cancelButtonColor: '#64748b',
                    confirmButtonText: '<i class="bi bi-box-arrow-right"></i> Sí, cerrar sesión',
                    cancelButtonText: 'Cancelar',
                    customClass: { popup: 'swal-admin-popup' }
                }).then(function (result) {
                    if (result.isConfirmed) window.location.href = href;
                });
            }

            var logoutSidebar = document.getElementById('btnLogoutSidebar');
            var logoutTopbar = document.getElementById('btnLogoutTopbar');
            if (logoutSidebar) logoutSidebar.addEventListener('click', function (e) { e.preventDefault(); confirmLogout(this.dataset.href); });
            if (logoutTopbar) logoutTopbar.addEventListener('click', function (e) { e.preventDefault(); confirmLogout(this.dataset.href); });

            /* ── Confirmar eliminación (formularios .form-delete) ── */
            document.addEventListener('submit', function (e) {
                var form = e.target;
                if (form.classList.contains('form-delete')) {
                    e.preventDefault();
                    var msg = form.dataset.confirmMsg || '¿Eliminar este registro? Esta acción no se puede deshacer.';
                    var name = form.dataset.itemName || '';
                    Swal.fire({
                        title: '¿Eliminar' + (name ? ' "' + name + '"' : '') + '?',
                        text: msg,
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#ef4444',
                        cancelButtonColor: '#64748b',
                        confirmButtonText: '<i class="bi bi-trash-fill"></i> Sí, eliminar',
                        cancelButtonText: 'Cancelar',
                        customClass: { popup: 'swal-admin-popup' }
                    }).then(function (result) {
                        if (result.isConfirmed) form.submit();
                    });
                }
            });

            /* ── Exponer Toast globalmente ───────────────────────── */
            window.AdminToast = Toast;

        })();
    </script>

    @yield('scripts')
</body>

</html>