import { createContext, useContext } from "react";
import type { ReactNode } from "react";
import type { ApiClient } from "./client.js";

const ApiClientContext = createContext<ApiClient | null>(null);

export interface ApiClientProviderProps {
  client: ApiClient;
  children: ReactNode;
}

/**
 * Provides the ApiClient instance to the React tree. SSR-aware:
 * on the server, construct per-request with the resolved locale;
 * on the client, share a single instance across the tab.
 */
export function ApiClientProvider({
  client,
  children,
}: ApiClientProviderProps): JSX.Element {
  return (
    <ApiClientContext.Provider value={client}>
      {children}
    </ApiClientContext.Provider>
  );
}

/**
 * Returns the ApiClient from context. Throws if used outside
 * <ApiClientProvider>.
 */
export function useApiClient(): ApiClient {
  const client = useContext(ApiClientContext);
  if (!client) {
    throw new Error(
      "useApiClient() must be used within an <ApiClientProvider>. " +
      "Ensure the root layout wraps the tree with <ApiClientProvider>.",
    );
  }
  return client;
}
