"use client";

import React from "react";

import { useAuth } from "@/components/auth/authContext";
import ForbiddenView from "@/components/system/ForbiddenView";
import {
	getBranchAccess,
	BRANCH_ACCESS,
} from "@/lib/frontend/rbac/branchAccess";

/**
 * BranchGuard (RHL-021)
 *
 * UI-side RBAC guard for branch-based routes.
 *
 * This guard assumes that AuthProvider already handled session checks and redirects.
 * Therefore:
 * - If the auth state is not authenticated yet, we render children (AuthProvider gating).
 * - If authenticated, we enforce branch-level RBAC for role="branch".
 */
export default function BranchGuard({ branch, children }) {
	const { status, user } = useAuth();

	const access = React.useMemo(() => {
		if (status !== "authenticated") return BRANCH_ACCESS.ALLOWED;
		return getBranchAccess(user, branch);
	}, [status, user, branch]);

	if (access === BRANCH_ACCESS.FORBIDDEN) {
		return <ForbiddenView attemptedBranch={branch} />;
	}

	return children;
}
