<div class="overflow-x-auto">
    <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
            <tr>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">순번</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">메뉴명</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">URL</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">순서</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">조회</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">생성</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">수정</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">삭제</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">승인</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">내보내기</th>
                <th class="px-3 py-2 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider whitespace-nowrap">관리</th>
            </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
            @php
                $permissionTypes = ['view', 'create', 'update', 'delete', 'approve', 'export', 'manage'];
            @endphp
            @forelse($menus as $index => $menu)
            <tr class="menu-row"
                data-menu-id="{{ $menu->id }}"
                data-parent-id="{{ $menu->parent_id ?? '' }}"
                data-depth="{{ $menu->depth ?? 0 }}">
                <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900 text-center">
                    {{ $index + 1 }}
                </td>
                <td class="px-3 py-2 whitespace-nowrap">
                    <div class="flex items-center gap-1.5" style="padding-left: {{ (($menu->depth ?? 0) * 1.25) }}rem;">
                        {{-- 트리 구조 표시 --}}
                        @if(($menu->depth ?? 0) > 0)
                            <span class="text-gray-300 text-xs font-mono flex-shrink-0">└─</span>
                        @endif

                        {{-- 폴더/아이템 아이콘 (폴더는 클릭으로 접기/펼치기) --}}
                        @if($menu->has_children)
                            <button type="button"
                                    onclick="toggleChildren({{ $menu->id }})"
                                    class="toggle-btn flex items-center text-blue-500 hover:text-blue-700 focus:outline-none"
                                    data-menu-id="{{ $menu->id }}">
                                <svg class="w-4 h-4 transform transition-transform flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                                </svg>
                                <svg class="w-3 h-3 ml-0.5 transform transition-transform chevron-icon" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"/>
                                </svg>
                            </button>
                        @else
                            <svg class="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                        @endif

                        {{-- 메뉴명 --}}
                        <span class="text-sm {{ ($menu->depth ?? 0) === 0 ? 'font-semibold text-gray-900' : 'font-medium text-gray-700' }}">
                            {{ $menu->name }}
                        </span>
                    </div>
                </td>
                <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-500">
                    <span class="truncate max-w-xs inline-block" title="{{ $menu->url }}">
                        {{ $menu->url }}
                    </span>
                </td>
                <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900 text-center">
                    {{ $menu->sort_order }}
                </td>
                @foreach($permissionTypes as $type)
                @php
                    // 권한 데이터 추출
                    $permData = $permissions[$menu->id][$type] ?? ['effective' => null, 'source' => null, 'personal' => null];
                    $effective = $permData['effective'] ?? null;
                    $source = $permData['source'] ?? null;
                    $personal = $permData['personal'] ?? null;

                    // 스타일 결정
                    // - 개인 DENY: 빨간색 (최우선)
                    // - 개인 ALLOW: 녹색
                    // - 역할 권한: 보라색
                    // - 부서 권한: 파란색
                    // - 미설정: 회색
                    if ($personal === 'deny') {
                        $bgClass = 'bg-red-100 text-red-600 hover:bg-red-200 focus:ring-red-500';
                        $icon = 'deny';
                        $title = '개인 거부 (클릭: 미설정으로 변경)';
                    } elseif ($personal === 'allow') {
                        $bgClass = 'bg-green-100 text-green-600 hover:bg-green-200 focus:ring-green-500';
                        $icon = 'allow';
                        $title = '개인 허용 (클릭: 거부로 변경)';
                    } elseif ($source === 'role') {
                        $bgClass = 'bg-purple-100 text-purple-600 hover:bg-purple-200 focus:ring-purple-500';
                        $icon = 'allow';
                        $title = '역할 권한 (클릭: 개인 거부로 오버라이드)';
                    } elseif ($source === 'department') {
                        $bgClass = 'bg-blue-100 text-blue-600 hover:bg-blue-200 focus:ring-blue-500';
                        $icon = 'allow';
                        $title = '부서 권한 (클릭: 개인 거부로 오버라이드)';
                    } else {
                        $bgClass = 'bg-gray-100 text-gray-400 hover:bg-gray-200 focus:ring-gray-400';
                        $icon = 'none';
                        $title = '미설정 (클릭: 개인 허용으로 변경)';
                    }
                @endphp
                <td class="px-3 py-2 whitespace-nowrap text-center">
                    <button
                        type="button"
                        class="w-5 h-5 rounded flex items-center justify-center transition-all duration-200 hover:scale-110 focus:outline-none focus:ring-2 focus:ring-offset-1 {{ $bgClass }}"
                        title="{{ $title }}"
                        hx-post="/api/admin/user-permissions/toggle"
                        hx-target="#permission-matrix"
                        hx-include="[name='user_id'],[name='guard_name']"
                        hx-vals='{"menu_id": {{ $menu->id }}, "permission_type": "{{ $type }}"}'
                    >
                        @if($icon === 'allow')
                            {{-- 허용: 체크 아이콘 --}}
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path>
                            </svg>
                        @elseif($icon === 'deny')
                            {{-- 거부: X 아이콘 --}}
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        @else
                            {{-- 미설정: 마이너스 아이콘 --}}
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M20 12H4"></path>
                            </svg>
                        @endif
                    </button>
                </td>
                @endforeach
            </tr>
            @empty
            <tr>
                <td colspan="11" class="px-6 py-12 text-center text-gray-500">
                    활성화된 메뉴가 없습니다.
                </td>
            </tr>
            @endforelse
        </tbody>
    </table>
</div>

{{-- 범례 --}}
<div class="mt-4 flex flex-wrap items-center gap-4 text-sm text-gray-600 px-3 pb-2">
    <span class="font-medium">범례:</span>
    <div class="flex items-center gap-1.5">
        <span class="inline-flex items-center justify-center w-5 h-5 rounded bg-gray-100 text-gray-400">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M20 12H4"></path>
            </svg>
        </span>
        <span>미설정</span>
    </div>
    <div class="flex items-center gap-1.5">
        <span class="inline-flex items-center justify-center w-5 h-5 rounded bg-purple-100 text-purple-600">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path>
            </svg>
        </span>
        <span>역할</span>
    </div>
    <div class="flex items-center gap-1.5">
        <span class="inline-flex items-center justify-center w-5 h-5 rounded bg-blue-100 text-blue-600">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path>
            </svg>
        </span>
        <span>부서</span>
    </div>
    <div class="flex items-center gap-1.5">
        <span class="inline-flex items-center justify-center w-5 h-5 rounded bg-green-100 text-green-600">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path>
            </svg>
        </span>
        <span>개인 허용</span>
    </div>
    <div class="flex items-center gap-1.5">
        <span class="inline-flex items-center justify-center w-5 h-5 rounded bg-red-100 text-red-600">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
        </span>
        <span>개인 거부</span>
    </div>
</div>
