@php
    // Determine if the current dealer (from session or user) is the default dealer.
    static $currentDealerIsDefault = null;
    if ($currentDealerIsDefault === null) {
        $currentDealerIsDefault = false;
        $dealerIdFromSession = session('current_dealer_id');
        $dealerId = $dealerIdFromSession ?: auth()->user()->dealer_id;
        if ($dealerId) {
            $dealer = \App\Models\Dealer::query()->select(['id', 'is_default'])->find($dealerId);
            $currentDealerIsDefault = (bool) optional($dealer)->is_default;
        }
    }

    $defaultDealerOnly = (bool) ($item['default_dealer_only'] ?? false);

    $canView = empty($item['permission_key']) || auth()->user()->can($item['permission_key']);
    if ($canView && $defaultDealerOnly && !$currentDealerIsDefault) {
        $canView = false;
    }
    $children = $item['children'] ?? [];
    $hasChildren = !empty($children);
    $isGroup = (bool) ($item['is_group'] ?? false);
    $routeName = $item['route_name'] ?? null;
    $routePrefix = $item['route_prefix'] ?? null;
    $routeExists = is_string($routeName) && $routeName !== '' && Route::has($routeName);
    $canViewNode = function (array $node) use (&$canViewNode): bool {
        $nodeCanView = empty($node['permission_key']) || auth()->user()->can($node['permission_key']);
        if (!$nodeCanView) {
            return false;
        }

        $nodeChildren = $node['children'] ?? [];
        if (empty($nodeChildren)) {
            return true;
        }

        foreach ($nodeChildren as $nodeChild) {
            if ($canViewNode($nodeChild)) {
                return true;
            }
        }

        // Non-group parents with a route remain visible even if all children are hidden.
        return !((bool) ($node['is_group'] ?? false)) && !empty($node['route_name']);
    };
    $visibleChildren = array_values(array_filter($children, $canViewNode));
    $hasVisibleChildren = !empty($visibleChildren);
    $isNodeActive = function (array $node) use (&$isNodeActive): bool {
        $nodeRoute = $node['route_name'] ?? null;
        if (is_string($nodeRoute) && $nodeRoute !== '' && request()->routeIs($nodeRoute)) {
            return true;
        }

        foreach (($node['children'] ?? []) as $childNode) {
            if ($isNodeActive($childNode)) {
                return true;
            }
        }

        return false;
    };
    $groupActive = $hasChildren && $isNodeActive($item);
    $leafActive = !empty($routeName) && request()->routeIs($routeName);
    $parentActive = $isNodeActive($item);
    $depth = (int) ($depth ?? 0);
    $keyPath = (string) ($keyPath ?? 'root');
    $nodeKey = (string) ($item['key'] ?? $routeName ?? 'item_'.$depth);
    $currentKeyPath = trim($keyPath.'.'.$nodeKey, '.');
    $leftPadding = 10 + ($depth * 12);
    $rightPadding = 10;
    $toggleKey = str_replace('.', '_', $currentKeyPath);
@endphp

@php
    $isDashboardRoot = is_string($routeName) && $routeName === 'dashboard.index';
    $canCollapseDashboard = $isDashboardRoot && (
        auth()->user()->hasSystemAdminRole()
        || auth()->user()->hasAnyRole(['Managing Director', 'Branch Manager', 'Financial Manager', 'F&I'])
    );
    $effectiveHasChildren = $hasVisibleChildren && (!$isDashboardRoot || $canCollapseDashboard);
@endphp

