@php
    use App\Enums\ProofStatus;
    use App\Models\SubscriptionPayment;

    $settings = app(\App\Services\SettingsRepository::class);
    $user = auth()->user();

    // Cheap enough to run on every page, and it is the number the team lives by.
    $pending = SubscriptionPayment::where('status', ProofStatus::Pending)->count();

    /*
     * Navigation is data, not markup. Each entry names the capability it
     * needs, so an accountant never sees the staff screen and a support agent
     * never sees the plan editor.
     */
    $sections = [
        [
            'label' => null,
            'items' => [
                ['route' => 'dashboard', 'label' => 'Dashboard', 'icon' => 'home'],
                ['route' => 'payments.queue', 'label' => 'Verification Queue', 'icon' => 'inbox',
                 'can' => 'verify', 'badge' => $pending, 'accent' => true],
            ],
        ],
        [
            'label' => 'Customers',
            'items' => [
                ['route' => 'tenants.index', 'label' => 'Shops', 'icon' => 'building'],
                ['route' => 'subscriptions.index', 'label' => 'Subscriptions', 'icon' => 'sparkles'],
                ['route' => 'invoices.index', 'label' => 'Invoices', 'icon' => 'receipt'],
                ['route' => 'payments.index', 'label' => 'Payment History', 'icon' => 'exchange'],
            ],
        ],
        [
            'label' => 'Catalogue',
            'items' => [
                ['route' => 'products.index', 'label' => 'Products', 'icon' => 'box', 'can' => 'catalog'],
                ['route' => 'plans.index', 'label' => 'Plans & Pricing', 'icon' => 'layers', 'can' => 'catalog'],
                ['route' => 'accounts.index', 'label' => 'Receiving Accounts', 'icon' => 'wallet', 'can' => 'catalog'],
            ],
        ],
        [
            'label' => 'Reports',
            'items' => [
                ['route' => 'reports.revenue', 'label' => 'Revenue', 'icon' => 'chart'],
                ['route' => 'reports.growth', 'label' => 'Growth & Churn', 'icon' => 'trending'],
            ],
        ],
        [
            'label' => 'System',
            'items' => [
                ['route' => 'announcements.index', 'label' => 'Announcements', 'icon' => 'info', 'can' => 'catalog'],
                ['route' => 'staff.index', 'label' => 'Staff Users', 'icon' => 'user-cog', 'can' => 'staff'],
                ['route' => 'activity.index', 'label' => 'Activity Log', 'icon' => 'clock'],
                ['route' => 'settings.index', 'label' => 'Settings', 'icon' => 'cog', 'can' => 'catalog'],
            ],
        ],
    ];


    /*
     * Which single nav entry should light up.
     *
     * Matching "everything under the same module" lights up all four Setup
     * links at once, because they all live under `settings.`. Matching only the
     * exact route leaves nothing lit while you are on products.create.
     *
     * So instead of asking each entry "are you active?", ask which entry is the
     * *best* match for the current route, and light only that one. Specificity
     * wins: an exact hit beats a nested hit, which beats a same-module hit.
     */
    $navRoutes = [];

    foreach ($sections as $section) {
        foreach ($section['items'] as $item) {
            $navRoutes[] = $item['route'];
        }
    }

    $score = function (string $route) : int {
        $current = (string) request()->route()?->getName();

        if ($current === '') {
            return 0;
        }

        if ($current === $route) {
            return 1000;                                    // settings.taxes
        }

        if (str_starts_with($current, $route.'.')) {
            return 500 + substr_count($route, '.');         // settings.receipts.edit
        }

        $module = \Illuminate\Support\Str::beforeLast($route, '.');

        if ($module !== $route && ($current === $module || str_starts_with($current, $module.'.'))) {
            return 1 + substr_count($module, '.');          // products.create -> Products
        }

        return 0;
    };

    $bestRoute = null;
    $bestScore = 0;

    foreach ($navRoutes as $candidate) {
        if (($points = $score($candidate)) > $bestScore) {
            $bestScore = $points;
            $bestRoute = $candidate;
        }
    }

    $isActive = fn (string $route): bool => $route === $bestRoute;

    $visible = function (array $item) use ($user): bool {
        return match ($item['can'] ?? null) {
            'verify' => (bool) $user?->canVerifyPayments(),
            'catalog' => (bool) $user?->canManageCatalog(),
            'tenants' => (bool) $user?->canManageTenants(),
            'staff' => (bool) $user?->canManageStaff(),
            default => true,
        };
    };
@endphp

{{-- Below lg the sidebar collapses off-canvas behind this button. --}}
<button
    type="button"
    @click="open = true"
    class="fixed bottom-5 left-5 z-40 flex h-12 w-12 items-center justify-center rounded-full bg-brand text-white shadow-lg lg:hidden"
    aria-label="Open menu"
>
    <x-ui.icon name="menu" class="h-5 w-5" />
</button>

<div x-show="open" x-cloak @click="open = false" class="fixed inset-0 z-40 bg-slate-900/60 lg:hidden"></div>

<nav
    x-bind:class="open ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'"
    class="sidebar-dark fixed inset-y-0 left-0 z-50 flex w-64 shrink-0 flex-col overflow-y-auto border-r border-slate-800 bg-slate-900 transition-transform lg:static lg:z-auto"
>
    {{-- Brand --}}
    <div class="flex items-center gap-3 border-b border-slate-800 px-5 py-4">
        <div class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand text-sm font-bold text-white">T</div>

        <div class="min-w-0 flex-1">
            <p class="truncate text-sm font-semibold text-white">{{ $settings->string('panel_name', 'Thinkrax Central') }}</p>
            <p class="truncate text-[11px] text-slate-400">{{ $user?->roleLabel() }}</p>
        </div>

        <button type="button" @click="open = false" class="text-slate-400 lg:hidden" aria-label="Close menu">
            <x-ui.icon name="x" class="h-5 w-5" />
        </button>
    </div>

    {{-- Links --}}
    <div class="flex-1 space-y-6 px-3 py-4">
        @foreach ($sections as $section)
            @php $items = array_filter($section['items'], $visible); @endphp

            @continue ($items === [])

            <div>
                @if ($section['label'])
                    <p class="mb-2 px-3 text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                        {{ $section['label'] }}
                    </p>
                @endif

                <div class="space-y-0.5">
                    @foreach ($items as $item)
                        @php $active = $isActive($item['route']); @endphp

                        <a
                            href="{{ route($item['route']) }}"
                            wire:navigate
                            @class(['nav-item', 'nav-item-active' => $active, 'nav-item-idle' => ! $active])
                        >
                            <x-ui.icon :name="$item['icon']" class="h-4 w-4 shrink-0" />
                            <span class="truncate">{{ $item['label'] }}</span>

                            @if (($item['badge'] ?? 0) > 0)
                                <span class="ml-auto rounded-full bg-amber-500 px-1.5 py-0.5 text-[10px] font-bold text-white">
                                    {{ $item['badge'] > 99 ? '99+' : $item['badge'] }}
                                </span>
                            @endif
                        </a>
                    @endforeach
                </div>
            </div>
        @endforeach
    </div>

    <div class="border-t border-slate-800 px-5 py-3 text-[11px] text-slate-500">
        <p>{{ config('thinkrax.company.name') }}</p>
        <p class="mt-0.5">{{ config('thinkrax.company.website') }}</p>
    </div>
</nav>
