@php
    $currentUser = auth()->user();
    $initials = collect(preg_split('/\s+/', trim($currentUser?->name ?? 'User')))
        ->filter()
        ->take(2)
        ->map(fn ($part) => mb_strtoupper(mb_substr($part, 0, 1)))
        ->implode('');

    $personalUnreadCount = $currentUser?->unreadNotifications()->count() ?? 0;
    $managementAlertCount = 0;
    $failedDeliveryCount = 0;

    if ($currentUser) {
        $branchAccess = app(\App\Services\BranchAccessService::class);

        if ($currentUser->can('management-alerts.view')) {
            $alertQuery = \App\Models\ManagementAlert::query()->whereIn('status', ['open', 'acknowledged']);
            $branchAccess->constrainBranchOwnedQuery($alertQuery, $currentUser);
            $managementAlertCount = $alertQuery->count();
        }

        if ($currentUser->can('notifications.view')) {
            $failureQuery = \App\Models\ReminderNotificationLog::query()->where('status', 'failed');
            $branchAccess->constrainBranchOwnedQuery($failureQuery, $currentUser);
            $failedDeliveryCount = $failureQuery->count();
        }
    }

    $notificationAttentionCount = $personalUnreadCount + $managementAlertCount + $failedDeliveryCount;
@endphp
<header class="mf-topbar sticky top-0 z-30 flex items-center border-b border-border bg-background/95 px-4 backdrop-blur lg:px-6">
    <div class="flex min-w-0 flex-1 items-center gap-3">
        <button type="button" data-sidebar-toggle class="mf-btn mf-icon-btn" aria-label="{{ __('ui.open_navigation') }}" aria-expanded="true">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 6h16M4 12h16M4 18h16"/></svg>
        </button>
        <div class="hidden min-w-0 sm:block">
            <div class="flex items-center gap-2 text-xs text-muted-foreground">
                <span>{{ __('ui.microfinance') }}</span><span>/</span><span class="text-foreground">@yield('page-label', __('ui.dashboard'))</span>
            </div>
        </div>
    </div>

    <div class="flex items-center gap-2">
        @can('search.use')
        <form method="GET" action="{{ route('global-search.index') }}" class="relative hidden md:block" data-global-search-form>
            <svg class="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" style="left:10px" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
            <input type="search" name="q" value="{{ request()->routeIs('global-search.*') ? request('q') : '' }}" class="mf-input h-9 w-64 pl-8 pr-12 text-xs" style="padding: 0 30px;" placeholder="{{ __('ui.search_records') }}" autocomplete="off" aria-label="{{ __('ui.global_search') }}" data-global-search-input>
            <span class="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground" style="right:10px">⌘ K</span>
        </form>
        <a href="{{ route('global-search.index') }}" class="mf-btn mf-icon-btn md:hidden" aria-label="{{ __('ui.global_search') }}">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
        </a>
        @endcan

        @if(($availableLanguages ?? collect())->count() > 1)
            <form method="POST" action="{{ route('locale.switch') }}" class="hidden sm:block">
                @csrf
                <label class="sr-only" for="topbar-locale">{{ __('ui.language') }}</label>
                <select id="topbar-locale" name="locale" class="mf-input h-9 min-w-24 py-0 text-xs" onchange="this.form.submit()" aria-label="{{ __('ui.language') }}">
                    @foreach($availableLanguages as $language)
                        <option value="{{ $language->code }}" @selected(app()->getLocale() === $language->code)>{{ $language->native_name ?: $language->name }}</option>
                    @endforeach
                </select>
            </form>
        @endif

        <button type="button" data-theme-toggle class="mf-btn mf-icon-btn" aria-label="{{ __('ui.toggle_theme') }}">
            <svg data-moon viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/></svg>
            <svg data-sun viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="hidden"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
        </button>
        <a href="{{ route('notification-center.index') }}" class="mf-btn mf-icon-btn relative" style="overflow: visible;" aria-label="{{ __('ui.notification_center') }}{{ $notificationAttentionCount > 0 ? ', '.$notificationAttentionCount.' items need attention' : '' }}" title="{{ $notificationAttentionCount > 0 ? number_format($notificationAttentionCount).' item(s) need attention' : __('ui.notification_center') }}">
            <span class="relative flex items-center justify-center" style="width:20px;height:20px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="width:19px;height:19px;">
                    <path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9"/>
                    <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
                </svg>
                @if($notificationAttentionCount > 0)
                    <span class="absolute flex items-center justify-center rounded-full bg-destructive font-semibold leading-none text-destructive-foreground" style="top:-8px;right:-9px;height:17px;min-width:17px;padding:0 4px;font-size:9px;box-shadow:0 0 0 2px var(--background);">{{ $notificationAttentionCount > 99 ? '99+' : $notificationAttentionCount }}</span>
                @endif
            </span>
        </a>

        <details class="mf-user-menu relative">
            <summary class="flex h-9 cursor-pointer list-none items-center gap-2 rounded-md border border-border px-2 transition-colors hover:bg-muted">
                <span class="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-[9px] font-semibold text-primary-foreground">{{ $initials ?: 'U' }}</span>
                <span class="hidden max-w-32 truncate text-xs font-medium sm:inline">{{ $currentUser?->name }}</span>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="hidden h-3.5 w-3.5 text-muted-foreground sm:block"><path d="m6 9 6 6 6-6"/></svg>
            </summary>
            <div class="mf-user-dropdown">
                <div class="border-b border-border px-3 py-2.5">
                    <div class="truncate text-xs font-semibold text-foreground">{{ $currentUser?->name }}</div>
                    <div class="mt-0.5 truncate text-[11px] text-muted-foreground">{{ $currentUser?->email }}</div>
                </div>
                @if(($availableLanguages ?? collect())->count() > 1)
                    <form method="POST" action="{{ route('locale.switch') }}" class="border-b border-border p-2 sm:hidden">
                        @csrf
                        <label class="mf-field-label" for="mobile-locale">{{ __('ui.language') }}</label>
                        <select id="mobile-locale" name="locale" class="mf-input text-xs" onchange="this.form.submit()">
                            @foreach($availableLanguages as $language)
                                <option value="{{ $language->code }}" @selected(app()->getLocale() === $language->code)>{{ $language->native_name ?: $language->name }}</option>
                            @endforeach
                        </select>
                    </form>
                @endif
                <div class="p-1.5 pb-0">
                    <a href="{{ route('notification-center.index') }}" class="mf-user-dropdown-item">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
                        {{ __('ui.notifications') }} @if($notificationAttentionCount > 0)<span class="ml-auto text-[10px] text-destructive">{{ $notificationAttentionCount }}</span>@endif
                    </a>
                    <a href="{{ route('security.show') }}" class="mf-user-dropdown-item">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/><path d="m9 12 2 2 4-4"/></svg>
                        {{ __('ui.security') }}
                    </a>
                </div>
                <form method="POST" action="{{ route('logout') }}" class="p-1.5">
                    @csrf
                    <button type="submit" class="mf-user-dropdown-item">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="m16 17 5-5-5-5M21 12H9"/></svg>
                        {{ __('ui.sign_out') }}
                    </button>
                </form>
            </div>
        </details>
    </div>
</header>
