'use client';

import { ReactNode } from 'react';
import { Lock } from 'lucide-react';
import { useAuthStore } from '@/stores/useAuthStore';
import { useMemberStore } from '@/stores/useMemberStore';
import { hasPermission } from '@/lib/permissions';

/**
 * 当前登录用户对某权限点的判定
 * 未登录 / 找不到 role 时一律 false（最严格只读）
 */
export function useHasPermission(permission: string): boolean {
  const user = useAuthStore((s) => s.user);
  const role = useMemberStore((s) => s.roles.find((r) => r.id === user?.roleId));
  return hasPermission(role, permission);
}

/**
 * 路由级拦截：包裹整页，无权限显示 AccessDenied
 */
export function RouteGuard({ permission, children }: { permission: string; children: ReactNode }) {
  const allowed = useHasPermission(permission);
  if (!allowed) return <AccessDenied />;
  return <>{children}</>;
}

/**
 * 按钮级拦截：无权限渲染 fallback（默认 null）
 */
export function PermissionGuard({
  permission,
  fallback = null,
  children,
}: {
  permission: string;
  fallback?: ReactNode;
  children: ReactNode;
}) {
  const allowed = useHasPermission(permission);
  if (!allowed) return <>{fallback}</>;
  return <>{children}</>;
}

/**
 * 路由级"无权访问"占位
 */
export function AccessDenied() {
  return (
    <div className="flex h-full items-center justify-center bg-[var(--bg)]">
      <div className="flex flex-col items-center gap-3 rounded-2xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] px-12 py-16">
        <Lock className="h-8 w-8 text-[var(--ink-muted)]" strokeWidth={1.5} />
        <p className="text-[14px] font-medium text-[var(--ink-soft)]">无权访问该模块</p>
        <p className="text-[12px] text-[var(--ink-muted)]">请联系管理员开通对应权限</p>
      </div>
    </div>
  );
}
