<!doctype html>
<html lang="{{ config('app.locale') }}"
      class="scroll-smooth">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    @php
        // TPL-01: SEO data cached 1 hour — was a DB query on EVERY page load
        // Bust with: Cache::forget('seo_data_' . activeTemplateName())
        $globalSeo = \Illuminate\Support\Facades\Cache::remember(
            'seo_data_' . activeTemplateName(),
            3600,
            fn () => \App\Models\Frontend::where('data_keys', 'seo.data')
                ->where('tempname', activeTemplateName())
                ->first()?->data_values
        );

        // Page-level SEO overrides (passed by controllers as $seoContents)
        $pageSeo = $seoContents ?? null;

        // Resolve each field: page-level > global > fallback
        $seoDescription = $pageSeo?->description ?? $pageDescription ?? $globalSeo?->description ?? gs('site_description') ?? '';
        $seoKeywords = $pageSeo?->keywords ?? $globalSeo?->keywords ?? [];
        $seoKeywordsStr = is_array($seoKeywords) ? implode(', ', $seoKeywords) : $seoKeywords;
        $seoRobots = !empty($pageSeo?->meta_robots) ? $pageSeo->meta_robots : (!empty($globalSeo?->meta_robots) ? $globalSeo->meta_robots : 'index, follow');
        $seoSocialTitle = $pageSeo?->social_title ?? $globalSeo?->social_title ?? gs()->siteName(__($pageTitle ?? ''));
        $seoSocialDesc = $pageSeo?->social_description ?? $globalSeo?->social_description ?? $seoDescription;

        // SEO Image: page-level > global > site logo
        $seoImageFile = $pageSeo?->image ?? $globalSeo?->image ?? null;
        $seoImage = $seoImageFile ? asset(getFilePath('seo') . '/' . $seoImageFile) : siteLogo();
    @endphp

    {{-- Primary Meta Tags --}}
    @php
        $seoTitlePart = !empty($pageSeo?->meta_title) ? $pageSeo->meta_title : (!empty($globalSeo?->meta_title) ? $globalSeo->meta_title : __($pageTitle ?? ''));
    @endphp
    <title>{{ gs()->siteName($seoTitlePart) }}</title>
    <meta name="description" content="{{ $seoDescription }}">
    @if($seoKeywordsStr)
        <meta name="keywords" content="{{ $seoKeywordsStr }}">
    @endif
    <meta name="robots" content="{{ $seoRobots }}">
    <meta name="author" content="{{ gs('site_name') }}">
    <meta name="theme-color" content="{{ templateMeta('colors.primary') ?? '#CC2628' }}">

    {{-- Canonical URL --}}
    <link rel="canonical" href="{{ url()->current() }}">

    {{-- Open Graph / Facebook --}}
    <meta property="og:type" content="website">
    <meta property="og:url" content="{{ url()->current() }}">
    <meta property="og:title" content="{{ $seoSocialTitle }}">
    <meta property="og:description" content="{{ $seoSocialDesc }}">
    <meta property="og:site_name" content="{{ gs('site_name') }}">
    <meta property="og:locale" content="{{ str_replace('-', '_', config('app.locale', 'en')) }}">
    @if($seoImage)
        <meta property="og:image" content="{{ $seoImage }}">
        <meta property="og:image:width" content="1200">
        <meta property="og:image:height" content="630">
    @endif

    {{-- Twitter / X --}}
    <meta name="twitter:card" content="{{ $seoImage ? 'summary_large_image' : 'summary' }}">
    <meta name="twitter:title" content="{{ $seoSocialTitle }}">
    <meta name="twitter:description" content="{{ $seoSocialDesc }}">
    @if($seoImage)
        <meta name="twitter:image" content="{{ $seoImage }}">
    @endif

    {{-- Favicon --}}
    <link rel="icon" type="image/png" href="{{ siteFavicon() }}">
    <link rel="shortcut icon" type="image/png" href="{{ siteFavicon() }}">

    {{-- Theme Controller — Shared with client area (Single Source of Truth) --}}
    @include('partials.theme-controller')

    <!-- Fonts -->
    @php
        $cs = clientAreaSettings();
        $fontFamily = $cs['font_family'] ?? 'Inter';
        $headingFont = $cs['heading_font'] ?? $fontFamily;
        $fontUrl = $cs['font_url'] ?? 'https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap';
        
        // Theme Colors - Pull from theme.json if possible, fallback to global settings or defaults
        $primary = templateMeta('colors.primary') ?: ($cs['primary_color'] ?? '#CC2628');
        
        // Convert Hex to RGB for tailwind/color-mix utilities (TPL-04: extracted to helper)
        $primaryRgb = hexToRgb($primary);

        // Neutral palette from theme.json
        $neutralDark = templateMeta('colors.neutral_dark') ?? '#0A0A0A';
        $neutralMid = templateMeta('colors.neutral_mid') ?? '#18181B';
        $neutralBorder = templateMeta('colors.neutral_border') ?? '#27272A';
        $neutralMuted = templateMeta('colors.neutral_muted') ?? '#A1A1AA';

        // Semantic tokens from theme.json
        $headingLight = templateMeta('colors.heading_light') ?? '#1f1b4d';
        $surfaceOffwhite = templateMeta('colors.surface_offwhite') ?? '#fcfcfd';
        $svgDark = templateMeta('colors.svg_dark') ?? '#0f172a';
        $svgMid = templateMeta('colors.svg_mid') ?? '#1e293b';
        $svgLight = templateMeta('colors.svg_light') ?? '#334155';
        $svgMuted = templateMeta('colors.svg_muted') ?? '#94a3b8';
        $svgSubtle = templateMeta('colors.svg_subtle') ?? '#cbd5e1';
        $svgSurface = templateMeta('colors.svg_surface') ?? '#f1f5f9';

        // Footer Colors from theme.json
        $footerBg = templateMeta('colors.footer_bg') ?? '#111827';
        $footerText = templateMeta('colors.footer_text') ?? '#F9FAFB';
        $footerBgDark = templateMeta('colors.footer_bg_dark') ?? '#050505';
        $footerTextDark = templateMeta('colors.footer_text_dark') ?? '#E2E8F0';
    @endphp
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="{{ $fontUrl }}" rel="stylesheet" media="print" data-async-css />
    <noscript><link href="{{ $fontUrl }}" rel="stylesheet" /></noscript>
    
          
    @vite([
        'resources/views/templates/salieno/assets/css/salieno.css',
        'resources/views/templates/salieno/assets/js/salieno.js'
    ])

    @livewireStyles
    @stack('style-lib')
    @stack('style')

    <!-- Phosphor Icons — async loaded (non-render-blocking) -->
    <link rel="stylesheet" href="{{ asset('assets/phosphor/regular.css') }}" media="print" data-async-css />
    <noscript><link rel="stylesheet" href="{{ asset('assets/phosphor/regular.css') }}" /></noscript>
    <link rel="stylesheet" href="{{ asset('assets/phosphor/bold.css') }}" media="print" data-async-css />
    <noscript><link rel="stylesheet" href="{{ asset('assets/phosphor/bold.css') }}" /></noscript>
    <link rel="stylesheet" href="{{ asset('assets/phosphor/fill.css') }}" media="print" data-async-css />
    <noscript><link rel="stylesheet" href="{{ asset('assets/phosphor/fill.css') }}" /></noscript>
    {{-- CSP-safe async CSS loader (replaces inline onload handlers) --}}
    <script nonce="{{ csp_nonce() }}">
    document.querySelectorAll('link[data-async-css]').forEach(function(l){
        l.onload=function(){this.media='all'};
    });
    </script>

    <style>
        /* ═══ Page Loader — Prevents FOUC ═══ */
        #salieno-loader {
            position: fixed;
            inset: 0;
            z-index: 99999;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--theme-bg-light, #ffffff);
            transition: opacity .3s ease, visibility .3s ease;
        }
        .dark #salieno-loader {
            background: var(--theme-bg-dark, #0a0a0a);
        }
        #salieno-loader.loaded {
            opacity: 0;
            visibility: hidden;
        }
        #salieno-loader .loader-spinner {
            width: 36px;
            height: 36px;
            border: 3px solid transparent;
            border-top-color: var(--primary, #6366f1);
            border-radius: 50%;
            animation: spin .6s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        [x-cloak] { display: none !important; }

        h1, h2, h3, h4, h5, h6 {
            font-family: var(--heading-font);
        }

        /* Global font reset - Ensuring all text uses the theme font while preserving icons */
        *:not(i, [class^="ph-"], [class*=" ph-"], [class^="fa-"], [class*=" fa-"]) {
            font-family: var(--font-family);
        }

        {{-- Advanced CSS Variable Core --}}
        :root {
            --primary: {{ $primary }};
            --primary-rgb: {{ $primaryRgb }};

            /* Font Sync - Standardized for Tailwind v4 Sync */
            --font-family: '{{ $fontFamily }}', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            --font-sans: '{{ $fontFamily }}', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            --heading-font: '{{ $headingFont }}', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            
            {{-- Dynamic Tints & Shades via color-mix --}}
            --primary-tint: color-mix(in srgb, var(--primary), white 20%);
            --primary-shade: color-mix(in srgb, var(--primary), black 20%);
            --primary-glow: color-mix(in srgb, var(--primary), transparent 85%);
            
            --neutral-dark: {{ $neutralDark }};
            --neutral-mid: {{ $neutralMid }};
            --neutral-border: {{ $neutralBorder }};
            --neutral-muted: {{ $neutralMuted }};

            --heading-light: {{ $headingLight }};
            --surface-offwhite: {{ $surfaceOffwhite }};
            --svg-dark: {{ $svgDark }};
            --svg-mid: {{ $svgMid }};
            --svg-light: {{ $svgLight }};
            --svg-muted: {{ $svgMuted }};
            --svg-subtle: {{ $svgSubtle }};
            --svg-surface: {{ $svgSurface }};
            
            {{-- Semantic Mappings --}}
            --theme-bg-light: #ffffff;
            --theme-text-light: var(--neutral-dark);
            
            --theme-bg-dark: var(--neutral-dark);
            --theme-text-dark: #ffffff;
            --theme-text-muted: var(--neutral-muted);

            --footer-bg: {{ $footerBg }};
            --footer-text: {{ $footerText }};
        }

        .dark {
            --footer-bg: {{ $footerBgDark }};
            --footer-text: {{ $footerTextDark }};
        }
    </style>
</head>

<body class="bg-[var(--theme-bg-light)] text-[var(--theme-text-light)] dark:bg-[var(--theme-bg-dark)] dark:text-[var(--theme-text-dark)] font-sans antialiased">
    {{-- Page Loader — shown instantly, dismissed on load --}}
    <div id="salieno-loader">
        <div class="loader-spinner"></div>
    </div>
    @if(isset($slot))
        {{ $slot }}
    @else
        @yield('app')
    @endif

    {{-- Global Toast Component --}}
    <div x-data="{ 
        toasts: [],
        add(toast) {
            toast.id = Date.now();
            this.toasts.push(toast);
            setTimeout(() => {
                this.toasts = this.toasts.filter(t => t.id !== toast.id);
            }, 5000);
        }
    }" 
    @toast.window="add($event.detail)"
    class="fixed bottom-6 left-6 z-[var(--z-toast)] flex flex-col gap-3 w-80 pointer-events-none">
        <template x-for="toast in toasts" :key="toast.id">
            <div x-show="true" 
                 x-transition:enter="transition ease-out duration-300"
                 x-transition:enter-start="opacity-0 translate-y-4"
                 x-transition:enter-end="opacity-100 translate-y-0"
                 x-transition:leave="transition ease-in duration-300"
                 x-transition:leave-start="opacity-100 translate-y-0"
                 x-transition:leave-end="opacity-0 translate-y-4"
                 class="pointer-events-auto p-4 rounded-2xl shadow-lg border flex items-center gap-4 animate-scale-up"
                 :class="{
                     'bg-white dark:bg-slate-900 border-slate-200 dark:border-white/10': !toast.type || toast.type === 'info',
                     'bg-green-500 border-green-400 text-white': toast.type === 'success',
                     'bg-rose-500 border-rose-400 text-white': toast.type === 'error',
                     'bg-amber-500 border-amber-400 text-white': toast.type === 'warning'
                 }">
                <div class="flex-shrink-0 w-10 h-10 rounded-xl bg-slate-100 dark:bg-white/10 flex items-center justify-center">
                    <i class="ph ph-bold text-xl" :class="{
                        'ph-info': !toast.type || toast.type === 'info',
                        'ph-check': toast.type === 'success',
                        'ph-warning-octagon': toast.type === 'error',
                        'ph-warning': toast.type === 'warning'
                    }"></i>
                </div>
                <div class="flex-1 min-w-0">
                    <p class="text-sm font-bold tracking-tight" x-text="toast.message"></p>
                </div>
                <button @click="toasts = toasts.filter(t => t.id !== toast.id)" class="opacity-50 hover:opacity-100 p-1">
                    <i class="ph ph-x"></i>
                </button>
            </div>
        </template>
    </div>

    <script nonce="{{ csp_nonce() }}">
        window.notify = function(type, message) {
            // Normalize arguments for flexible usage: notify('success', 'msg') or notify('msg') defaults to info
            let t = type;
            let m = message;
            if (!m) {
                m = t;
                t = 'info';
            }
            window.dispatchEvent(new CustomEvent('toast', { detail: { message: m, type: t } }));
        };
    </script>

    @livewireScripts

    @if(config('app.demo_mode'))
    <script nonce="{{ csp_nonce() }}">
        document.addEventListener('livewire:init', () => {
            Livewire.hook('request', ({ fail }) => {
                fail(({ status, content, preventDefault }) => {
                    if (status === 403) {
                        preventDefault();
                        try {
                            const data = JSON.parse(content);
                            window.notify('warning', data.message || 'This action is disabled in demo mode.');
                        } catch (e) {
                            window.notify('warning', 'This action is disabled in demo mode.');
                        }
                    }
                });
            });
        });
    </script>
    @endif
    
    @if(gs('ticket_livechat_enabled'))
        <livewire:frontend.live-chat.chat-widget />
    @endif

    @stack('script-lib')
    @stack('script')

    {{-- TPL-05: Dismiss loader on DOMContentLoaded (faster than window.load)
         with 4-second safety timeout (was 8s). Uses rAF for smooth visual. --}}
    <script nonce="{{ csp_nonce() }}">
        (function() {
            function dismissLoader() {
                var loader = document.getElementById('salieno-loader');
                if (loader && !loader._dismissed) {
                    loader._dismissed = true;
                    requestAnimationFrame(function() {
                        loader.classList.add('loaded');
                        setTimeout(function() { loader.remove(); }, 350);
                    });
                }
            }
            // Fire on DOM ready (doesn't wait for images/fonts)
            if (document.readyState !== 'loading') { dismissLoader(); }
            else { document.addEventListener('DOMContentLoaded', dismissLoader); }
            // Livewire SPA navigation
            document.addEventListener('livewire:navigated', dismissLoader);
            // Safety timeout — 4 seconds max (was 8s)
            setTimeout(dismissLoader, 4000);
        })();
    </script>
</body>
</html>