import { createContext, useContext } from "react";
import type { ReactNode } from "react";
import type { Logger } from "./types.js";

const LoggerContext = createContext<Logger | null>(null);

export interface LoggerProviderProps {
  logger: Logger;
  children: ReactNode;
}

/**
 * Provides the Logger instance to the React tree. On the server,
 * use a request-scoped child logger (with traceId, locale). On the
 * client, use the shared root logger from createRootLogger().
 */
export function LoggerProvider({
  logger,
  children,
}: LoggerProviderProps): JSX.Element {
  return (
    <LoggerContext.Provider value={logger}>
      {children}
    </LoggerContext.Provider>
  );
}

/**
 * Returns the Logger from context. Throws if used outside
 * <LoggerProvider>.
 */
export function useLogger(): Logger {
  const logger = useContext(LoggerContext);
  if (!logger) {
    throw new Error(
      "useLogger() must be used within a <LoggerProvider>. " +
      "Ensure the root layout wraps the tree with <LoggerProvider>.",
    );
  }
  return logger;
}
