const STORAGE_KEY = "lottery.player.selected_currency";

export function persistPlayerSelectedCurrency(code: string): void {
  try {
    localStorage.setItem(STORAGE_KEY, code.trim().toUpperCase());
  } catch {
    /* ignore quota / private mode */
  }
}

export function readPersistedPlayerSelectedCurrency(): string | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw?.trim() ? raw.trim().toUpperCase() : null;
  } catch {
    return null;
  }
}

export function clearPersistedPlayerSelectedCurrency(): void {
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch {
    /* ignore */
  }
}

/** 切换币种后通知各业务模块重新拉取玩法/钱包等数据 */
export const PLAYER_CURRENCY_CHANGE_EVENT = "lottery-currency-change";

export function dispatchPlayerCurrencyChange(code: string): void {
  if (typeof window === "undefined") return;
  window.dispatchEvent(
    new CustomEvent(PLAYER_CURRENCY_CHANGE_EVENT, {
      detail: { currency: code.trim().toUpperCase() },
    }),
  );
}
