"use client";

import Link from "next/link";
import {
  createContext,
  useContext,
  type ComponentProps,
  type ReactNode,
} from "react";
import { joinStudioPath } from "@/core/tenant/studio-path";

const SitePathContext = createContext("");

export function SitePathProvider({
  basePath,
  children,
}: {
  basePath: string;
  children: ReactNode;
}) {
  return (
    <SitePathContext.Provider value={basePath}>
      {children}
    </SitePathContext.Provider>
  );
}

export function useStudioBasePath() {
  return useContext(SitePathContext);
}

/** Tenant slug when browsing via /studio/{slug} path preview; empty on subdomain. */
export function useStudioSlug() {
  const basePath = useContext(SitePathContext);
  const match = basePath.match(/^\/studio\/([^/]+)/);
  return match?.[1]?.toLowerCase() ?? "";
}

export function useStudioHref(href: string) {
  return joinStudioPath(useContext(SitePathContext), href);
}

type SiteLinkProps = Omit<ComponentProps<typeof Link>, "href"> & {
  href: string;
};

/** Next Link that respects `/studio/{slug}` LAN path preview prefix. */
export function SiteLink({ href, ...props }: SiteLinkProps) {
  const basePath = useContext(SitePathContext);
  return <Link href={joinStudioPath(basePath, href)} {...props} />;
}
