@php
    $brand = app(\App\Domain\Shared\Services\BrandingService::class)->forCurrentAcademy();
    // Direction follows the locale rather than being hardcoded: a document
    // marked dir="rtl" while announcing lang="en" tells a screen reader two
    // contradictory things about the same text.
    $locale = app()->getLocale();
    $dir = in_array($locale, ['ar', 'he', 'fa', 'ur'], true) ? 'rtl' : 'ltr';
    $portal = app(\App\Domain\Shared\Context\PortalContext::class);
    $profiles = $portal->switchableProfiles();
@endphp
<!DOCTYPE html>
<html dir="{{ $dir }}" lang="{{ $locale }}" class="h-full"
      data-theme-mode="{{ $brand->themeMode }}"
      data-theme="{{ $brand->themeMode === 'dark' ? 'dark' : 'light' }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="theme-color" content="{{ $brand->themeColor }}">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="{{ $brand->appShortName }}">
    <title>{{ $title ?? __('حسابي') }} — {{ $brand->academyName }}</title>

    <link rel="manifest" href="{{ route('portal.manifest') }}">
    @if($brand->faviconUrl)
        <link rel="icon" href="{{ $brand->faviconUrl }}">
    @endif
    @if($brand->appIconUrl)
        <link rel="apple-touch-icon" href="{{ $brand->appIconUrl }}">
    @endif

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family={{ urlencode($brand->fontAr) }}:wght@400;500;600;700;800&display=swap" rel="stylesheet">

    {{-- portal.css only. Two Tailwind entrypoints on one document means two
         preflights and a non-deterministic @layer order. --}}
    @vite(['resources/css/portal.css', 'resources/js/portal.js'])
    @livewireStyles

    <style>
        :root {
{!! $brand->cssVariableBlock() !!}
            --portal-bg: oklch(0.985 0.002 265);
            --portal-surface: #ffffff;
            --portal-border: oklch(0.92 0.004 265);
            --portal-ink: oklch(0.22 0.02 265);
            --portal-muted: oklch(0.55 0.015 265);

            /* Interactive text — links, the active tab, a figure that is also
               a destination. Not a shade of the ramp: a navy tenant's 600 is
               indistinguishable from body text and a yellow tenant's is
               illegible. See ColorRamp::interactive(). */
            --portal-link: var(--brand-link);

            /* The semantic palette as text. The raw --brand-danger/-warning are
               fills; used as small text on a light card they sit below AA. */
            --portal-success-ink: var(--brand-success-ink);
            --portal-warning-ink: var(--brand-warning-ink);
            --portal-danger-ink: var(--brand-danger-ink);
        }

        [data-theme='dark'] {
            --portal-bg: oklch(0.18 0.012 265);
            --portal-surface: oklch(0.23 0.014 265);
            --portal-border: oklch(0.31 0.016 265);
            --portal-ink: oklch(0.96 0.004 265);
            --portal-muted: oklch(0.70 0.012 265);
            --portal-link: var(--brand-link-dark);
            --portal-success-ink: var(--brand-success-ink-dark);
            --portal-warning-ink: var(--brand-warning-ink-dark);
            --portal-danger-ink: var(--brand-danger-ink-dark);
        }

        html, body {
            background: var(--portal-bg);
            color: var(--portal-ink);
        }

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

    {{-- Set before first paint so `auto` never flashes the wrong theme. --}}
    <script>
        (function () {
            var root = document.documentElement;
            if (root.dataset.themeMode !== 'auto') return;
            var dark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
            root.setAttribute('data-theme', dark ? 'dark' : 'light');
        })();
    </script>
