@props(['groups' => []])

@php
    /**
     * Resolve a nav entry into an absolute URL.
     * Honours 'route' (named route) first, then 'href' (raw path/URL).
     * Returns null if a declared route does not exist — so we can
     * skip broken entries instead of rendering dead links.
     */
    $resolveUrl = function (array $entry): ?string {
        if (! empty($entry['route'])) {
            if (! \Illuminate\Support\Facades\Route::has($entry['route'])) {
                return null;
            }
            return route($entry['route'], $entry['route_params'] ?? []);
        }

        $href = $entry['href'] ?? null;
        if ($href === null || $href === '') {
            return null;
        }

        if ($href === '#' || str_starts_with($href, 'http://') || str_starts_with($href, 'https://') || str_starts_with($href, 'mailto:') || str_starts_with($href, 'tel:')) {
            return $href;
        }

        return url($href);
    };

    $isVisible = fn (array $entry): bool => empty($entry['gate']) || auth()->user()?->can($entry['gate']);
@endphp

<ul {{ $attributes->merge(['class' => 'header-nav-menu d-flex align-items-center gap-2 mb-0 list-unstyled']) }}>
    @foreach ($groups as $group)
        @continue(! $isVisible($group))

        @php
            $visibleItems = array_values(array_filter(
                $group['items'] ?? [],
                fn (array $item) => $isVisible($item) && $resolveUrl($item) !== null,
            ));
        @endphp

        @continue(empty($visibleItems))

        <li class="header-nav-item dropdown">
            <a class="header-nav-link dropdown-toggle" href="#" role="button"
               data-bs-toggle="dropdown" aria-expanded="false">
                <i class="{{ $group['icon'] }} me-1"></i>{{ $group['label'] }}
            </a>
            <ul class="dropdown-menu">
                @foreach ($visibleItems as $item)
                    <li>
                        <a class="dropdown-item" href="{{ $resolveUrl($item) }}">
                            {{ $item['label'] }}
                        </a>
                    </li>
                @endforeach
            </ul>
        </li>
    @endforeach
</ul>
