@props(['menu', 'depth' => 0])

@php
    $sidebarMenuService = app(\App\Services\SidebarMenuService::class);
    $isActive = $sidebarMenuService->isMenuActive($menu);
    $paddingLeft = $depth > 0 ? ($depth * 0.75 + 0.75) . 'rem' : '0.75rem';

    $url = $menu->url;
    if ($menu->is_external && $menu->external_url) {
        $url = $menu->external_url;
    }

    // 라우트명이 있으면 라우트 URL 사용
    $routeName = $menu->getRouteName();
    if ($routeName && !str_contains($routeName, '*') && \Route::has($routeName)) {
        $url = route($routeName);
    }

    $activeClass = $isActive
        ? 'bg-primary text-white hover:bg-primary'
        : 'text-gray-700 hover:bg-gray-100';

    $target = $menu->is_external ? '_blank' : '_self';

    // 메뉴 뱃지 확인 (라우트명 또는 URL 기준)
    $badgeCount = 0;
    if (isset($menuBadges)) {
        // 라우트명으로 찾기
        if ($routeName && isset($menuBadges['byRoute'][$routeName])) {
            $badgeCount = $menuBadges['byRoute'][$routeName];
        }
        // URL로 찾기
        elseif ($menu->url && isset($menuBadges['byUrl'][$menu->url])) {
            $badgeCount = $menuBadges['byUrl'][$menu->url];
        }
    }
@endphp

<li>
    <a href="{{ $url }}"
       class="flex items-center gap-2 px-3 py-2 rounded-lg text-sm {{ $activeClass }}"
       style="padding-left: {{ $paddingLeft }}"
       title="{{ $menu->name }}"
       @if($menu->is_external) target="{{ $target }}" rel="noopener noreferrer" hx-boost="false" @endif
    >
        @if($menu->icon)
            <x-sidebar.menu-icon :icon="$menu->icon" />
        @endif
        <span class="sidebar-text flex-1">{{ $menu->name }}</span>
        @if($badgeCount > 0)
            <span class="sidebar-text inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 text-xs font-bold text-white bg-red-500 rounded-full">
                {{ $badgeCount > 99 ? '99+' : $badgeCount }}
            </span>
        @endif
        @if($menu->is_external)
            <x-sidebar.menu-icon icon="external-link" class="w-3 h-3 opacity-50" />
        @endif
    </a>
</li>
