<!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>@yield('title', 'Home') — {{ config('app.name') }}</title>
    <meta name="description" content="@yield('description', 'South Sudan Health Informatics Association - Advancing health informatics in South Sudan')">
    <meta name="keywords" content="@yield('keywords', 'health informatics, South Sudan, SSHIA, healthcare, digital health')">
    <meta name="author" content="{{ config('app.name') }}">

    {{-- Open Graph Meta Tags --}}
    <meta property="og:title" content="@yield('og_title', config('app.name'))">
    <meta property="og:description" content="@yield('og_description', 'South Sudan Health Informatics Association')">
    <meta property="og:type" content="@yield('og_type', 'website')">
    <meta property="og:url" content="{{ url()->current() }}">
    <meta property="og:image" content="@yield('og_image', 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="@yield('twitter_title', config('app.name'))">
    <meta name="twitter:description" content="@yield('twitter_description', 'South Sudan Health Informatics Association')">
    <meta name="twitter:image" content="@yield('twitter_image', 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 --}}
    @stack('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(isset($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">
        @yield('content')
    </main>

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

    {{-- ── Chat Widget ─────────────────────────────────────────────────────── --}}
    {{--
        z-[9999] ensures the widget sits above the sticky header (z-50) and
        all other page content. The panel is fixed to the bottom-right corner.
        On mobile it expands to near-full-screen width.
    --}}
    <div x-data="chatWidget()"
         class="fixed bottom-5 right-5 z-[9999] flex flex-col items-end"
         x-cloak>

        {{-- ── Floating trigger 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 flex-shrink-0"
                :aria-label="open ? 'Minimise chat' : 'Open chat support'"
                :aria-expanded="open.toString()">
            {{-- Unread badge (shown when minimised and there are messages) --}}
            <span x-show="minimised && messages.length > 0"
                  class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center font-bold"
                  x-text="messages.filter(m => m.sender_type === 'agent').length || ''"
                  x-cloak></span>
            <i class="fas fa-comments text-xl" x-show="!open || minimised" aria-hidden="true"></i>
            <i class="fas fa-minus  text-xl" x-show="open && !minimised" aria-hidden="true" x-cloak></i>
        </button>

        {{-- ── Chat 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="mb-3 w-[22rem] sm:w-[26rem] bg-white rounded-2xl shadow-2xl border border-gray-200 flex flex-col overflow-hidden"
             :class="minimised ? 'h-auto' : 'h-[32rem] sm:h-[36rem]'"
             x-cloak
             role="dialog"
             aria-modal="true"
             aria-label="Chat support">

            {{-- ── Panel header (always visible) ── --}}
            <div class="bg-[#1a4731] text-white px-4 py-3 flex items-center gap-3 flex-shrink-0 cursor-pointer select-none"
                 @click="minimised ? maximise() : null">
                <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 leading-tight flex items-center gap-1.5">
                        <span class="w-1.5 h-1.5 rounded-full inline-block" :class="phase === 'chatting' ? statusDot : 'bg-green-400'"></span>
                        <span x-show="phase === 'intro'"    class="text-green-200">We typically reply within minutes</span>
                        <span x-show="phase === 'chatting'" class="text-green-200" x-text="statusText"></span>
                        <span x-show="phase === 'ended'"    class="text-green-200">Session ended</span>
                    </p>
                </div>
                <div class="flex items-center gap-1 flex-shrink-0">
                    {{-- Minimise --}}
                    <button @click.stop="minimised ? maximise() : (minimised = true)"
                            class="w-7 h-7 rounded-full hover:bg-white/20 flex items-center justify-center transition focus:outline-none focus:ring-2 focus:ring-white"
                            :aria-label="minimised ? 'Expand chat' : 'Minimise chat'">
                        <i class="fas text-sm" :class="minimised ? 'fa-chevron-up' : 'fa-minus'" aria-hidden="true"></i>
                    </button>
                    {{-- Close --}}
                    <button @click.stop="close()"
                            class="w-7 h-7 rounded-full hover:bg-white/20 flex items-center justify-center transition 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>
            </div>

            {{-- ── Body (hidden when minimised) ── --}}
            <div x-show="!minimised" class="flex flex-col flex-1 min-h-0">

                {{-- ════ INTRO PHASE ════ --}}
                <div x-show="phase === 'intro'" class="flex flex-col flex-1 min-h-0">
                    <div class="flex-1 overflow-y-auto 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="4"
                                      @keydown="handleEnter($event)"
                                      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>
                        <p x-show="startError" x-text="startError"
                           class="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1"></p>
                    </div>
                    <div class="p-4 border-t border-gray-100 flex-shrink-0">
                        <button @click="startChat()"
                                :disabled="starting"
                                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 disabled:opacity-60 disabled:cursor-not-allowed">
                            <i class="fas fa-spinner fa-spin text-xs" x-show="starting" aria-hidden="true"></i>
                            <i class="fas fa-paper-plane text-xs" x-show="!starting" aria-hidden="true"></i>
                            <span x-text="starting ? 'Starting…' : 'Start Chat'"></span>
                        </button>
                        <p class="text-center text-xs text-gray-400 mt-2">
                            Or <a href="{{ route('chat.public.start') }}" class="text-green-600 hover:underline">open full chat page</a>
                        </p>
                    </div>
                </div>

                {{-- ════ CHATTING PHASE ════ --}}
                <div x-show="phase === 'chatting'" class="flex flex-col flex-1 min-h-0">

                    {{-- Messages area --}}
                    <div id="cw-messages" class="flex-1 overflow-y-auto p-4 space-y-3 bg-gray-50">

                        {{-- Empty state --}}
                        <template x-if="messages.length === 0">
                            <div class="text-center py-8 text-gray-500">
                                <i class="fas fa-comments text-3xl mb-3 block opacity-30"></i>
                                <p class="text-sm">An agent will be with you shortly.</p>
                            </div>
                        </template>

                        <template x-for="msg in messages" :key="msg.id">
                            <div>
                                {{-- System message --}}
                                <div x-show="msg.is_system" class="text-center">
                                    <span class="text-xs text-gray-400 bg-white px-3 py-1 rounded-full border border-gray-200"
                                          x-text="msg.message"></span>
                                </div>
                                {{-- Agent message --}}
                                <div x-show="!msg.is_system && msg.sender_type === 'agent'" class="flex justify-start items-end gap-2">
                                    <div class="w-6 h-6 rounded-full bg-[#1a4731] flex items-center justify-center text-white flex-shrink-0 mb-1">
                                        <i class="fas fa-headset text-xs"></i>
                                    </div>
                                    <div class="max-w-[78%]">
                                        <div class="px-3 py-2 rounded-2xl rounded-bl-sm text-sm leading-relaxed bg-white border border-gray-200 text-gray-800"
                                             x-text="msg.message"></div>
                                        <p class="text-xs text-gray-400 mt-0.5" x-text="msg.time"></p>
                                    </div>
                                </div>
                                {{-- Visitor message --}}
                                <div x-show="!msg.is_system && msg.sender_type === 'visitor'" class="flex justify-end">
                                    <div class="max-w-[78%]">
                                        <div class="px-3 py-2 rounded-2xl rounded-br-sm text-sm leading-relaxed text-white"
                                             :class="msg._pending ? 'opacity-60' : ''"
                                             style="background-color: #1a4731;"
                                             x-text="msg.message"></div>
                                        <p class="text-xs text-gray-400 mt-0.5 text-right" x-text="msg.time"></p>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>

                    {{-- Send form --}}
                    <div class="p-3 border-t border-gray-200 bg-white flex-shrink-0">
                        <div class="flex gap-2 items-end">
                            <textarea x-model="outgoing"
                                      @keydown="handleEnter($event)"
                                      rows="2"
                                      placeholder="Type a message…"
                                      class="flex-1 px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-green-500 resize-none transition"></textarea>
                            <button @click="sendMessage()"
                                    :disabled="!canSend"
                                    class="w-9 h-9 bg-[#1a4731] hover:bg-[#0f2819] text-white rounded-xl flex items-center justify-center transition disabled:opacity-40 disabled:cursor-not-allowed flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-green-500">
                                <i class="fas fa-paper-plane text-xs" aria-hidden="true"></i>
                            </button>
                        </div>
                        <div class="flex justify-between items-center mt-1.5">
                            <p class="text-xs text-gray-400">Enter to send · Shift+Enter for new line</p>
                            <button @click="endChat()"
                                    class="text-xs text-red-500 hover:text-red-700 transition focus:outline-none">
                                <i class="fas fa-times mr-1"></i>End chat
                            </button>
                        </div>
                    </div>
                </div>

                {{-- ════ ENDED PHASE ════ --}}
                <div x-show="phase === 'ended'" class="flex flex-col flex-1 items-center justify-center p-6 text-center">
                    <div class="w-14 h-14 rounded-full bg-green-100 flex items-center justify-center mb-4">
                        <i class="fas fa-check text-green-600 text-xl"></i>
                    </div>
                    <h4 class="font-semibold text-gray-800 mb-1">Chat Ended</h4>
                    <p class="text-sm text-gray-500 mb-5">Thank you for contacting us. We hope we were helpful!</p>
                    <button @click="phase = 'intro'; messages = []; sessionId = null; outgoing = ''; initialMessage = ''; visitorName = ''; visitorEmail = '';"
                            class="px-5 py-2 bg-[#1a4731] text-white text-sm font-semibold rounded-lg hover:bg-[#0f2819] transition focus:outline-none focus:ring-2 focus:ring-green-500">
                        <i class="fas fa-plus mr-1"></i> Start New Chat
                    </button>
                </div>

            </div>{{-- /body --}}
        </div>{{-- /panel --}}
    </div>{{-- /widget root --}}

    {{-- 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 --}}
    @stack('scripts')
</body>
</html>
