@php
    $roles = session('admin_ctx.role_names', []);
    $menu = [
      [
        'title' => '대시보드',
        'items' => [
          ['label' => '대시보드', 'route' => 'admin.home'],
        ],
      ],
      [
        'title' => '관리자/MY 관리',
        'items' => [
          ['label' => '내 정보', 'route' => 'admin.me'],
          ['label' => '관리자 계정 관리', 'route' => 'admin.admins.index' ,'roles' => ['super_admin']],
        ],
      ],
      [
        'title' => '회원/정책',
        'items' => [
          ['label' => '회원 관리', 'route' => 'admin.members.index','roles' => ['super_admin','support']],
          ['label' => '회원 데이터추출', 'route' => 'admin.marketing.index','roles' => ['super_admin','support']],
          ['label' => '로그인/가입 아이피 필터설정', 'route' => 'admin.join-filters.index','roles' => ['super_admin','support']],
        ],
      ],
      [
        'title' => 'SMS 관리',
        'items' => [
          ['label' => 'SMS 발송', 'route' => 'admin.sms.send','roles' => ['super_admin','finance','product','support']],
          ['label' => 'SMS 발송 이력', 'route' => 'admin.sms.logs','roles' => ['super_admin','finance','product','support']],
          ['label' => 'SMS 템플릿', 'route' => 'admin.templates.index','roles' => ['super_admin','finance','product','support']],
        ],
      ],
      [
        'title' => 'MAIL 관리',
        'items' => [
          ['label' => 'MAIL 발송',      'route' => 'admin.mail.send',            'roles' => ['super_admin','finance','product','support']],
          ['label' => 'MAIL 발송 이력', 'route' => 'admin.mail.logs',            'roles' => ['super_admin','finance','product','support']],
          ['label' => 'MAIL 템플릿',    'route' => 'admin.mail.templates.index', 'roles' => ['super_admin','finance','product','support']],
        ],
      ],
      [
        'title' => '고객지원',
        'items' => [
          ['label' => '공지사항', 'route' => 'admin.notice.index','roles' => ['super_admin','support']],
          ['label' => '1:1 문의', 'route' => 'admin.qna.index','roles' => ['super_admin','support']],
        ],
      ],
      [
        'title' => '상품권 관리',
        'items' => [
          ['label' => '상품 리스트', 'route' => 'admin.products.index','roles' => ['super_admin','product']],
          ['label' => '상품 등록', 'route' => 'admin.products.create','roles' => ['super_admin','product']],
          ['label' => '판매 코드 관리', 'route' => 'admin.sale-codes.index','roles' => ['super_admin','product']],
          ['label' => '핀 번호 관리', 'route' => 'admin.pins.index','roles' => ['super_admin','product']],
          ['label' => '메인 노출 관리', 'route' => 'admin.exposure.index','roles' => ['super_admin','product']],
          ['label' => '결제 수수료/정책', 'route' => 'admin.fees.index','roles' => ['super_admin','product']],
        ],
      ],
      [
        'title' => '매입/정산',
        'items' => [
          ['label' => '핀 매입 현황(출금)', 'route' => 'admin.buyback.index','roles' => ['super_admin','finance']],
          ['label' => '출금 요청 관리', 'route' => 'admin.withdraw.index','roles' => ['super_admin','finance']],
          ['label' => '정산 리포트', 'route' => 'admin.settlement.index','roles' => ['super_admin','finance']],
        ],
      ],
      [
        'title' => '거래/매출',
        'items' => [
          ['label' => '상품권 거래 장부', 'route' => 'admin.ledger.index','roles' => ['super_admin','finance']],
          ['label' => '매출 리포트', 'route' => 'admin.sales.index','roles' => ['super_admin','finance']],
          ['label' => '환불/취소 내역', 'route' => 'admin.refunds.index','roles' => ['super_admin','finance']],
        ],
      ],
      [
        'title' => '시스템 로그',
        'items' => [
          ['label' => '로그인 로그', 'route' => 'admin.logs.login','roles' => ['super_admin','finance','product','support']],
          ['label' => '다날 인증 로그', 'route' => 'admin.logs.danal','roles' => ['super_admin','finance','product','support']],
          ['label' => '결제 로그', 'route' => 'admin.logs.pay','roles' => ['super_admin','finance','product','support']],
          ['label' => '기타 로그', 'route' => 'admin.logs.misc','roles' => ['super_admin','finance','product','support']],
          ['label' => '관리자 활동 로그', 'route' => 'admin.logs.audit','roles' => ['super_admin','finance','product','support']],
        ],
      ],
    ];

    $roleNames = (array) data_get(session('admin_ctx', []), 'role_names', []);
    $isSuper   = in_array('super_admin', $roleNames, true);
