"use client";

import { useContext, type ComponentProps, type ReactNode } from "react";
import Link from "next/link";
import { dashboardRouteForHref } from "@/lib/auth/dashboard-menus";
import { DashboardMenuContext } from "./dashboard-menu-context";

export function DashboardLink({
  href,
  children,
  whenDenied = children,
  ...props
}: ComponentProps<typeof Link> & { whenDenied?: ReactNode }) {
  const routes = useContext(DashboardMenuContext);
  const path = typeof href === "string" ? href : href.pathname;
  const route = path ? dashboardRouteForHref(path) : undefined;
  if (routes && route && !routes.includes(route)) return whenDenied;

  return <Link {...props} href={href} prefetch={routes && route ? false : props.prefetch}>{children}</Link>;
}
