@php
$navigation = [
    ['label' => 'لوحة التحكم', 'route' => 'dashboard', 'icon' => 'home', 'permission' => 'dashboard.view'],
    ['label' => 'بوابة ولي الأمر', 'route' => 'guardian.dashboard', 'icon' => 'user-group', 'permission' => 'dashboard.view', 'role' => 'parent'],
    ['label' => 'مكتب الاستقبال', 'route' => 'receptionist.dashboard', 'icon' => 'reception', 'permission' => 'participants.list'],

    ['section' => 'المشاركين', 'items' => [
        ['label' => 'المشاركين', 'route' => 'participants.list', 'icon' => 'users', 'permission' => 'participants.list'],
        ['label' => 'استيراد مشتركين', 'route' => 'participants.import', 'icon' => 'document-text', 'permission' => 'participants.create'],
        ['label' => 'الأشخاص', 'route' => 'people.list', 'icon' => 'user-group', 'permission' => 'participants.list'],
    ]],

    ['section' => 'التدريب', 'items' => [
        ['label' => 'الأنشطة', 'route' => 'activities.list', 'icon' => 'bolt', 'permission' => 'activities.list'],
        ['label' => 'البرامج', 'route' => 'programs.list', 'icon' => 'academic-cap', 'permission' => 'programs.list'],
        ['label' => 'المجموعات', 'route' => 'groups.list', 'icon' => 'user-group', 'permission' => 'groups.list'],
        ['label' => 'التسجيلات', 'route' => 'enrollments.list', 'icon' => 'clipboard-check', 'permission' => 'enrollments.list'],
        ['label' => 'قائمة الانتظار', 'route' => 'enrollments.waitlist', 'icon' => 'clock', 'permission' => 'enrollments.list'],
        ['label' => 'نقل مشترك', 'route' => 'enrollments.transfer', 'icon' => 'truck', 'permission' => 'enrollments.create'],
        ['label' => 'التقييمات', 'route' => 'evaluations.list', 'icon' => 'chart-bar', 'permission' => 'evaluations.list'],
        ['label' => 'التعيينات', 'route' => 'assignments.list', 'icon' => 'calendar', 'permission' => 'assignments.list'],
    ]],

    ['section' => 'الحضور والجدول', 'items' => [
        ['label' => 'تسجيل الحضور', 'route' => 'attendance.list', 'icon' => 'clipboard-check', 'permission' => 'attendance.mark'],
        ['label' => 'حضور سريع', 'route' => 'attendance.quick', 'icon' => 'check-badge', 'permission' => 'attendance.mark'],
        ['label' => 'الجدول الأسبوعي', 'route' => 'schedule.weekly', 'icon' => 'calendar-days', 'permission' => 'schedules.view'],
        ['label' => 'لوحة المدرب', 'route' => 'trainer.dashboard', 'icon' => 'user', 'permission' => 'attendance.mark'],
    ]],

    ['section' => 'الإيفنتات', 'items' => [
        ['label' => 'الإيفنتات', 'route' => 'events.list', 'icon' => 'calendar', 'permission' => 'events.list'],
        ['label' => 'إنشاء إيفنت', 'route' => 'events.create', 'icon' => 'plus-circle', 'permission' => 'events.create'],
    ]],

    ['section' => 'الموارد البشرية', 'items' => [
        ['label' => 'الموظفين', 'route' => 'employees.list', 'icon' => 'briefcase', 'permission' => 'employees.list'],
        ['label' => 'المدربين', 'route' => 'trainers.list', 'icon' => 'academic-cap', 'permission' => 'trainers.list'],
        ['label' => 'الرواتب', 'route' => 'payroll.dashboard', 'icon' => 'banknotes', 'permission' => 'payroll.manage'],
        ['label' => 'السلف', 'route' => 'payroll.advances', 'icon' => 'arrow-trending-up', 'permission' => 'payroll.manage'],
    ]],

    ['section' => 'المالية', 'items' => [
        ['label' => 'النظرة المالية', 'route' => 'financial.overview', 'icon' => 'chart-bar', 'permission' => 'invoices.list'],
        ['label' => 'الفواتير', 'route' => 'invoices.list', 'icon' => 'document', 'permission' => 'invoices.list'],
        ['label' => 'المصروفات', 'route' => 'expenses.list', 'icon' => 'banknotes', 'permission' => 'expenses.create'],
        ['label' => 'إيجارات المنشآت', 'route' => 'expenses.rent.list', 'icon' => 'building-office', 'permission' => 'facilities.update'],
        ['label' => 'المحافظ', 'route' => 'wallets.list', 'icon' => 'wallet', 'permission' => 'wallets.list'],
        ['label' => 'جلسات الكاشير', 'route' => 'cash-sessions.list', 'icon' => 'calculator', 'permission' => 'cash_sessions.list'],
    ]],

    ['section' => 'نقطة البيع', 'items' => [
        ['label' => 'نقطة البيع', 'route' => 'pos.terminal', 'icon' => 'shopping-cart', 'permission' => 'pos.sell'],
        ['label' => 'سجل المبيعات', 'route' => 'pos.history', 'icon' => 'clock', 'permission' => 'pos.list'],
    ]],

    ['section' => 'التسعير', 'items' => [
        ['label' => 'الأسعار الأساسية', 'route' => 'pricing.base-prices', 'icon' => 'tag', 'permission' => 'pricing.list'],
        ['label' => 'قواعد التسعير', 'route' => 'pricing.rules', 'icon' => 'adjustments-horizontal', 'permission' => 'pricing.list'],
        ['label' => 'العروض والكوبونات', 'route' => 'pricing.promotions', 'icon' => 'gift', 'permission' => 'pricing.list'],
    ]],

    ['section' => 'المخزون', 'items' => [
        ['label' => 'المنتجات', 'route' => 'inventory.products', 'icon' => 'cube', 'permission' => 'inventory.list'],
        ['label' => 'المستودعات', 'route' => 'inventory.warehouses', 'icon' => 'building-storefront', 'permission' => 'inventory.list'],
        ['label' => 'الحركات', 'route' => 'inventory.movements', 'icon' => 'truck', 'permission' => 'inventory.list'],
        ['label' => 'أوامر الشراء', 'route' => 'inventory.purchase-orders', 'icon' => 'document', 'permission' => 'inventory.list'],
        ['label' => 'الأطقم', 'route' => 'inventory.kits', 'icon' => 'gift', 'permission' => 'inventory.list'],
        ['label' => 'جرد المخزون', 'route' => 'inventory.stock-counts', 'icon' => 'clipboard-document-list', 'permission' => 'inventory.list'],
        ['label' => 'التسويات', 'route' => 'inventory.adjustments', 'icon' => 'clipboard-document-list', 'permission' => 'inventory.adjust'],
        ['label' => 'تسليم الأساسيات', 'route' => 'inventory.essential-deliveries', 'icon' => 'hand-raised', 'permission' => 'inventory.list'],
    ]],

    ['section' => 'المنشآت', 'items' => [
        ['label' => 'المنشآت', 'route' => 'facilities.list', 'icon' => 'building-office', 'permission' => 'facilities.list'],
        ['label' => 'جدولة المنشآت', 'route' => 'facilities.schedule-builder', 'icon' => 'calendar-days', 'permission' => 'schedules.manage'],
        ['label' => 'تعيين المساحات', 'route' => 'facilities.space-assignment', 'icon' => 'grid', 'permission' => 'facilities.manage_layouts'],
    ]],

    ['section' => 'واتساب', 'items' => [
        ['label' => 'إرسال رسالة', 'route' => 'whatsapp.send', 'icon' => 'chat', 'permission' => 'notifications.manage'],
        ['label' => 'إرسال قالب', 'route' => 'whatsapp.templates', 'icon' => 'document-text', 'permission' => 'notifications.manage'],
        ['label' => 'سجل الرسائل', 'route' => 'whatsapp.log', 'icon' => 'eye', 'permission' => 'notifications.manage'],
    ]],

    ['section' => 'الإشعارات والرسائل', 'items' => [
        ['label' => 'مركز الإشعارات', 'route' => 'notifications.center', 'icon' => 'bolt', 'permission' => 'dashboard.view'],
        ['label' => 'رسائل جماعية', 'route' => 'messaging.bulk', 'icon' => 'chat', 'permission' => 'notifications.manage'],
        ['label' => 'القوالب', 'route' => 'notifications.templates', 'icon' => 'document-text', 'permission' => 'notifications.manage'],
        ['label' => 'سجل الإرسال', 'route' => 'notifications.logs', 'icon' => 'eye', 'permission' => 'notifications.manage'],
    ]],

    ['section' => 'الموقع الإلكتروني', 'items' => [
        ['label' => 'صفحات الموقع', 'route' => 'website.manage.pages', 'icon' => 'document-text', 'permission' => 'settings.manage'],
        ['label' => 'قوائم التنقل', 'route' => 'website.manage.menus', 'icon' => 'squares-2x2', 'permission' => 'settings.manage'],
        ['label' => 'أقسام الموقع', 'route' => 'website.manage.sections', 'icon' => 'grid', 'permission' => 'settings.manage'],
        ['label' => 'المظهر والألوان', 'route' => 'website.manage.theme', 'icon' => 'swatch', 'permission' => 'settings.manage'],
        ['label' => 'معرض الصور', 'route' => 'website.manage.gallery', 'icon' => 'photo', 'permission' => 'settings.manage'],
        ['label' => 'آراء العملاء', 'route' => 'website.manage.testimonials', 'icon' => 'chat', 'permission' => 'settings.manage'],
        ['label' => 'الأسئلة الشائعة', 'route' => 'website.manage.faqs', 'icon' => 'document-text', 'permission' => 'settings.manage'],
        ['label' => 'الأخبار', 'route' => 'website.manage.news', 'icon' => 'document', 'permission' => 'settings.manage'],
        ['label' => 'الشركاء', 'route' => 'website.manage.partners', 'icon' => 'building-library', 'permission' => 'settings.manage'],
        ['label' => 'رسائل التواصل', 'route' => 'website.manage.contacts', 'icon' => 'chat', 'permission' => 'settings.manage'],
        ['label' => 'معاينة الموقع', 'route' => 'website.manage.preview', 'icon' => 'eye', 'permission' => 'settings.manage'],
    ]],

    ['section' => 'الإدارة', 'items' => [
        ['label' => 'التقارير', 'route' => 'reports.hub', 'icon' => 'chart-bar', 'permission' => 'reports.view'],
        ['label' => 'المستخدمين', 'route' => 'users.list', 'icon' => 'users', 'permission' => 'users.list'],
        ['label' => 'الأدوار', 'route' => 'roles.list', 'icon' => 'shield-check', 'permission' => 'roles.list'],
        ['label' => 'الفروع', 'route' => 'branches.list', 'icon' => 'building-office', 'permission' => 'branches.list'],
        ['label' => 'سجل المراجعة', 'route' => 'audit.list', 'icon' => 'eye', 'permission' => 'audit.list'],
        ['label' => 'إعدادات الأكاديمية', 'route' => 'settings.academy', 'icon' => 'cog-6-tooth', 'permission' => 'settings.manage'],
        ['label' => 'الهوية البصرية', 'route' => 'settings.branding', 'icon' => 'swatch', 'permission' => 'settings.manage'],
        ['label' => 'إعدادات النظام', 'route' => 'settings.system', 'icon' => 'cog-6-tooth', 'permission' => 'settings.manage'],
        ['label' => 'إعدادات الإيصال', 'route' => 'settings.receipts', 'icon' => 'receipt-percent', 'permission' => 'settings.manage'],
        ['label' => 'معالج الإعداد', 'route' => 'setup.wizard', 'icon' => 'bolt', 'permission' => 'settings.manage'],
        ['label' => 'لوحة المشرف', 'route' => 'admin.panel', 'icon' => 'shield-check', 'permission' => 'settings.manage'],
    ]],
];

