<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="theme-color" content="#0a0a0f">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>{{ $title ?? 'Admin' }} | {{ gs('site_name') ?? 'Salieno' }}</title>

    @php
        $isSecure = systemRegistered();
        $isSelfAware = app(\App\Services\SystemIntegrityService::class)->monitor()['integral'];
    @endphp

    <link rel="preconnect" href="https://fonts.bunny.net">
    <link
        href="https://fonts.bunny.net/css?family=inter:100,200,300,400,500,600,700,800,900|jetbrains-mono:400,500,600,700"
        rel="stylesheet" media="print" onload="this.media='all'" />
    <noscript><link href="https://fonts.bunny.net/css?family=inter:100,200,300,400,500,600,700,800,900|jetbrains-mono:400,500,600,700" rel="stylesheet" /></noscript>

    <!-- Icons - Phosphor Icons (defer: non-blocking, loads after HTML parse) -->
    <script src="https://unpkg.com/@phosphor-icons/web@2.1.1" 
        integrity="sha384-cPFV+/abYd3INVFHPmSKpBmcnH+Q+bTZW7dv/EiuShUNPkHyFmRF8PsL7Ibfvunk" 
        crossorigin="anonymous" defer nonce="{{ csp_nonce() }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js" 
        integrity="sha384-BSxuMLxX+FCbTdYec3TbXlnMGEEM2QXTFdtDaveen71o+jswm2J36+xFqp8k4VHM" 
        crossorigin="anonymous" defer nonce="{{ csp_nonce() }}"></script>

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

