import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react'; import { StorageServiceCasual } from 'common-ui'; import type { ReactParentComponent } from '@packages/shared'; import { trpc } from '../trpc-client'; export const ACTIVE_REGION_KEY = 'active_region'; interface RegionState { regionId: number | null; regionName: string | null; boundId: number | null; boundName: string | null; isLoading: boolean; } interface RegionContextType extends RegionState { setRegion: (regionId: number, regionName: string, boundId?: number | null, boundName?: string | null) => Promise; } const RegionContext = createContext(undefined); interface StoredRegion { regionId: number; regionName: string | null; boundId: number | null; boundName: string | null; } export const RegionProvider: React.FC = ({ children }) => { const [state, setState] = useState({ regionId: null, regionName: null, boundId: null, boundName: null, isLoading: true, }); const [stored, setStored] = useState<{ loaded: boolean; value: StoredRegion | null }>({ loaded: false, value: null, }); useEffect(() => { StorageServiceCasual.getItem(ACTIVE_REGION_KEY).then((raw) => { if (raw) { try { const parsed = JSON.parse(raw); if (typeof parsed?.regionId === 'number') { setStored({ loaded: true, value: { regionId: parsed.regionId, regionName: typeof parsed.regionName === 'string' ? parsed.regionName : null, boundId: typeof parsed?.boundId === 'number' ? parsed.boundId : null, boundName: typeof parsed?.boundName === 'string' ? parsed.boundName : null, }, }); return; } } catch { // ignore corrupt cache } } setStored({ loaded: true, value: null }); }); }, []); // Validate the persisted region still exists backend-side. Unknown ids reset // so the gate re-prompts instead of serving a ghost region. A stale boundId // needs no reset: server merge degrades gracefully to region rows. const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity }); useEffect(() => { if (!stored.loaded || regionsData === undefined) return; const valid = stored.value != null && regionsData.regions.some((r) => r.id === stored.value!.regionId); if (valid && stored.value != null) { setState({ ...stored.value, isLoading: false }); } else { if (stored.value != null) { void StorageServiceCasual.removeItem(ACTIVE_REGION_KEY); } setState({ regionId: null, regionName: null, boundId: null, boundName: null, isLoading: false }); } }, [stored, regionsData]); const setRegion = useCallback( async (regionId: number, regionName: string, boundId?: number | null, boundName?: string | null) => { await StorageServiceCasual.setItem( ACTIVE_REGION_KEY, JSON.stringify({ regionId, regionName, boundId: boundId ?? null, boundName: boundName ?? null }) ); setState({ regionId, regionName, boundId: boundId ?? null, boundName: boundName ?? null, isLoading: false }); }, [] ); const value = useMemo(() => ({ ...state, setRegion }), [state, setRegion]); return ( {children} ); }; export const useRegion = (): RegionContextType => { const context = useContext(RegionContext); if (context === undefined) { throw new Error('useRegion must be used within a RegionProvider'); } return context; }; /** Spread into user-facing trpc query/mutation inputs so the backend scopes * to the active region (and bound, when known). Empty object when no region * is set yet (backend keeps its default-region behaviour in that case). */ export const useRegionParams = (): { regionId?: number; boundId?: number } => { const { regionId, boundId } = useRegion(); return useMemo( () => ({ ...(regionId != null ? { regionId } : {}), ...(boundId != null ? { boundId } : {}), }), [regionId, boundId] ); };