@php
    use App\Models\MenuPermission;
    use App\Models\MenuConfig;
    use Filament\Facades\Filament;

    // 获取当前用户
    $user = Filament::getCurrentPanel()->auth()->user();

    // 检查是否是管理员
    $isAdmin = $user && (
        $user->role === 'admin' ||
        $user->username === '17689974321'
    );

    if (!$isAdmin) {
        return;
    }

    // 获取当前路径
    $currentPath = request()->path();
    $menuKey = null;

    // 根据路径映射到菜单键
    $menuMappings = [
        'admin/ocr-paper-grading' => 'ocr-paper-grading',
        'admin/exam-analysis' => 'exam-analysis',
        'admin/dashboard' => 'dashboard',
        'admin/exam-history' => 'exam-history',
        'admin/intelligent-exam-generation' => 'intelligent-exam-generation',
        'admin/knowledge-graph' => 'knowledge-graph',
        'admin/student-management' => 'student-management',
        'admin/teacher-management' => 'teacher-management',
    ];

    // 查找匹配的菜单键
    foreach ($menuMappings as $path => $key) {
        if (str_contains($currentPath, $path)) {
            $menuKey = $key;
            break;
        }
    }

    if (!$menuKey) {
        return;
    }

    // 检查该菜单是否纳入管理系统
    $menuConfig = MenuConfig::where('menu_key', $menuKey)->first();
    if (!$menuConfig || !$menuConfig->is_managed || !$menuConfig->is_active) {
        return;
    }

    // 获取用户ID
    $userId = $user->teacher_id ?? $user->id;

    // 获取当前菜单可见性
    $isVisible = MenuPermission::isMenuVisible($userId, $menuKey);

    // 获取菜单显示名称
    $menuLabel = $menuConfig->menu_label ?? $menuKey;
@endphp

<div x-data="menuToggle()" class="flex items-center gap-3">
    <!-- 菜单状态指示 -->
    <div class="flex items-center gap-2 text-sm">
        <span class="text-gray-600 dark:text-gray-400">菜单:</span>
        <span x-text="isVisible ? '显示' : '隐藏'" class="font-medium"
              :class="isVisible ? 'text-success-600' : 'text-danger-600'">
        </span>
    </div>

    <!-- DaisyUI Toggle 开关 -->
    <input
        type="checkbox"
        class="toggle toggle-primary toggle-sm"
        :checked="{{ $isVisible ? 'true' : 'false' }}"
        @change="toggleMenu('{{ $menuKey }}', '{{ $userId }}', $event.target.checked)"
    />
</div>

<script>
    function menuToggle() {
        return {
            isVisible: {{ $isVisible ? 'true' : 'false' }},

            async toggleMenu(menuKey, userId, visible) {
                try {
                    const response = await fetch('{{ route('filament.admin.auth.toggle-menu-visibility') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        },
                        body: JSON.stringify({
                            menu_key: menuKey,
                            user_id: userId,
                            is_visible: visible
                        })
                    });

                    if (response.ok) {
                        this.isVisible = visible;

                        // 显示成功通知
                        if (window.Filament && Filament.notify) {
                            Filament.notify('success', '菜单已' + (visible ? '显示' : '隐藏'));
                        }
                    } else {
                        throw new Error('操作失败');
                    }
                } catch (error) {
                    console.error('Error:', error);

                    // 显示错误通知
                    if (window.Filament && Filament.notify) {
                        Filament.notify('danger', '操作失败，请重试');
                    }

                    // 恢复原状态
                    this.isVisible = !visible;
                }
            }
        }
    }
</script>
