import type { ReactNode } from "react" import { createContext, useContext, useLayoutEffect } from "react" import type { RegionConfig, RegionalRegistry } from "./types" const RegionalContext = createContext(null) /** * Module-level ref — synced by RegionalProvider via useLayoutEffect. * Safe to read after mount; throws if called before provider mounts. * Used by createApiClient in services/client.ts for non-hook contexts. * * Per-bundle singleton: only one RegionalProvider should exist per module * bundle. Multiple providers in the same bundle would overwrite each other. * In MFE architecture each MFE bundle has exactly one provider, so this is safe. * * Cleanup note: when registry.config changes identity, useLayoutEffect cleanup * sets this to null before the new effect sets the new value. Any synchronous * read during that window will throw — this is intentional (stale config is * worse than a clear error). */ let _currentRegionConfig: RegionConfig | null = null export function getRegionalConfig(): RegionConfig { if (!_currentRegionConfig) throw new Error("getRegionalConfig called before RegionalProvider mounted") return _currentRegionConfig } /** * Wrap AppContainer (or any subtree) with RegionalProvider to make the * resolved registry available via the useRegional() hook. */ export function RegionalProvider({ registry, children, }: { registry: RegionalRegistry children: ReactNode }) { useLayoutEffect(() => { _currentRegionConfig = registry.config return () => { _currentRegionConfig = null } }, [registry.config]) return ( {children} ) } /** * Read the active regional registry. * Must be called inside a . * * @example * const { config, logic, components } = useRegional() */ export function useRegional(): RegionalRegistry { const ctx = useContext(RegionalContext) if (!ctx) throw new Error("useRegional must be used within ") return ctx }