"use client";

import { useMemo } from "react";
import { ShieldX } from "lucide-react";
import { useTranslations } from "next-intl";
import { usePathname } from "@/i18n/routing";
import { NAV_GROUPS, type NavItemKey } from "@/lib/sidebar-nav";
import { NAV_REQUIRED_PERMISSION } from "@/lib/permissions";
import { canSeeNavItem } from "@/lib/auth-permissions";
import { permissionsOf } from "@/lib/permissions";
import { useAuthStore } from "@/lib/stores/auth.store";

/** Resolve the nav item key that owns the given pathname (locale already stripped). */
function navKeyForPath(pathname: string): NavItemKey | null {
  for (const group of NAV_GROUPS) {
    for (const item of group.items) {
      if (pathname === item.href || pathname.startsWith(`${item.href}/`)) {
        return item.key;
      }
    }
  }
  return null;
}

/**
 * Page-level access gate for direct-URL navigation. Mirrors the sidebar's
 * visibility rules so a user who types a URL for a page they can't access sees a
 * friendly notice instead of an empty or erroring screen. The API still enforces
 * the real permission server-side.
 */
export function RouteGuard({ children }: { children: React.ReactNode }) {
  const t = useTranslations("access");
  const pathname = usePathname();
  const user = useAuthStore((s) => s.user);
  const hasHydrated = useAuthStore((s) => s._hasHydrated);

  const allowed = useMemo(() => {
    const key = navKeyForPath(pathname);
    // Pages outside the nav map (e.g. detail routes without a gated key) pass through.
    if (!key) return true;
    if (!NAV_REQUIRED_PERMISSION[key]) {
      // No permission mapping — defer to role/branch visibility rules.
      return canSeeNavItem(key, user?.role, user?.branchId ?? null, permissionsOf(user));
    }
    return canSeeNavItem(key, user?.role, user?.branchId ?? null, permissionsOf(user));
  }, [pathname, user]);

  // Avoid flashing the denied panel before the persisted auth state rehydrates.
  if (!hasHydrated) return <>{children}</>;
  if (allowed) return <>{children}</>;

  return (
    <div className="flex min-h-[60vh] flex-col items-center justify-center gap-3 text-center">
      <span className="flex h-14 w-14 items-center justify-center rounded-full bg-red-50 text-[#A32D2D]">
        <ShieldX className="h-7 w-7" aria-hidden />
      </span>
      <h2 className="text-lg font-semibold text-foreground">{t("deniedTitle")}</h2>
      <p className="max-w-sm text-sm text-muted-foreground">{t("deniedBody")}</p>
    </div>
  );
}
