<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" dir="{{ session('is_rtl', false) ? 'rtl' : 'ltr' }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        @php
            // 1. Fetch Global Settings Securely
            $settings = \Illuminate\Support\Facades\Cache::rememberForever('app_settings', function () {
                return \Illuminate\Support\Facades\Schema::hasTable('settings') 
                    ? \App\Models\Setting::pluck('value', 'key')->toArray() 
                    : [];
            });
            
            $appName = config('app.name', 'OwnStore');
            $defaultDesc = $settings['seo_meta_description'] ?? 'Global B2B/B2C Marketplace';
            $defaultKeywords = $settings['seo_meta_keywords'] ?? 'marketplace, b2b, wholesale, shop';
            
            $defaultImage = \Illuminate\Support\Facades\Storage::disk('public')->exists('settings/og_image.png')
                ? asset('storage/settings/og_image.png') . '?v=' . time()
                : asset('placeholder.jpg'); 
                
            $favicon = \Illuminate\Support\Facades\Storage::disk('public')->exists('settings/favicon.png')
                ? asset('storage/settings/favicon.png') . '?v=' . time()
                : asset('favicon.ico');

            // 2. Extract Dynamic SEO Props from Inertia Controllers
            $seo = $page['props']['seo'] ?? [];
            
            $title = isset($seo['title']) ? $seo['title'] . ' | ' . $appName : $appName;
            $description = $seo['description'] ?? $defaultDesc;
            $keywords = $seo['keywords'] ?? $defaultKeywords;
            $url = $seo['url'] ?? request()->url();
            $type = $seo['type'] ?? 'website';
            
            // 3. Handle Multiple Images (For Pinterest & Facebook Carousel)
            $images = $seo['images'] ?? [];
            if (is_string($images)) {
                $images = [$images];
            }
            if (empty($images)) {
                $images = [$defaultImage];
            }
        @endphp

        <!-- Basic SEO -->
        <title inertia>{{ $title }}</title>
        <meta name="description" content="{{ $description }}">
        <meta name="keywords" content="{{ $keywords }}">
        
        <!-- Open Graph / Facebook / Pinterest / WhatsApp -->
        <meta property="og:site_name" content="{{ $appName }}">
        <meta property="og:type" content="{{ $type }}">
        <meta property="og:url" content="{{ $url }}">
        <meta property="og:title" content="{{ $title }}">
        <meta property="og:description" content="{{ $description }}">
        
        <!-- Loop through all images for Pinterest / Facebook -->
        @foreach($images as $image)
            <meta property="og:image" content="{{ $image }}">
            <meta property="og:image:secure_url" content="{{ $image }}">
        @endforeach

        <!-- Twitter Card -->
        <meta name="twitter:card" content="summary_large_image">
        <meta name="twitter:url" content="{{ $url }}">
        <meta name="twitter:title" content="{{ $title }}">
        <meta name="twitter:description" content="{{ $description }}">
        <meta name="twitter:image" content="{{ $images[0] }}">

        <!-- Favicon -->
        <link rel="icon" type="image/x-icon" href="{{ $favicon }}">

        <!-- PWA Integration -->
        @if(($settings['pwa_enable'] ?? '0') === '1')
            <link rel="manifest" href="/manifest.json">
            <meta name="theme-color" content="{{ $settings['pwa_theme_color'] ?? '#000000' }}">
            <link rel="apple-touch-icon" href="{{ \Illuminate\Support\Facades\Storage::disk('public')->exists('settings/pwa_icon.png') ? asset('storage/settings/pwa_icon.png') : asset('placeholder.png') }}">
            
            <!-- Modern PWA Standard (Fixes Warning) -->
            <meta name="mobile-web-app-capable" content="yes">
            <!-- Legacy iOS Fallback -->
            <meta name="apple-mobile-web-app-capable" content="yes">
            <meta name="apple-mobile-web-app-status-bar-style" content="black">
            
            <!-- Register Service Worker -->
            <script>
                if ('serviceWorker' in navigator) {
                    window.addEventListener('load', () => {
                        navigator.serviceWorker.register('/sw.js').then(registration => {
                            console.log('PWA ServiceWorker registered successfully.');
                        }).catch(err => {
                            console.log('PWA ServiceWorker registration failed: ', err);
                        });
                    });
                }
            </script>
        @endif

        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,500,600,700,800,900&display=swap" rel="stylesheet" />
        
        <!-- === CUSTOM HEADER SCRIPTS === -->
        @if(!empty($settings['custom_header_script']))
            {!! $settings['custom_header_script'] !!}
        @endif

        <!-- Scripts -->
        @routes
        @viteReactRefresh
        @vite(['resources/js/app.jsx', "resources/js/Pages/{$page['component']}.jsx"])
        @inertiaHead
    </head>
    <body class="font-sans antialiased">
        @inertia

    <!-- === CUSTOM FOOTER SCRIPTS === -->
        @if(!empty($settings['custom_footer_script']))
            {!! $settings['custom_footer_script'] !!}
        @endif
    </body>
</html>