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

    <title>@yield('title', App\Models\SystemSetting::getSiteTitle())</title>

    <!-- Favicon -->
    @if(App\Models\SystemSetting::getFavicon())
    <link rel="icon" type="image/x-icon" href="{{ asset(App\Models\SystemSetting::getFavicon()) }}">
    <link rel="shortcut icon" type="image/x-icon" href="{{ asset(App\Models\SystemSetting::getFavicon()) }}">
    @else
    <link rel="shortcut icon" href="{{ url(asset('favicon.ico')) }}">
    @endif

    <!-- PWA Meta Tags -->
    <link rel="manifest" href="{{ route('pwa.manifest') }}">
    <meta name="theme-color" content="#4F46E5">
    <link rel="apple-touch-icon" href="/icons/icon-192.png">
    <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="{{ config('pwa.default.short_name', 'Omnia') }}">
    <meta name="mobile-web-app-capable" content="yes">

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

    <!-- Theme Script (must run before body renders to prevent flash) -->
    <script>
        // Initialize theme on page load
        (function() {
            const theme = localStorage.getItem('theme');
            if (theme === 'dark') {
                document.documentElement.classList.add('dark');
            } else if (theme === 'light') {
                document.documentElement.classList.remove('dark');
            } else {
                // No preference set, use system preference
                if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
                    document.documentElement.classList.add('dark');
                } else {
                    document.documentElement.classList.remove('dark');
                }
            }
        })();
    </script>

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

    @livewireStyles

    @stack('styles')
</head>
<body class="antialiased bg-gray-50 dark:bg-gray-900 overflow-x-hidden">
    @yield('body')

    @livewireScripts

    <!-- Theme Toggle Script -->
    <script>
        function toggleTheme() {
            const html = document.documentElement;
            const isDark = html.classList.contains('dark');

            if (isDark) {
                // Switch to light mode
                html.classList.remove('dark');
                localStorage.setItem('theme', 'light');
                console.log('Switched to light mode');
            } else {
                // Switch to dark mode
                html.classList.add('dark');
                localStorage.setItem('theme', 'dark');
                console.log('Switched to dark mode');
            }

            // Force a repaint to ensure changes take effect
            html.style.display = 'none';
            html.offsetHeight; // Trigger reflow
            html.style.display = '';
        }
    </script>

    <!-- PWA Service Worker Registration -->
    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                // FORCE UPDATE: Change version to force browser to download new service worker
                const SW_VERSION = 'v5.0-notification-only';

                navigator.serviceWorker.register('/service-worker.js?v=' + SW_VERSION)
                    .then(function(registration) {
                        console.log('[PWA] ServiceWorker registration successful:', registration.scope);
                        console.log('[PWA] ServiceWorker version:', SW_VERSION);

                        // Force immediate update check
                        registration.update();

                        // Check for updates periodically
                        setInterval(function() {
                            registration.update();
                        }, 60000); // Check every minute

                        // Listen for service worker updates
                        registration.addEventListener('updatefound', function() {
                            const newWorker = registration.installing;
                            console.log('[PWA] New service worker found, installing...');

                            newWorker.addEventListener('statechange', function() {
                                if (newWorker.state === 'activated') {
                                    console.log('[PWA] New service worker activated! Reloading page...');
                                    // Optional: Auto-reload when new SW activates
                                    // window.location.reload();
                                }
                            });
                        });
                    })
                    .catch(function(err) {
                        console.log('[PWA] ServiceWorker registration failed:', err);
                    });
            });

            // Pre-loaded audio elements for mobile compatibility
            const audioCache = {};
            let audioUnlocked = false;

            // Unlock audio on first user interaction (required for iOS)
            function unlockAudio() {
                if (audioUnlocked) return;

                console.log('[PWA] Unlocking audio for mobile...');

                // Pre-load all notification sounds
                const sounds = {
                    'default': '{{ config("pwa.sounds.default") }}',
                    'high_value': '{{ config("pwa.sounds.high_value") }}'
                };

                Object.keys(sounds).forEach(key => {
                    const audio = new Audio();
                    audio.src = sounds[key];
                    audio.volume = {{ \App\Models\SystemSetting::getNotificationVolume() / 100 }};
                    audio.load(); // Pre-load

                    // Play and immediately pause to unlock on iOS
                    audio.play().then(() => {
                        audio.pause();
                        audio.currentTime = 0;
                        console.log('[PWA] Audio unlocked for:', key);
                    }).catch(e => {
                        console.log('[PWA] Audio unlock failed for:', key, e);
                    });

                    audioCache[sounds[key]] = audio;
                });

                audioUnlocked = true;
            }

            // Unlock audio on any user interaction
            ['click', 'touchstart', 'touchend', 'keydown'].forEach(eventType => {
                document.addEventListener(eventType, unlockAudio, { once: true, passive: true });
            });

            // Handle service worker messages
            navigator.serviceWorker.addEventListener('message', function(event) {
                console.log('[PWA] Received message from service worker:', event.data);

                if (event.data.type === 'NOTIFICATION_CLICK') {
                    // Handle notification click
                    if (event.data.url) {
                        window.location.href = event.data.url;
                    }
                }

                // Play notification sound
                if (event.data.type === 'PLAY_SOUND') {
                    console.log('[PWA] Playing sound:', event.data.sound);

                    // Try to use pre-loaded audio first (better for mobile)
                    let audio = audioCache[event.data.sound];

                    if (audio) {
                        // Use cached audio
                        console.log('[PWA] Using pre-loaded audio');
                        audio.currentTime = 0; // Reset to start
                        audio.volume = {{ \App\Models\SystemSetting::getNotificationVolume() / 100 }};
                        audio.play()
                            .then(() => console.log('[PWA] Sound played successfully (cached)'))
                            .catch(e => {
                                console.log('[PWA] Cached audio failed, trying fallback:', e);
                                playFallbackAudio(event.data.sound);
                            });
                    } else {
                        // Fallback to creating new Audio (works on desktop)
                        console.log('[PWA] Audio not cached, using fallback');
                        playFallbackAudio(event.data.sound);
                    }
                }
            });

            // Fallback audio playback
            function playFallbackAudio(soundUrl) {
                const audio = new Audio(soundUrl);
                audio.volume = {{ \App\Models\SystemSetting::getNotificationVolume() / 100 }};
                audio.play()
                    .then(() => console.log('[PWA] Fallback sound played successfully'))
                    .catch(e => {
                        console.log('[PWA] Could not play sound:', e);
                        console.log('[PWA] This might be due to browser autoplay restrictions');

                        // Show visual feedback if sound fails on mobile
                        if (isMobile()) {
                            showSoundFailedNotice();
                        }
                    });
            }

            // Detect mobile device
            function isMobile() {
                return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            }

            // Show notice when sound fails (optional)
            function showSoundFailedNotice() {
                // You can implement a visual indicator here if needed
                console.warn('[PWA] Sound playback blocked - user may need to interact with page first');
            }
        }
    </script>

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