<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@yield('title', 'Scalar Admin')</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1Up41JQbM6+Zef7hM8Ql7nAJl3WDAg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <script src="https://unpkg.com/alpinejs@3.14.1/dist/cdn.min.js" defer></script>

    @php
        $viteManifest = public_path('build/manifest.json');
        $publicCss = public_path('css/app.css');
        $publicJs = public_path('js/app.js');
    @endphp

    @if (file_exists($viteManifest))
        @vite(['resources/css/app.css', 'resources/js/app.js'])
    @else
        @if (file_exists($publicCss))
            <link rel="stylesheet" href="{{ asset('css/app.css') }}?v={{ filemtime($publicCss) }}">
        @endif
        @if (file_exists($publicJs))
            <script src="{{ asset('js/app.js') }}?v={{ filemtime($publicJs) }}" defer></script>
        @endif
    @endif
    @stack('styles')

    <style>
        :root {
            --sidebar-width: 260px;
            --sidebar-collapsed: 84px;
            --sidebar-bg: #111827;
            --sidebar-text: #d1d5db;
            --sidebar-text-active: #fff;
            --sidebar-accent: #38bdf8;
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #f4f6fb;
            color: #1f2937;
        }

        .app-wrapper {
            min-height: 100vh;
            display: flex;
            background: linear-gradient(135deg, rgba(17, 24, 39, 0.04), rgba(99, 102, 241, 0.06));
        }

        .sidebar {
            width: var(--sidebar-width);
            background: var(--sidebar-bg);
            color: var(--sidebar-text);
            display: flex;
            flex-direction: column;
            transition: width 0.25s ease;
            position: relative;
            z-index: 1030;
        }

        .sidebar.collapsed {
            width: var(--sidebar-collapsed);
        }

        .sidebar .brand {
            padding: 1.25rem 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .sidebar .brand .logo {
            width: 42px;
            height: 42px;
            border-radius: 14px;
            display: grid;
            place-items: center;
            background: linear-gradient(135deg, #38bdf8, #6366f1);
            color: #fff;
        }

        .sidebar .brand .text {
            font-weight: 600;
            font-size: 1.05rem;
        }

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

        .sidebar-nav ul {
            list-style: none;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            gap: 0.35rem;
        }

        .sidebar-nav .nav-label {
            font-size: 0.7rem;
            letter-spacing: 0.1em;
            text-transform: uppercase;
            color: rgba(209, 213, 219, 0.5);
            padding: 0.75rem 1rem 0.25rem;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 0.85rem;
            padding: 0.65rem 0.95rem;
            border-radius: 0.65rem;
            color: inherit;
            text-decoration: none;
            transition: background 0.2s ease, color 0.2s ease;
        }

        .sidebar-nav a .icon {
            width: 1.9rem;
            display: grid;
            place-items: center;
            font-size: 1.1rem;
        }

        .sidebar-nav a:hover {
            background: rgba(59, 130, 246, 0.14);
            color: var(--sidebar-text-active);
        }

        .sidebar-nav a.active {
            background: linear-gradient(135deg, rgba(56, 189, 248, 0.18), rgba(99, 102, 241, 0.28));
            color: var(--sidebar-text-active);
            box-shadow: inset 0 0 0 1px rgba(129, 140, 248, 0.35);
        }

        .main-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .topbar {
            height: 64px;
            background: rgba(255, 255, 255, 0.92);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid rgba(148, 163, 184, 0.2);
            padding: 0 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 1rem;
        }

        .topbar .search {
            max-width: 360px;
            flex: 1;
            position: relative;
        }

        .topbar .search input {
            width: 100%;
            border-radius: 999px;
            border: 1px solid rgba(148, 163, 184, 0.4);
            padding: 0.55rem 0.95rem 0.55rem 2.6rem;
            background: rgba(241, 245, 249, 0.6);
        }

        .topbar .search i {
            position: absolute;
            top: 50%;
            left: 1rem;
            transform: translateY(-50%);
            color: #6b7280;
        }

        .topbar-actions {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .avatar {
            width: 38px;
            height: 38px;
            border-radius: 50%;
            background: linear-gradient(135deg, #6366f1, #8b5cf6);
            color: #fff;
            display: grid;
            place-items: center;
            font-weight: 600;
        }

        .content-wrapper {
            flex: 1;
            padding: 1.5rem 1.5rem 2rem;
        }

        footer.admin-footer {
            background: #0f172a;
            color: #94a3b8;
            font-size: 0.85rem;
            padding: 0.85rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .icon-circle {
            width: 44px;
            height: 44px;
            border-radius: 14px;
            display: grid;
            place-items: center;
            font-size: 1.1rem;
        }

        .icon-circle.xl {
            width: 66px;
            height: 66px;
            font-size: 1.35rem;
        }

        .sidebar.collapsed .nav-label,
        .sidebar.collapsed .brand .text,
        .sidebar.collapsed .nav-text {
            display: none;
        }

        .sidebar.collapsed .sidebar-nav a {
            justify-content: center;
        }

        @media (max-width: 992px) {
            .app-wrapper {
                flex-direction: column;
            }

            .sidebar {
                position: fixed;
                inset: 0 40% 0 0;
                transform: translateX(-100%);
                width: min(320px, 75vw);
                box-shadow: 8px 0 20px rgba(15, 23, 42, 0.35);
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .sidebar-canvas {
                display: none;
                position: fixed;
                inset: 0;
                background: rgba(15, 23, 42, 0.45);
                z-index: 1025;
            }

            .sidebar-canvas.show {
                display: block;
            }

            .main-panel {
                min-height: 100vh;
            }

            .topbar {
                padding: 0 1rem;
            }

            .topbar .search {
                display: none;
            }
        }
    </style>
</head>
<body>
@php
    $usuarioAutenticado = auth()->user();
    $menuItems = [
        ['label' => 'Dashboard', 'icon' => 'fa-house-chimney', 'route' => 'admin.dashboard'],
        ['label' => 'Usuarios', 'icon' => 'fa-users', 'route' => 'admin.usuarios'],
        ['label' => 'ScaWatts', 'icon' => 'fa-solar-panel', 'route' => 'admin.scawatts'],
        ['label' => 'Marketplace', 'icon' => 'fa-store', 'route' => 'admin.marketplace'],
        ['label' => 'Granjas', 'icon' => 'fa-seedling', 'route' => 'admin.granjas'],
        ['label' => 'Transacciones', 'icon' => 'fa-coins', 'route' => 'admin.transacciones'],
        ['label' => 'Notificaciones', 'icon' => 'fa-bell', 'route' => 'admin.notificaciones'],
        ['label' => 'Mensajes', 'icon' => 'fa-inbox', 'route' => 'admin.mensajes'],
        ['label' => 'Correos', 'icon' => 'fa-envelope-open-text', 'route' => 'admin.correos'],
        ['label' => 'Monitor', 'icon' => 'fa-wave-square', 'route' => 'admin.monitor'],
    ];
    $inicialesUsuario = $usuarioAutenticado
        ? collect(explode(' ', trim($usuarioAutenticado->nombre ?? $usuarioAutenticado->email)))
            ->filter()
            ->map(fn ($part) => strtoupper(substr($part, 0, 1)))
            ->take(2)
            ->implode('')
        : Str::of(config('app.name', 'SA'))->upper()->substr(0, 2);
    $nombreUsuario = $usuarioAutenticado?->nombre ?? $usuarioAutenticado?->email ?? 'Master';
@endphp

<div x-data="{ sidebarOpen: false, sidebarCollapsed: false, toggleMobile() { this.sidebarOpen = !this.sidebarOpen; }, toggleDesktop() { this.sidebarCollapsed = !this.sidebarCollapsed; } }" class="app-wrapper">
    <div class="sidebar-canvas" :class="{'show': sidebarOpen}" @click="sidebarOpen = false"></div>
    <aside class="sidebar" :class="{'collapsed': sidebarCollapsed, 'mobile-open': sidebarOpen}">
        <div class="brand">
            <div class="logo"><i class="fas fa-bolt"></i></div>
            <div class="text">Scalar Admin</div>
        </div>
        <nav class="sidebar-nav">
            <div class="nav-label">Panel maestro</div>
            <ul>
                @foreach($menuItems as $item)
                    <li>
                        <a href="{{ route($item['route']) }}" class="{{ request()->routeIs($item['route']) ? 'active' : '' }}" @click="sidebarOpen = false">
                            <span class="icon"><i class="fas {{ $item['icon'] }}"></i></span>
                            <span class="nav-text">{{ $item['label'] }}</span>
                        </a>
                    </li>
                @endforeach
            </ul>
        </nav>
    </aside>

    <div class="main-panel">
        <header class="topbar">
            <div class="d-flex align-items-center gap-2">
                <button type="button" class="btn btn-outline-secondary btn-sm d-lg-none" @click="toggleMobile()">
                    <i class="fas" :class="sidebarOpen ? 'fa-times' : 'fa-bars'"></i>
                </button>
                <button type="button" class="btn btn-outline-secondary btn-sm d-none d-lg-inline-flex" @click="toggleDesktop()">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="search d-none d-md-block">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Buscar módulo, usuario o ScaWatt" autocomplete="off">
                </div>
            </div>
            <div class="topbar-actions">
                <a href="{{ route('admin.monitor') }}" class="btn btn-sm btn-primary d-none d-sm-inline-flex">
                    <i class="fas fa-wave-square me-1"></i> Monitor
                </a>
                @auth
                    <span class="text-muted d-none d-md-inline">{{ $nombreUsuario }}</span>
                    <form method="POST" action="{{ route('logout') }}" class="d-inline">
                        @csrf
                        <button type="submit" class="btn btn-sm btn-outline-light">
                            <i class="fas fa-arrow-right-from-bracket"></i>
                        </button>
                    </form>
                @endauth
                <div class="avatar" title="{{ $nombreUsuario }}">
                    {{ $inicialesUsuario }}
                </div>
            </div>
        </header>

        <main class="content-wrapper">
            @hasSection('page-title')
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-3">
                    <div>
                        <h1 class="h4 mb-1">@yield('page-title')</h1>
                        @hasSection('page-subtitle')
                            <p class="text-muted mb-0">@yield('page-subtitle')</p>
                        @endif
                    </div>
                    <div>@yield('page-actions')</div>
                </div>
            @endif

            @if (session('status'))
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-circle-check me-2"></i>{{ session('status') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            @endif

            @if (session('error'))
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-triangle-exclamation me-2"></i>{{ session('error') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            @endif

            @if (session('generated_password'))
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <i class="fas fa-key me-2"></i>
                    Credenciales temporales generadas: <strong>{{ session('generated_password') }}</strong>. Comunica esta contraseña al usuario y solicita que la cambie en su próximo inicio de sesión.
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            @endif

            @if ($errors->any())
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-list-check me-2"></i>Revisa los siguientes campos:
                    <ul class="mb-0 mt-2 ps-3">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            @endif

            @yield('content')
        </main>

        <footer class="admin-footer">
            <span>&copy; {{ date('Y') }} Scalar Energía Renovable · Control maestro del ecosistema ScaWatt</span>
            <span><i class="fas fa-shield-alt me-1"></i> Sesión administrativa</span>
        </footer>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
@stack('scripts')
@yield('scripts')
</body>
</html>
