<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    @php
        $appName = config('settings.app_name', 'Innovaxcess Attendance');
        $favicon = config('settings.favicon');
        $logo = config('settings.logo');
    @endphp

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <!-- CRITICAL CACHE CONTROL META TAGS -->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    
    <!-- VERSION META TAG FOR CACHE BUSTING -->
    <meta name="version" content="{{ config('app.version', '1.0.0') }}-{{ time() }}">

    <title>{{ $pageTitle ?? 'Dashboard' }} - {{ $appName }}</title>

    @if($favicon)
    <link rel="icon" href="{{ Storage::url($favicon) }}?v={{ time() }}" type="image/x-icon">
    @else
    <link rel="icon" href="/favicon.ico?v={{ time() }}" type="image/x-icon">
    @endif

    <!-- PWA Meta Tags -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="Innovaxcess">
    <link rel="apple-touch-icon" href="{{ $favicon ? Storage::url($favicon) : '/images/icon-192x192.png' }}?v={{ time() }}">

    <!-- Manifest with version -->
    <link rel="manifest" href="/manifest.json?v={{ time() }}">

    <!-- Theme Color -->
    <meta name="theme-color" content="#3b82f6">
    <meta name="msapplication-TileColor" content="#3b82f6">

    <!-- Vite Assets with Cache Busting -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
    
    <!-- Fallback for CDN assets when Vite is not in dev mode -->
    @production
        <!-- Tailwind CSS via CDN (with version) -->
        <script src="https://cdn.tailwindcss.com/3.3.0"></script>
        <script>
            tailwind.config = {
                theme: {
                    extend: {
                        colors: {
                            primary: {
                                50: '#eff6ff',
                                100: '#dbeafe',
                                200: '#bfdbfe',
                                300: '#93c5fd',
                                400: '#60a5fa',
                                500: '#3b82f6',
                                600: '#2563eb',
                                700: '#1d4ed8',
                                800: '#1e40af',
                                900: '#1e3a8a',
                            }
                        }
                    }
                }
            }
        </script>
        
        <!-- Font Awesome with version -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" 
              integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" 
              crossorigin="anonymous" referrerpolicy="no-referrer">
        
        <!-- Alpine.js with version -->
        <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.0/dist/cdn.min.js" 
                integrity="sha384-1+5BqT8CSUme0jKpP/VhHkLp8t8c5jeS9lYFkL9SGlPhK21zKd0NlTk8y6tPY8R6" 
                crossorigin="anonymous"></script>
    @else
        <!-- In development, Vite will handle these -->
        <style>
            /* Temporary styles while Vite loads */
            body { visibility: hidden; }
        </style>
    @endproduction

    <!-- Custom Styles with version -->
    <style id="custom-styles">
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .sidebar-transition {
            transition: all 0.3s ease-in-out;
        }
        .btn-primary {
            background-color: rgb(37 99 235);
            color: white;
            font-weight: 500;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            transition: all 0.2s ease-in-out;
        }
        .btn-primary:hover {
            background-color: rgb(29 78 216);
            transform: scale(1.05);
        }
        .btn-secondary {
            background-color: rgb(75 85 99);
            color: white;
            font-weight: 500;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            transition: all 0.2s;
        }
        .btn-secondary:hover {
            background-color: rgb(55 65 81);
        }
        .card {
            background-color: white;
            border-radius: 0.75rem;
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            transition: all 0.3s ease-in-out;
        }
        .card:hover {
            box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
        }
        .form-input {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            outline: none;
            transition: all 0.2s;
        }
        .form-input:focus {
            ring: 2px solid rgb(59 130 246);
            border-color: transparent;
        }
        .form-select {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            outline: none;
            background-color: white;
        }
        .form-select:focus {
            ring: 2px solid rgb(59 130 246);
            border-color: transparent;
        }
    </style>
