<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>{{ 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&display=swap" rel="stylesheet" />

        <link rel="manifest" href="/manifest.json">
        <meta name="theme-color" content="#2563eb">
        
        <!-- Scripts -->
        @vite(['resources/css/app.css', 'resources/js/app.js'])
        
        <script>
            if ('serviceWorker' in navigator) {
                window.addEventListener('load', function() {
                    navigator.serviceWorker.register('/sw.js').then(function(registration) {
                        console.log('ServiceWorker registration successful');
                    }, function(err) {
                        console.log('ServiceWorker registration failed: ', err);
                    });
                });
            }
        </script>
    </head>
    <body class="font-sans antialiased">
        <div class="min-h-screen bg-gray-100">
            @include('layouts.navigation')

            <!-- Toast Notifications -->
            <div x-data="{ 
                show: false, 
                message: '', 
                type: 'success',
                init() {
                    @if(session('success'))
                        this.showToast('{{ session('success') }}', 'success');
                    @endif
                    @if(session('error'))
                        this.showToast('{{ session('error') }}', 'error');
                    @endif
                },
                showToast(msg, type) {
                    this.message = msg;
                    this.type = type;
                    this.show = true;
                    setTimeout(() => { this.show = false }, 5000);
                }
            }" 
            x-show="show" 
            x-transition:enter="transition ease-out duration-300"
            x-transition:enter-start="opacity-0 transform translate-y-2"
            x-transition:enter-end="opacity-100 transform translate-y-0"
            x-transition:leave="transition ease-in duration-300"
            x-transition:leave-start="opacity-100 transform translate-y-0"
            x-transition:leave-end="opacity-0 transform translate-y-2"
            class="fixed bottom-5 right-5 z-50 p-4 rounded-lg shadow-xl text-white font-bold"
            :class="type === 'success' ? 'bg-green-600' : 'bg-red-600'"
            style="display: none;">
                <div class="flex items-center space-x-2">
                    <span x-text="type === 'success' ? '✅' : '❌'"></span>
                    <span x-text="message"></span>
                </div>
            </div>

            <!-- Page Loading Animation -->
            <div id="pageLoader" class="fixed inset-0 z-[100] flex items-center justify-center bg-white bg-opacity-90" style="display:none;">
                <div class="text-center">
                    <div class="inline-block relative" style="width:80px;height:50px;">
                        <!-- Truck body -->
                        <svg viewBox="0 0 80 50" class="w-20 h-12 animate-bounce" style="animation-duration:1.2s;">
                            <rect x="2" y="10" width="45" height="24" rx="3" fill="#4F46E5"/>
                            <path d="M47 16 L60 16 L66 28 L66 34 L47 34 Z" fill="#6366F1"/>
                            <path d="M49 17 L57 17 L62 26 L49 26 Z" fill="#C7D2FE"/>
                            <text x="24" y="26" font-family="Arial" font-size="8" font-weight="bold" fill="white" text-anchor="middle">VMS</text>
                        </svg>
                        <!-- Wheels with spin -->
                        <div class="absolute bottom-0 left-3">
                            <div class="w-5 h-5 border-3 border-indigo-800 border-t-indigo-300 rounded-full animate-spin"></div>
                        </div>
                        <div class="absolute bottom-0 right-3">
                            <div class="w-5 h-5 border-3 border-indigo-800 border-t-indigo-300 rounded-full animate-spin"></div>
                        </div>
                    </div>
                    <p class="text-sm text-gray-500 mt-3 font-medium animate-pulse">Loading...</p>
                </div>
            </div>

            <!-- Global Loading Spinner (form submits) -->
            <div x-data="{ loading: false }" 
                 x-show="loading" 
                 @loading.window="loading = $event.detail"
                 class="fixed inset-0 z-[100] flex items-center justify-center bg-white bg-opacity-75"
                 style="display: none;">
                <div class="text-center">
                    <div class="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mx-auto"></div>
                    <p class="text-sm text-gray-500 mt-3 font-medium">Saving...</p>
                </div>
            </div>

            <!-- PWA Offline Indicator -->
            <div x-data="{ online: navigator.onLine }" 
                 @online.window="online = true" 
                 @offline.window="online = false" 
                 x-show="!online"
                 class="bg-red-600 text-white text-center py-1 text-xs font-bold sticky top-0 z-[60]"
                 style="display: none;">
                📡 You are currently offline. Some features may not work.
            </div>

            <!-- Page Heading -->
            @isset($header)
                <header class="bg-white shadow">
                    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8 flex items-center gap-4">
                        @if(!request()->routeIs('dashboard') && !request()->routeIs('trips.my'))
                        <button onclick="window.history.back()" class="text-gray-500 hover:text-blue-600 bg-gray-100 hover:bg-blue-50 rounded-full p-2 transition focus:outline-none">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                        </button>
                        @endif
                        <div class="flex-1">
                            {{ $header }}
                        </div>
                    </div>
                </header>
            @endisset

            <!-- Page Content -->
            <main>
                {{ $slot }}
            </main>
        </div>

        <script>
            // Global Form Loading Spinner
            document.addEventListener('submit', function(e) {
                if (!e.target.classList.contains('no-loader')) {
                    window.dispatchEvent(new CustomEvent('loading', { detail: true }));
                }
            });

            // Page Navigation Loader (truck animation)
            document.addEventListener('click', function(e) {
                const link = e.target.closest('a');
                if (link && link.href && !link.href.startsWith('javascript') && !link.hasAttribute('download') && !e.ctrlKey && !e.metaKey && link.target !== '_blank') {
                    const url = new URL(link.href);
                    if (url.origin === window.location.origin && url.pathname !== window.location.pathname) {
                        document.getElementById('pageLoader').style.display = 'flex';
                    }
                }
            });
            window.addEventListener('pageshow', function() {
                document.getElementById('pageLoader').style.display = 'none';
            });

            // Service Worker Registration
            if ('serviceWorker' in navigator) {
                window.addEventListener('load', () => {
                    navigator.serviceWorker.register('/sw.js').then(registration => {
                        registration.onupdatefound = () => {
                            const installingWorker = registration.installing;
                            installingWorker.onstatechange = () => {
                                if (installingWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                    if (confirm('New update available! Reload to apply?')) {
                                        window.location.reload();
                                    }
                                }
                            };
                        };
                    });
                });
            }
        </script>
    </body>
</html>