@if($canView)
    @if($effectiveHasChildren)
        <div class="rounded-lg nav-group-container" data-nav-key="{{ $toggleKey }}">
            @php
                // Dashboard root should only be red when its own route is active,
                // not when a child dashboard route is active.
                $dashboardLinkActive = $leafActive;
                $dashboardLinkClasses = $dashboardLinkActive
                    ? 'bg-red-600 text-white font-semibold'
                    : 'text-gray-200 hover:bg-neutral-200 hover:text-black';
            @endphp

            @if($routeName === 'dashboard.index')
                @php
                    // For the personal dashboard (/dashboard), do NOT auto-expand the dropdown.
                    // For department dashboard children (/dashboard/*), auto-expand so the active child is visible.
                    $dashboardForceOpen = ($groupActive && !$leafActive) ? '1' : '0';
                @endphp
                <div
                    class="flex items-stretch overflow-hidden rounded-lg text-sm transition{{ $dashboardLinkActive ? ' shadow-sm' : '' }}"
                    style="padding-right: 0;"
                >
                    <a
                        href="{{ $routeExists ? route($routeName) : '#' }}"
                        class="flex-1 text-left py-3 {{ $dashboardLinkClasses }}"
                        style="padding-left: {{ $leftPadding }}px; padding-right: 8px;"
                        @click="sidebarOpen = false"
                    >
                        {{ $item['label'] }}
                    </a>

                    <button
                        type="button"
                        class="nav-group-toggle flex h-full items-center justify-end w-9 py-3 pb-4 bg-neutral-800 text-white hover:bg-neutral-700 "
                        style="padding-right: {{ $rightPadding }}px;"
                        data-nav-key="{{ $toggleKey }}"
                        data-nav-parent-key="{{ $keyPath }}"
                        data-nav-depth="{{ $depth }}"
                        data-force-open="{{ $dashboardForceOpen }}"
                        aria-label="Toggle {{ $item['label'] }}"
                    >
                        <svg class="h-4 w-4 nav-chevron origin-center transition-transform duration-150 translate-y-0.5 {{ $groupActive ? 'rotate-180' : '' }}" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.169l3.71-3.94a.75.75 0 111.08 1.04l-4.25 4.51a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z" clip-rule="evenodd" />
                        </svg>
                    </button>
                </div>
            @elseif($routeName === 'dashboard.recon.dashboard')
                <div
                    class="flex items-center rounded-lg py-3 text-sm transition text-white hover:bg-neutral-200 hover:text-black"
                    style="padding-left: {{ $leftPadding }}px; padding-right: {{ $rightPadding }}px;"
                >
                    <a
                        href="{{ $routeExists ? route($routeName) : '#' }}"
                        class="flex-1 text-left"
                        @click="sidebarOpen = false"
                    >
                        {{ $item['label'] }}
                    </a>

                    <button
                        type="button"
                        class="nav-group-toggle ms-2 inline-flex items-center justify-center rounded-md px-1 py-0.5 text-white hover:text-black hover:bg-neutral-200"
                        data-nav-key="{{ $toggleKey }}"
                        data-nav-parent-key="{{ $keyPath }}"
                        data-nav-depth="{{ $depth }}"
                        data-force-open="{{ $groupActive ? '1' : '0' }}"
                        aria-label="Toggle {{ $item['label'] }}"
                    >
                        <svg class="h-4 w-4 nav-chevron transition-transform duration-150 {{ $groupActive ? 'rotate-180' : '' }}" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.169l3.71-3.94a.75.75 0 111.08 1.04l-4.25 4.51a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z" clip-rule="evenodd" />
                        </svg>
                    </button>
                </div>
            @else
                @php
                    // Collapsible items should not turn red just because a child is active.
                    // Use leafActive so only the item's own route (if any) can be red.
                    $groupButtonActive = $leafActive;
                    $groupButtonClasses = $groupButtonActive
                        ? 'bg-red-600 text-white font-semibold shadow-sm'
                        : 'text-white hover:bg-neutral-200 hover:text-black';
                @endphp
                <button
                    type="button"
                    class="nav-group-toggle w-full flex items-center justify-between rounded-lg py-3 text-sm transition {{ $groupButtonClasses }}"
                    data-nav-key="{{ $toggleKey }}"
                    data-nav-parent-key="{{ $keyPath }}"
                    data-nav-depth="{{ $depth }}"
                    data-force-open="{{ $groupActive ? '1' : '0' }}"
                    aria-label="Toggle {{ $item['label'] }}"
                    style="padding-left: {{ $leftPadding }}px; padding-right: {{ $rightPadding }}px;"
                >
                    <span class="nav-label">{{ $item['label'] }}</span>
                    <svg class="h-4 w-4 nav-chevron transition-transform duration-150 {{ $groupActive ? 'rotate-180' : '' }}" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.169l3.71-3.94a.75.75 0 111.08 1.04l-4.25 4.51a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z" clip-rule="evenodd" />
                    </svg>
                </button>
            @endif

            <div class="nav-children mt-1 space-y-1 {{ $groupActive ? '' : 'hidden' }}" data-nav-key="{{ $toggleKey }}">
                @foreach($visibleChildren as $child)
                    @include('layouts.partials.nav-item', ['item' => $child, 'depth' => $depth + 1, 'keyPath' => $currentKeyPath])
                @endforeach
            </div>
            @if($depth === 0)
                <div
                    class="nav-group-divider mt-2 border-t-2 border-red-600/80 {{ $groupActive ? '' : 'hidden' }}"
                    data-nav-divider-key="{{ $toggleKey }}"
                    style="margin-left: {{ $leftPadding }}px; margin-right: 16px;"
                ></div>
            @endif
        </div>
    @elseif(!$isGroup && !empty($routeName))
        <a
            href="{{ $routeExists ? route($routeName) : '#' }}"
            class="block rounded-lg py-2.5 my-0.5 text-sm transition {{ ($leafActive || $parentActive) ? 'bg-red-600 text-white font-semibold shadow-sm' : 'text-gray-200 hover:bg-neutral-200 hover:text-black' }}"
            style="padding-left: {{ $leftPadding }}px; padding-right: {{ $rightPadding }}px;"
            @click="sidebarOpen = false"
        >
            {{ $item['label'] }}
        </a>
    @endif
@endif