</head>
<body class="font-sans antialiased bg-gray-50">
    <div class="min-h-screen">
        <!-- Navigation -->
        @if (Route::has('login'))
            <nav class="bg-white shadow-sm border-b border-gray-200">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="flex justify-between h-16">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 flex items-center space-x-3">
                                @if($logo)
                                <div class="w-10 h-10 rounded-lg flex items-center justify-center overflow-hidden">
                                    <img src="{{ Storage::url($logo) }}?v={{ time() }}" 
                                         alt="{{ $appName }}" 
                                         class="max-w-full max-h-full">
                                </div>
                                @else
                                <div class="w-10 h-10 bg-gradient-to-r from-primary-600 to-purple-600 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-stethoscope text-white text-lg"></i>
                                </div>
                                @endif
                                <span class="text-xl font-bold text-gray-900">{{ $appName }}</span>
                            </div>
                        </div>

                        <div class="flex items-center space-x-4">
                            @auth
                                <a href="{{ url('/dashboard') }}" class="text-gray-700 hover:text-primary-600 font-medium transition duration-200">
                                    <i class="fas fa-tachometer-alt mr-1"></i>Dashboard
                                </a>
                            @else
                                <a href="{{ route('login') }}" class="text-gray-700 hover:text-primary-600 font-medium transition duration-200">
                                    <i class="fas fa-sign-in-alt mr-1"></i>Log in
                                </a>

                                @if (Route::has('register'))
                                    <a href="{{ route('register') }}" class="text-gray-700 hover:text-primary-600 font-medium transition duration-200">
                                        <i class="fas fa-user-plus mr-1"></i>Register
                                    </a>
                                @endif
                            @endauth
                        </div>
                    </div>
                </div>
            </nav>
        @endif

        <!-- Page Content -->
        <main class="flex-1">
            {{ $slot }}
        </main>
    </div>

    <!-- Cache Control Script -->
    <script>
        // Set cache control in localStorage
        localStorage.setItem('app_version', '{{ config("app.version", "1.0.0") }}-{{ time() }}');
        
        // Check for updates on page load
        window.addEventListener('load', function() {
            const currentVersion = localStorage.getItem('app_version');
            const latestVersion = '{{ config("app.version", "1.0.0") }}-{{ time() }}';
            
            if (currentVersion !== latestVersion) {
                console.log('New version detected, clearing cache...');
                localStorage.setItem('app_version', latestVersion);
                
                // Clear service worker cache
                if ('serviceWorker' in navigator) {
                    navigator.serviceWorker.getRegistrations().then(function(registrations) {
                        for(let registration of registrations) {
                            registration.unregister();
                        }
                    }).then(function() {
                        // Force reload to get fresh assets
                        window.location.reload(true);
                    });
                }
            }
        });

        // Service Worker Registration with cache control
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                // Only register in production
                @production
                navigator.serviceWorker.register('/sw.js?v={{ time() }}')
                    .then(function(registration) {
                        console.log('ServiceWorker registered:', registration.scope);
                        
                        // Check for updates
                        registration.addEventListener('updatefound', () => {
                            const newWorker = registration.installing;
                            console.log('ServiceWorker update found!');
                            
                            newWorker.addEventListener('statechange', () => {
                                if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                    // New update available
                                    if(confirm('New version available. Update now?')) {
                                        newWorker.postMessage({action: 'skipWaiting'});
                                        window.location.reload();
                                    }
                                }
                            });
                        });
                    })
                    .catch(function(error) {
                        console.log('ServiceWorker registration failed:', error);
                    });
                @endproduction
            });
        }

        // Mobile menu toggle
        function toggleMobileMenu() {
            const menu = document.getElementById('mobile-menu');
            menu.classList.toggle('hidden');
        }

        // Dropdown toggle
        function toggleDropdown(id) {
            const dropdown = document.getElementById(id);
            dropdown.classList.toggle('hidden');
        }

        // Close dropdowns when clicking outside
        document.addEventListener('click', function(event) {
            const dropdowns = document.querySelectorAll('.dropdown-content');
            dropdowns.forEach(function(dropdown) {
                if (!dropdown.parentElement.contains(event.target)) {
                    dropdown.classList.add('hidden');
                }
            });
        });

        // Form validation
        function validateForm(formId) {
            const form = document.getElementById(formId);
            const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');
            let isValid = true;

            inputs.forEach(input => {
                if (!input.value.trim()) {
                    input.classList.add('border-red-500');
                    isValid = false;
                } else {
                    input.classList.remove('border-red-500');
                }
            });

            return isValid;
        }

        // Toast notifications
        function showToast(message, type = 'success') {
            const toast = document.createElement('div');
            toast.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg text-white ${
                type === 'success' ? 'bg-green-500' : 
                type === 'error' ? 'bg-red-500' : 
                'bg-blue-500'
            } transform translate-x-full transition-transform duration-300 z-50`;
            toast.innerHTML = `
                <div class="flex items-center space-x-2">
                    <i class="fas fa-${type === 'success' ? 'check' : 'exclamation-triangle'}"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.classList.remove('translate-x-full');
            }, 100);
            
            setTimeout(() => {
                toast.classList.add('translate-x-full');
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 3000);
        }

        // Auto-hide alerts
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert-auto-hide');
            alerts.forEach(alert => {
                setTimeout(() => {
                    alert.style.transition = 'all 0.5s ease-in-out';
                    alert.style.opacity = '0';
                    alert.style.height = '0';
                    alert.style.padding = '0';
                    alert.style.margin = '0';
                    setTimeout(() => {
                        alert.remove();
                    }, 500);
                }, 5000);
            });
        });
    </script>

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