@props([
    'title' => 'Home',
    'description' => 'South Sudan Health Informatics Association - Advancing health informatics in South Sudan',
    'keywords' => 'health informatics, South Sudan, SSHIA, healthcare, digital health',
    'breadcrumbs' => null,
    'showBreadcrumbs' => true,
    'metaDescription' => null,
])

<!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() }}">

    {{-- SEO Meta Tags --}}
    <title>{{ $title }} — {{ config('app.name') }}</title>
    <meta name="description" content="{{ $metaDescription ?? $description }}">
    <meta name="keywords" content="{{ $keywords }}">
    <meta name="author" content="{{ config('app.name') }}">

    {{-- Open Graph Meta Tags --}}
    <meta property="og:title" content="{{ $title }} — {{ config('app.name') }}">
    <meta property="og:description" content="{{ $description }}">
    <meta property="og:type" content="website">
    <meta property="og:url" content="{{ url()->current() }}">
    <meta property="og:image" content="{{ asset('storage/organization/logo.png') }}">
    <meta property="og:site_name" content="{{ config('app.name') }}">

    {{-- Twitter Card Meta Tags --}}
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="{{ $title }} — {{ config('app.name') }}">
    <meta name="twitter:description" content="{{ $description }}">
    <meta name="twitter:image" content="{{ asset('storage/organization/logo.png') }}">

    {{-- Favicon --}}
    <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}">

    {{-- 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" />

    {{-- Preload Critical Assets for Performance --}}
    <link rel="preload" as="style" href="{{ asset('build/assets/app.css') }}" onload="this.onload=null;this.rel='stylesheet'">
    <noscript><link rel="stylesheet" href="{{ asset('build/assets/app.css') }}"></noscript>

    {{-- Theme CSS Variables (Injected by Middleware) --}}
    @if(isset($themeCssVariables) && is_array($themeCssVariables))
    <style>
        :root {
            @foreach($themeCssVariables as $property => $value)
            {{ $property }}: {{ $value }};
            @endforeach
        }
    </style>
    @endif

    {{-- Alpine.js cloak style --}}
    <style>[x-cloak] { display: none !important; }</style>

    {{-- Vite Assets --}}
    @vite(['resources/css/app.css', 'resources/js/app.js'])

    {{-- Additional Styles --}}
    {{ $styles ?? '' }}
</head>
<body class="antialiased bg-white font-sans">
    
    {{-- Site Header --}}
    @php
        try {
            $org = \App\Models\Organization::first();
        } catch (\Exception $e) {
            \Log::error('Failed to fetch organization data: ' . $e->getMessage());
            $org = null;
        }
        
        try {
            $topbarNotifications = app(\App\Services\TopbarNotificationService::class)->getActive();
        } catch (\Exception $e) {
            \Log::error('Failed to fetch topbar notifications: ' . $e->getMessage());
            $topbarNotifications = collect([]);
        }
    @endphp
    
    <x-site-header :organization="$org" :notifications="$topbarNotifications" />

    {{-- Breadcrumbs (Optional) --}}
    @if($showBreadcrumbs && $breadcrumbs && !empty($breadcrumbs))
        <x-breadcrumbs :items="$breadcrumbs" />
    @endif

    {{-- Flash Messages --}}
    @if(session('success') || session('error') || session('warning') || session('info'))
        <div class="w-full px-4 sm:px-6 lg:px-8 pt-4">
            @if(session('success'))
                <div x-data="{ show: true }" x-show="show" x-transition
                     class="flex items-center gap-3 bg-green-50 border border-green-200 text-green-800 rounded-lg px-4 py-3 mb-2">
                    <i class="fas fa-check-circle text-green-500"></i>
                    <span class="text-sm flex-1">{{ session('success') }}</span>
                    <button @click="show = false" class="text-green-400 hover:text-green-600"><i class="fas fa-times"></i></button>
                </div>
            @endif
            @if(session('error'))
                <div x-data="{ show: true }" x-show="show" x-transition
                     class="flex items-center gap-3 bg-red-50 border border-red-200 text-red-800 rounded-lg px-4 py-3 mb-2">
                    <i class="fas fa-exclamation-circle text-red-500"></i>
                    <span class="text-sm flex-1">{{ session('error') }}</span>
                    <button @click="show = false" class="text-red-400 hover:text-red-600"><i class="fas fa-times"></i></button>
                </div>
            @endif
            @if(session('warning'))
                <div x-data="{ show: true }" x-show="show" x-transition
                     class="flex items-center gap-3 bg-amber-50 border border-amber-200 text-amber-800 rounded-lg px-4 py-3 mb-2">
                    <i class="fas fa-exclamation-triangle text-amber-500"></i>
                    <span class="text-sm flex-1">{{ session('warning') }}</span>
                    <button @click="show = false" class="text-amber-400 hover:text-amber-600"><i class="fas fa-times"></i></button>
                </div>
            @endif
            @if(session('info'))
                <div x-data="{ show: true }" x-show="show" x-transition
                     class="flex items-center gap-3 bg-blue-50 border border-blue-200 text-blue-800 rounded-lg px-4 py-3 mb-2">
                    <i class="fas fa-info-circle text-blue-500"></i>
                    <span class="text-sm flex-1">{{ session('info') }}</span>
                    <button @click="show = false" class="text-blue-400 hover:text-blue-600"><i class="fas fa-times"></i></button>
                </div>
            @endif
        </div>
    @endif

    {{-- Main Content --}}
    <main class="min-h-screen">
        {{ $slot }}
    </main>

    {{-- Site Footer --}}
    <x-site-footer :organization="$org" />

    {{-- ── Chat Widget ─────────────────────────────────────────────────────── --}}
    {{-- open starts as false; x-cloak hides until Alpine initialises --}}
    <div x-data="chatWidget()" class="fixed bottom-6 right-6 z-40" x-cloak>

        {{-- Floating button --}}
        <button @click="toggle()"
                class="relative w-14 h-14 bg-[#1a4731] hover:bg-[#0f2819] text-white rounded-full shadow-2xl flex items-center justify-center transition-all duration-200 hover:scale-110 focus:outline-none focus:ring-4 focus:ring-green-500/50"
                :aria-label="open ? 'Close chat' : 'Open chat support'"
                :aria-expanded="open.toString()">
            <i class="fas fa-comments text-xl transition-all" x-show="!open" aria-hidden="true"></i>
            <i class="fas fa-times  text-xl transition-all" x-show="open"  aria-hidden="true" x-cloak></i>
        </button>

        {{-- Popup panel --}}
        <div x-show="open"
             x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0 translate-y-4 scale-95"
             x-transition:enter-end="opacity-100 translate-y-0 scale-100"
             x-transition:leave="transition ease-in duration-150"
             x-transition:leave-start="opacity-100 translate-y-0 scale-100"
             x-transition:leave-end="opacity-0 translate-y-4 scale-95"
             class="absolute bottom-16 right-0 w-80 bg-white rounded-2xl shadow-2xl overflow-hidden border border-gray-100"
             x-cloak
             role="dialog"
             aria-modal="true"
             aria-label="Chat support">

            {{-- Header --}}
            <div class="bg-[#1a4731] text-white px-4 py-3 flex items-center gap-3">
                <div class="w-9 h-9 rounded-full bg-white/20 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-headset text-sm" aria-hidden="true"></i>
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="font-semibold text-sm leading-tight">SSHIA Support</h3>
                    <p class="text-xs text-green-200 leading-tight">We typically reply within minutes</p>
                </div>
                <button @click="close()"
                        class="w-7 h-7 rounded-full hover:bg-white/20 flex items-center justify-center transition flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-white"
                        aria-label="Close chat">
                    <i class="fas fa-times text-sm" aria-hidden="true"></i>
                </button>
            </div>

            {{-- Form --}}
            <div class="p-4 space-y-3">
                <div>
                    <label for="cw-name" class="block text-xs font-medium text-gray-600 mb-1">Name <span class="text-gray-400">(optional)</span></label>
                    <input type="text"
                           id="cw-name"
                           x-model="visitorName"
                           placeholder="Your name"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-green-500 transition">
                </div>

                <div>
                    <label for="cw-email" class="block text-xs font-medium text-gray-600 mb-1">Email <span class="text-gray-400">(optional)</span></label>
                    <input type="email"
                           id="cw-email"
                           x-model="visitorEmail"
                           placeholder="your@email.com"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-green-500 transition">
                </div>

                <div>
                    <label for="cw-message" class="block text-xs font-medium text-gray-600 mb-1">
                        Message <span class="text-red-500">*</span>
                    </label>
                    <textarea id="cw-message"
                              x-model="initialMessage"
                              placeholder="How can we help you?"
                              rows="3"
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-green-500 resize-none transition"></textarea>
                </div>

                <button @click="startChat()"
                        class="w-full px-4 py-2.5 bg-[#1a4731] hover:bg-[#0f2819] text-white rounded-lg text-sm font-semibold transition flex items-center justify-center gap-2 focus:outline-none focus:ring-2 focus:ring-green-500">
                    <i class="fas fa-paper-plane text-xs" aria-hidden="true"></i>
                    Start Chat
                </button>

                <p class="text-center text-xs text-gray-400">
                    Or <a href="{{ route('chat.public.start') }}" class="text-green-600 hover:underline">open full chat page</a>
                </p>
            </div>
        </div>
    </div>

    {{-- CDN Fallbacks --}}
    <script>
        {{--
            NOTE: Alpine is loaded via Vite as a JS module (type="module", deferred).
            A synchronous document.write() CDN fallback CANNOT be used here because
            window.Alpine is not yet set when this inline script runs — the module
            hasn't executed yet. Loading a second bare Alpine CDN build would start
            Alpine without the registered siteHeader/chatWidget components, breaking
            the notification ticker and all other Alpine components.

            The FontAwesome fallback below is safe because it only appends a <link>.
        --}}

        // FontAwesome CDN fallback (safe — only injects a stylesheet link)
        if (!document.querySelector('link[href*="fontawesome"]') && !document.querySelector('link[href*="font-awesome"]')) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css';
            link.crossOrigin = 'anonymous';
            link.referrerPolicy = 'no-referrer';
            document.head.appendChild(link);
        }
    </script>

    {{-- Additional Scripts --}}
    {{ $scripts ?? '' }}
    @stack('scripts')
</body>
</html>
