<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}"
      x-data="{ darkMode: localStorage.getItem('darkMode') === 'true' || (!('darkMode' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) }"
      x-init="$watch('darkMode', val => localStorage.setItem('darkMode', val))"
      :class="{ 'dark': darkMode }">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>{{ \App\Models\Setting::get('system_name', config('app.name', 'Laravel')) }}</title>

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

        <!-- SweetAlert2 -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

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

        <!-- UX Styles -->
        <style>
            .page-fade-in { animation: fadeIn 0.4s ease-out forwards; }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(4px); }
                to { opacity: 1; transform: translateY(0); }
            }
            /* SweetAlert2 custom theme */
            .swal2-popup { border-radius: 1.25rem !important; font-family: 'Figtree', sans-serif !important; }
            .swal2-title { font-weight: 900 !important; color: #0f172a; }
            .swal2-html-container { color: #64748b !important; font-size: 0.95rem !important; }
            .dark .swal2-popup { background: #1e293b !important; }
            .dark .swal2-title { color: #f1f5f9 !important; }
            .dark .swal2-html-container { color: #94a3b8 !important; }
        </style>
    </head>
    <body class="font-sans antialiased text-slate-800 dark:text-slate-200 bg-slate-50 dark:bg-slate-900 transition-colors duration-200 selection:bg-indigo-500 selection:text-white">
        <div class="min-h-screen">
            @include('layouts.navigation')

            <!-- Page Heading -->
            @isset($header)
                <header class="bg-white/80 dark:bg-slate-800/80 backdrop-blur-md shadow-sm transition-colors duration-200 sticky top-0 z-30 border-b border-slate-200 dark:border-slate-700">
                    <div class="max-w-7xl mx-auto py-5 px-4 sm:px-6 lg:px-8">
                        {{ $header }}
                    </div>
                </header>
            @endisset

            <!-- Page Content -->
            <main class="page-fade-in">
                {{ $slot }}
            </main>
        </div>

        <!-- SweetAlert2 JS (global) -->
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

        <script>
            // ─── Toast Global Config ───────────────────────────────────────────
            const SwalToast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3500,
                timerProgressBar: true,
                customClass: {
                    popup: 'rounded-2xl shadow-xl',
                    timerProgressBar: 'bg-current opacity-30',
                },
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer);
                    toast.addEventListener('mouseleave', Swal.resumeTimer);
                }
            });

            // ─── Auto-show flash messages from server session ──────────────────
            @if(session('success'))
                SwalToast.fire({ icon: 'success', title: @json(session('success')) });
            @endif
            @if(session('error'))
                SwalToast.fire({ icon: 'error', title: @json(session('error')), timer: 5000 });
            @endif
            @if(session('warning'))
                SwalToast.fire({ icon: 'warning', title: @json(session('warning')), timer: 4500 });
            @endif
            @if(session('info'))
                SwalToast.fire({ icon: 'info', title: @json(session('info')) });
            @endif

            // ─── Global Delete Confirmation ────────────────────────────────────
            function swalDelete(url, token, title = '¿Eliminar este registro?', text = 'Esta acción no se puede deshacer.') {
                Swal.fire({
                    title: title,
                    text: text,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ef4444',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Sí, eliminar',
                    cancelButtonText: 'Cancelar',
                    reverseButtons: true,
                    focusCancel: true,
                    customClass: { popup: 'rounded-2xl shadow-2xl' }
                }).then((result) => {
                    if (result.isConfirmed) {
                        const form = document.createElement('form');
                        form.method = 'POST';
                        form.action = url;
                        form.innerHTML = `<input type="hidden" name="_token" value="${token}"><input type="hidden" name="_method" value="DELETE">`;
                        document.body.appendChild(form);
                        form.submit();
                    }
                });
            }

            // ─── Global Confirm Action (for non-delete actions) ────────────────
            function swalConfirm(formId, title = '¿Confirmar acción?', text = '', icon = 'question') {
                Swal.fire({
                    title: title,
                    text: text,
                    icon: icon,
                    showCancelButton: true,
                    confirmButtonColor: '#4f46e5',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Confirmar',
                    cancelButtonText: 'Cancelar',
                    reverseButtons: true,
                    customClass: { popup: 'rounded-2xl shadow-2xl' }
                }).then((result) => {
                    if (result.isConfirmed) {
                        document.getElementById(formId).submit();
                    }
                });
            }
        </script>

        @stack('scripts')
    </body>
</html>