$permissionService = app(\App\Domain\Identity\Services\PermissionService::class);
$currentUser = auth()->user();

$userCan = function (string $permission) use ($permissionService, $currentUser): bool {
    return $permissionService->can($currentUser, $permission);
};

$userRole = $currentUser->primaryRole?->slug ?? $currentUser->roles->first()?->slug;

$itemVisible = function (array $item) use ($userCan, $userRole): bool {
    if (!Route::has($item['route']) || !$userCan($item['permission'])) {
        return false;
    }
    if (isset($item['role']) && $userRole !== $item['role']) {
        return false;
    }
    return true;
};
@endphp

<aside dir="rtl"
      :class="sidebarOpen ? 'translate-x-0' : 'translate-x-full lg:translate-x-0'"
      class="fixed top-0 start-0 h-screen w-64 flex flex-col z-40 overflow-hidden transition-transform duration-300 ease-in-out lg:translate-x-0"
      style="background-color: var(--brand-sidebar-bg, #0f172a); color: var(--brand-sidebar-text, #e2e8f0);">
    {{-- Logo + Mobile Close --}}
    <div class="flex items-center justify-between h-16 border-b border-white/10 px-4 shrink-0">
        <div class="flex items-center justify-center flex-1">
            @if(isset($brandLogoDark) && $brandLogoDark && isset($showLogoSidebar) && $showLogoSidebar)
                <img src="{{ Storage::disk('public')->url($brandLogoDark) }}" alt="" class="h-10 max-w-[140px] object-contain">
            @elseif(isset($brandLogo) && $brandLogo && isset($showLogoSidebar) && $showLogoSidebar)
                <img src="{{ Storage::disk('public')->url($brandLogo) }}" alt="" class="h-10 max-w-[140px] object-contain">
            @else
                <h1 class="text-xl font-bold">الكابتن</h1>
            @endif
        </div>
        <button @click="sidebarOpen = false" class="lg:hidden flex items-center justify-center w-10 h-10 rounded-lg text-white/70 hover:text-white hover:bg-white/10 active:bg-white/20 transition-colors" aria-label="{{ __('إغلاق القائمة') }}">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
        </button>
    </div>

    {{-- Navigation --}}
    <nav class="flex-1 overflow-y-auto py-4 ps-3 pe-3 space-y-1">
        @foreach($navigation as $item)
            {{-- Top-level link (no section) --}}
            @if(isset($item['route']))
                @if($itemVisible($item))
                    <a href="{{ route($item['route']) }}"
                       class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-150 hover:bg-white/10 active:bg-white/20 active:scale-[0.97]"
                       style="{{ request()->routeIs($item['route'] . '*') ? 'background-color: var(--brand-sidebar-active, #2563eb); color: #fff;' : 'color: var(--brand-sidebar-text, #e2e8f0);' }}">
                        <x-ui.icon :name="$item['icon']" class="w-5 h-5 shrink-0" />
                        <span>{{ $item['label'] }}</span>
                    </a>
                @endif

            {{-- Section with items (collapsible) --}}
            @elseif(isset($item['section']))
                @php
                    $visibleItems = collect($item['items'])->filter(function ($child) use ($itemVisible) {
                        return $itemVisible($child);
                    });
                    $sectionActive = $visibleItems->contains(function ($child) {
                        return request()->routeIs(Str::before($child['route'], '.index') . '.*');
                    });
                @endphp

                @if($visibleItems->isNotEmpty())
                    <div x-data="{ open: {{ $sectionActive ? 'true' : 'false' }} }" class="pt-3">
                        <button @click="open = !open" class="w-full flex items-center justify-between px-3 py-1.5 rounded-lg hover:bg-white/5 transition-colors group">
                            <p class="text-xs font-semibold uppercase tracking-wider" style="color: var(--brand-sidebar-text, #e2e8f0); opacity: 0.5;">{{ $item['section'] }}</p>
                            <svg class="w-3.5 h-3.5 transition-transform duration-200" :class="open ? 'rotate-180' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="color: var(--brand-sidebar-text, #e2e8f0); opacity: 0.4;"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                        </button>

                        <div x-show="open" x-transition:enter="transition ease-out duration-150" x-transition:enter-start="opacity-0 -translate-y-1" x-transition:enter-end="opacity-100 translate-y-0" x-transition:leave="transition ease-in duration-100" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0" class="mt-1 space-y-0.5">
                            @foreach($visibleItems as $child)
                                <a href="{{ route($child['route']) }}"
                                   class="flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150 hover:bg-white/10 active:bg-white/20 active:scale-[0.97]"
                                   style="{{ request()->routeIs(Str::before($child['route'], '.index') . '.*') ? 'background-color: var(--brand-sidebar-active, #2563eb); color: #fff;' : 'color: var(--brand-sidebar-text, #e2e8f0);' }}">
                                    <x-ui.icon :name="$child['icon']" class="w-5 h-5 shrink-0" />
                                    <span>{{ $child['label'] }}</span>
                                </a>
                            @endforeach
                        </div>
                    </div>
                @endif
            @endif
        @endforeach
    </nav>

    {{-- User info at bottom --}}
    <div class="border-t border-white/10 p-4 shrink-0">
        <div class="flex items-center gap-3">
            <div class="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style="background-color: var(--brand-sidebar-active, #2563eb);">
                <span class="text-sm font-medium text-white">{{ mb_substr(auth()->user()->name_ar ?? auth()->user()->name, 0, 1) }}</span>
            </div>
            <div class="flex-1 min-w-0">
                <p class="text-sm font-medium text-white truncate">{{ auth()->user()->name_ar ?? auth()->user()->name }}</p>
                <p class="text-xs text-slate-400 truncate">{{ auth()->user()->email }}</p>
            </div>
            <form method="POST" action="{{ route('logout') }}">
                @csrf
                <button type="submit" class="w-9 h-9 flex items-center justify-center rounded-lg text-slate-400 hover:text-red-400 hover:bg-white/10 active:bg-white/20 transition-colors" title="{{ __('تسجيل الخروج') }}">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
                </button>
            </form>
        </div>
    </div>
</aside>