@endphp

<nav class="a-nav" data-nav="accordion">
    {{-- ✅ 대시보드는 메뉴 배열에서 빼고 "단일 링크"로만 상단 고정 --}}
    @php
        $dashHas = \Illuminate\Support\Facades\Route::has('admin.home');
        $dashActive = request()->routeIs('admin.home');
    @endphp

    @if($dashHas)
        <a class="a-nav__item a-nav__item--root {{ $dashActive ? 'is-active' : '' }}" href="{{ route('admin.home') }}">
            <span class="a-nav__dot" aria-hidden="true"></span>
            <span class="a-nav__label">대시보드</span>
        </a>
    @else
        <span class="a-nav__item a-nav__item--root is-disabled" title="준비중">
            <span class="a-nav__dot" aria-hidden="true"></span>
            <span class="a-nav__label">대시보드</span>
        </span>
    @endif

    @foreach($menu as $group)
        @php
            // ✅ "대시보드" 그룹은 렌더링에서만 제외 (배열 수정 X)
            if (($group['title'] ?? '') === '대시보드') {
                continue;
            }

            // 그룹 아이템 필터링 (roles 체크)
            $visibleItems = [];
            foreach (($group['items'] ?? []) as $it) {
                $need = $it['roles'] ?? null;

                if ($need === null) { $visibleItems[] = $it; continue; }
                if ($isSuper)       { $visibleItems[] = $it; continue; }

                if (is_array($need) && !empty(array_intersect($need, $roleNames))) {
                    $visibleItems[] = $it;
                }
            }

            // ✅ 현재 라우트 기준으로 "해당 그룹이 열려야 하는지" 선계산
            $groupActive = false;
            foreach ($visibleItems as $it) {
                $routeName = (string)($it['route'] ?? '');
                if ($routeName === '' || !\Illuminate\Support\Facades\Route::has($routeName)) continue;

                $base = preg_replace('/\.index$/', '', $routeName);
                if ($base && (request()->routeIs($base.'.*') || request()->routeIs($base))) {
                    $groupActive = true;
                    break;
                }
            }
        @endphp

        @if(!empty($visibleItems))
            <div class="a-nav__group {{ $groupActive ? 'is-open' : '' }}" data-nav-group>
                {{-- ✅ 타이틀만 기본 노출 + 클릭 시 하위 펼침 --}}
                <button type="button"
                        class="a-nav__titlebtn"
                        data-nav-toggle
                        aria-expanded="{{ $groupActive ? 'true' : 'false' }}">
                    <span class="a-nav__titletext">{{ $group['title'] }}</span>
                    <span class="a-nav__chev" aria-hidden="true"></span>
                </button>

                {{-- ✅ 하위 메뉴(기본 닫힘 / is-open일 때만 펼침) --}}
                <div class="a-nav__items" data-nav-items>
                    @foreach($visibleItems as $it)
                        @php
                            $routeName = (string)($it['route'] ?? '');
                            $has = $routeName !== '' ? \Illuminate\Support\Facades\Route::has($routeName) : false;

                            $base = $routeName !== '' ? preg_replace('/\.index$/', '', $routeName) : '';
                            $isActive = $has && $base !== '' ? (request()->routeIs($base . '.*') || request()->routeIs($base)) : false;
                        @endphp

                        @if($has)
                            <a class="a-nav__item {{ $isActive ? 'is-active' : '' }}" href="{{ route($routeName) }}">
                                <span class="a-nav__dot" aria-hidden="true"></span>
                                <span class="a-nav__label">{{ $it['label'] }}</span>
                            </a>
                        @else
                            <span class="a-nav__item is-disabled" title="준비중">
                                <span class="a-nav__dot" aria-hidden="true"></span>
                                <span class="a-nav__label">{{ $it['label'] }}</span>
                            </span>
                        @endif
                    @endforeach
                </div>
            </div>
        @endif
    @endforeach
</nav>

