// packages/commerce-catalog-react/src/CatalogProvider.tsx
import { createContext, useContext, useMemo, type ReactNode } from 'react'
import type { CatalogClient } from './client.js'
import { CatalogProviderError } from './errors.js'

export interface CatalogContextValue {
  client: CatalogClient
}

const CatalogContext = createContext<CatalogContextValue | null>(null)

/** Pure client-injection context (§2) — no shared mount-state, no mount fetch. */
export function CatalogProvider({ client, children }: { client: CatalogClient; children: ReactNode }) {
  const value = useMemo<CatalogContextValue>(() => ({ client }), [client])
  return <CatalogContext.Provider value={value}>{children}</CatalogContext.Provider>
}

export function useCatalogContext(hook: string): CatalogContextValue {
  const ctx = useContext(CatalogContext)
  if (!ctx) throw new CatalogProviderError(hook)
  return ctx
}
