import { useSyncExternalStore } from 'react'; const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId'; const DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY = 'lolympus.devCaptainTeamIndex'; const LEGACY_DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide'; const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed'; const CAPTAIN_SIDE_CHANGED_EVENT = 'lolympus:captain-side-changed'; export const API_BASE_URL = ( import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3000' ).replace(/\/$/, ''); export const DEFAULT_COMMUNITY_ID = ( import.meta.env.VITE_DEFAULT_COMMUNITY_ID ?? '' ).trim(); function dispatchWindowEvent(eventName: string) { if (typeof window === 'undefined') return; window.dispatchEvent(new Event(eventName)); } function subscribeToWindowChanges(eventName: string, callback: () => void) { if (typeof window === 'undefined') { return () => undefined; } const handleChange = () => callback(); window.addEventListener(eventName, handleChange); window.addEventListener('storage', handleChange); return () => { window.removeEventListener(eventName, handleChange); window.removeEventListener('storage', handleChange); }; } export function getAuthUserId(): string | null { if (!import.meta.env.DEV) return null; if (typeof window === 'undefined') return null; const value = window.localStorage.getItem(AUTH_USER_ID_STORAGE_KEY)?.trim(); return value ? value : null; } export function setAuthUserId(userId: string | null) { if (!import.meta.env.DEV) return; if (typeof window === 'undefined') return; if (!userId?.trim()) { window.localStorage.removeItem(AUTH_USER_ID_STORAGE_KEY); } else { window.localStorage.setItem(AUTH_USER_ID_STORAGE_KEY, userId.trim()); } dispatchWindowEvent(AUTH_USER_CHANGED_EVENT); } export function getDevCaptainTeamIndex(): number | null { if (typeof window === 'undefined') return null; const value = window.localStorage.getItem(DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY); const parsed = Number(value); if (Number.isInteger(parsed) && parsed > 0) return parsed; const legacy = window.localStorage.getItem(LEGACY_DEV_CAPTAIN_SIDE_STORAGE_KEY); if (legacy === 'blue') return 1; if (legacy === 'red') return 2; return null; } export function setDevCaptainTeamIndex(teamIndex: number | null) { if (typeof window === 'undefined') return; if (teamIndex && Number.isInteger(teamIndex) && teamIndex > 0) { window.localStorage.setItem( DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY, String(teamIndex), ); } else { window.localStorage.removeItem(DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY); } dispatchWindowEvent(CAPTAIN_SIDE_CHANGED_EVENT); } export function useAuthUserId(): string | null { return useSyncExternalStore( (callback) => subscribeToWindowChanges(AUTH_USER_CHANGED_EVENT, callback), getAuthUserId, () => null, ); } export function useDevCaptainTeamIndex(): number | null { return useSyncExternalStore( (callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback), getDevCaptainTeamIndex, () => null, ); }