</head>
<body class="min-h-full antialiased">
<div class="mx-auto flex min-h-dvh max-w-2xl flex-col">

    <header class="pt-safe sticky top-0 z-40 border-b"
            style="background: var(--portal-surface); border-color: var(--portal-border);">
        <div class="flex items-center gap-2 px-4 py-2.5">
            @if($brand->logoUrl)
                {{-- Sized by .portal-logo, not by utilities: the frame must hold
                     whatever a tenant uploaded, square crest or wide wordmark. --}}
                <img src="{{ $brand->logoUrl }}" alt="{{ $brand->academyName }}" class="portal-logo shrink-0">
            @else
                <span class="grid h-8 w-8 place-items-center rounded-lg text-sm font-bold"
                      style="background: var(--brand-500); color: var(--brand-fg);">
                    {{ mb_substr($brand->academyName, 0, 1) }}
                </span>
            @endif

            {{-- The screen's name, once. The active member used to be repeated
                 here under it — the profile switcher below already names them,
                 and every screen's own heading names them again. --}}
            <div class="min-w-0 flex-1">
                <p class="truncate text-sm font-bold leading-tight">{{ $title ?? $brand->academyName }}</p>
            </div>

            @if($portal->speaksForAnyone())
                {{-- The pass is per active profile: a guardian with three
                     children needs three, so it is an affordance in the header
                     rather than a tab of its own. --}}
                <a href="{{ route('portal.pass') }}"
                   class="tap-target rounded-xl"
                   style="color: var(--portal-muted);"
                   aria-label="{{ __('بطاقة الدخول') }}">
                    <x-portal.icon name="pass" class="h-6 w-6" />
                </a>
            @endif

            <a href="{{ route('portal.notifications') }}"
               class="tap-target relative rounded-xl"
               style="color: var(--portal-muted);"
               aria-label="{{ __('الإشعارات') }}">
                <x-portal.icon name="bell" class="h-6 w-6" />
                @if(($unreadNotifications ?? 0) > 0)
                    <span class="absolute end-1.5 top-1.5 grid h-4 min-w-4 place-items-center rounded-full px-1 text-[10px] font-bold"
                          style="background: var(--brand-danger); color: var(--brand-danger-fg);">
                        {{ $unreadNotifications > 9 ? '9+' : $unreadNotifications }}
                    </span>
                @endif
            </a>
        </div>

        @if($profiles->count() > 1)
            <livewire:portal.profile-switcher />
        @endif
    </header>

    <main class="flex-1 px-4 pb-28 pt-4">
        @if(session('success'))
            {{-- A message that appears after an action has to be announced, or
                 a screen-reader user submits a form and hears nothing. --}}
            <div role="status" aria-live="polite" class="portal-card mb-4 p-3 text-sm"
                 style="background: color-mix(in oklab, var(--brand-success) 12%, var(--portal-surface));
                        border-color: color-mix(in oklab, var(--brand-success) 35%, var(--portal-surface));">
                {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div role="alert" class="portal-card mb-4 p-3 text-sm"
                 style="background: color-mix(in oklab, var(--brand-danger) 12%, var(--portal-surface));
                        border-color: color-mix(in oklab, var(--brand-danger) 35%, var(--portal-surface));">
                {{ session('error') }}
            </div>
        @endif

        {{ $slot }}
    </main>

    {{-- Five tabs, capped. Each is a real URL so a deep link and the native
         shell's back button both behave. --}}
    <nav class="pb-safe fixed inset-x-0 bottom-0 z-40 mx-auto max-w-2xl border-t"
         style="background: var(--portal-surface); border-color: var(--portal-border);"
         aria-label="{{ __('التنقل الرئيسي') }}">
        <ul class="flex items-stretch justify-around gap-1 px-2 pt-1.5">
            @foreach([
                ['portal.home', 'الرئيسية', 'home'],
                ['portal.training', 'التدريب', 'training'],
                ['portal.payments', 'المدفوعات', 'payments'],
                ['portal.academy', 'الأكاديمية', 'academy'],
                ['portal.account', 'حسابي', 'account'],
            ] as [$route, $label, $icon])
                @php $isActive = request()->routeIs($route . '*'); @endphp
                <li class="flex-1">
                    <a href="{{ route($route) }}" wire:navigate
                       @class(['flex flex-col items-center gap-1 rounded-xl px-1 py-1.5 transition-colors'])
                       style="color: {{ $isActive ? 'var(--portal-link)' : 'var(--portal-muted)' }};"
                       @if($isActive) aria-current="page" @endif>
                        <span class="tap-target !min-h-9">
                            <x-portal.icon :name="$icon" class="h-6 w-6"
                                           :width="$isActive ? '2.1' : '1.6'" />
                        </span>
                        <span class="text-[10px] {{ $isActive ? 'font-bold' : 'font-medium' }}">{{ __($label) }}</span>
                    </a>
                </li>
            @endforeach
        </ul>
    </nav>
</div>
@livewireScripts
</body>
</html>
