"use client";

import type { Link } from "@/i18n/navigation";
import { type ComponentProps, createContext, use } from "react";

type Href = ComponentProps<typeof Link>["href"];

export type NavItem = { href: Href; label: string };

type NavItemsCtx = {
  items: ReadonlyArray<NavItem>;
  cta: NavItem;
  /**
   * `/${useSelectedLayoutSegment()}` — the *internal* segment (`/about-us`,
   * never `/a-propos`), thanks to the rewrite in `src/proxy.ts`, so comparing
   * it to `item.href` works in every locale.
   */
  currentPath: string;
};

const NavItemsContext = createContext<NavItemsCtx | null>(null);

/**
 * The header nav list crossed the RSC → client boundary twice — once as a prop
 * of `HeaderNavBar`, once as a prop of `MobileMenuPanel` — duplicating eight
 * `{href,label}` objects in the Flight payload on every navigation. It is now
 * serialised once, into `HeaderShell`, and read from here by both consumers.
 *
 * `currentPath` rides along for the same reason: `HeaderShell` owns the single
 * `useSelectedLayoutSegment()` subscription, instead of the bar and the CTA
 * each opening their own.
 */
export const NavItemsProvider = NavItemsContext.Provider;

export function useNavItems(): NavItemsCtx {
  const ctx = use(NavItemsContext);
  if (!ctx) {
    throw new Error("useNavItems must be used within HeaderShell");
  }
  return ctx;
}