<body x-data="{
        {{-- ADM-06: Sidebar state uses localStorage (NOT x-persist) because it must
             persist across browser sessions and full page reloads. x-persist only
             survives Livewire SPA navigations (wire:navigate). --}}
        sidebarOpen: localStorage.getItem('admin_sidebar_open') !== 'false',
        sidebarMobileOpen: false,
        touchStartX: 0,
        touchCurrentX: 0,
        toggleSidebar() {
            this.sidebarOpen = !this.sidebarOpen;
            localStorage.setItem('admin_sidebar_open', this.sidebarOpen);
        },
        toggleMobileSidebar() {
            this.sidebarMobileOpen = !this.sidebarMobileOpen;
            document.body.style.overflow = this.sidebarMobileOpen ? 'hidden' : '';
        },
        closeMobileSidebar() {
            this.sidebarMobileOpen = false;
            document.body.style.overflow = '';
        }
    }" @keydown.escape.window="closeMobileSidebar()" class="h-full bg-[#0a0a0f] font-sans antialiased">
    <div class="flex h-full">
        <!-- Mobile Sidebar Backdrop -->
        <div x-show="sidebarMobileOpen" x-transition:enter="transition-opacity ease-linear duration-300"
            x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
            x-transition:leave="transition-opacity ease-linear duration-300" x-transition:leave-start="opacity-100"
            x-transition:leave-end="opacity-0" @click="closeMobileSidebar()"
            class="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm lg:hidden"></div>

        <!-- Sidebar -->
        <x-admin.sidebar />

        <!-- Main Content Area -->
        <div class="flex flex-1 flex-col transition-all duration-300"
            :class="sidebarOpen ? 'lg:pl-[272px]' : 'lg:pl-[80px]'">
            <!-- Header -->
            <x-admin.header :title="$title ?? 'Dashboard'" />

            <!-- Page Content -->
            <main class="flex-1 overflow-y-auto overscroll-contain p-4 sm:p-6 lg:p-8">
                <div class="mx-auto max-w-[1600px]">
                    <!-- Breadcrumbs - Hidden on mobile, shown on tablet+ -->
                    @if(isset($breadcrumbs))
                        <nav class="mb-4 sm:mb-6 hidden sm:flex items-center gap-2 text-sm overflow-x-auto scrollbar-none"
                            aria-label="Breadcrumb">
                            <a href="{{ route('admin.dashboard') }}"
                                class="text-slate-500 transition-colors hover:text-indigo-400 shrink-0">
                                <i class="ph-duotone ph-house text-lg"></i>
                            </a>
                            {{ $breadcrumbs }}
                        </nav>
                    @endif

                    <!-- Page Header -->
                    @if(isset($header))
                        <div class="mb-4 sm:mb-6 lg:mb-8">
                            {{ $header }}
                        </div>
                    @endif

                    <!-- Main Slot -->
                    {{ $slot }}
                </div>
            </main>

            <!-- Footer - Simplified on mobile -->
            <footer class="border-t border-white/5 px-4 sm:px-6 py-3 sm:py-4 lg:px-8 pb-safe">
                <div
                    class="mx-auto flex max-w-[1600px] flex-col sm:flex-row items-center justify-between gap-2 sm:gap-4 text-xs sm:text-sm text-slate-500">
                    <p class="text-center sm:text-left">&copy; {{ date('Y') }} {{ gs('site_name') ?? 'Salieno' }}.</p>
                    <div class="flex items-center gap-3 sm:gap-6">
                        @php
                            // Lightweight health check — cached 60s to avoid per-request overhead
                            $health = cache()->remember('admin_health_status', 60, function () {
                                try {
                                    \DB::select('SELECT 1');
                                    $dbOk = true;
                                } catch (\Throwable $e) {
                                    $dbOk = false;
                                }
                                $cacheOk = cache()->put('_health_probe', true, 10) !== false;
                                $diskFree = disk_free_space(storage_path()) > 100 * 1024 * 1024; // > 100MB
                                if ($dbOk && $cacheOk && $diskFree) return 'ok';
                                if ($dbOk) return 'degraded';
                                return 'down';
                            });
                            $statusColor = match($health) {
                                'ok' => 'emerald',
                                'degraded' => 'amber',
                                default => 'rose',
                            };
                            $statusLabel = match($health) {
                                'ok' => __('All Systems Operational'),
                                'degraded' => __('Degraded Performance'),
                                default => __('System Issues Detected'),
                            };
                            $statusShort = match($health) {
                                'ok' => __('Online'),
                                'degraded' => __('Degraded'),
                                default => __('Issues'),
                            };
                        @endphp
                        <p class="flex items-center gap-1.5 sm:gap-2">
                            <span class="relative flex h-2 w-2">
                                <span
                                    class="absolute inline-flex h-full w-full animate-ping rounded-full bg-{{ $statusColor }}-400 opacity-75"></span>
                                <span class="relative inline-flex h-2 w-2 rounded-full bg-{{ $statusColor }}-500"></span>
                            </span>
                            <span class="hidden sm:inline">{{ $statusLabel }}</span>
                            <span class="sm:hidden">{{ $statusShort }}</span>
                        </p>
                        <span class="text-slate-600">v{{ config('app.version', '1.0.0') }}</span>
                    </div>
                </div>
            </footer>
        </div>
    </div>

    <!-- Toast Notifications -->
    <x-admin.toast x-persist="admin-toast" />

    @livewireScripts
    @livewireScriptConfig

    <!-- SPA Navigation Loading State Manager -->
    <script nonce="{{ csp_nonce() }}">
        document.addEventListener('alpine:init', () => {
            Alpine.store('navigation', {
                isNavigating: false,
                start() {
                    this.isNavigating = true;
                    document.body.classList.add('navigating');
                },
                end() {
                    this.isNavigating = false;
                    document.body.classList.remove('navigating');
                }
            });
        });

        // Listen for Livewire navigate events
        document.addEventListener('livewire:navigate', () => {
            if (Alpine.store('navigation')) {
                Alpine.store('navigation').start();
            }
        });

        document.addEventListener('livewire:navigated', () => {
            if (Alpine.store('navigation')) {
                Alpine.store('navigation').end();
            }
        });
    </script>

    <!-- Toast Helper -->
    <script nonce="{{ csp_nonce() }}">
        window.toast = function (options) {
            window.dispatchEvent(new CustomEvent('toast', { detail: options }));
        };

        // Keyboard shortcut for search (Cmd+K / Ctrl+K)
        document.addEventListener('keydown', function (e) {
            if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
                e.preventDefault();
                document.querySelector('input[type="search"]')?.focus();
            }
        });
    </script>

    <!-- Page-specific scripts -->
    @stack('scripts')

    <!-- Page Loader Overlay (controlled by body.navigating class) -->
    <div id="page-loader"><div class="loader-spinner"></div></div>
</body>

</html>