const STORAGE_KEY = "space-game.auth.effective-player-id";

let currentEffectivePlayerId = loadEffectivePlayerId();
const listeners = new Set<(playerId: string | null) => void>();

export function getEffectivePlayerIdentityId() {
  return currentEffectivePlayerId;
}

export function setEffectivePlayerIdentityId(playerId: string | null) {
  currentEffectivePlayerId = playerId && playerId.trim().length > 0 ? playerId.trim() : null;
  persistEffectivePlayerId(currentEffectivePlayerId);
  for (const listener of listeners) {
    listener(currentEffectivePlayerId);
  }
}

export function clearEffectivePlayerIdentityId() {
  setEffectivePlayerIdentityId(null);
}

export function subscribeToEffectivePlayerIdentity(listener: (playerId: string | null) => void) {
  listeners.add(listener);
  return () => listeners.delete(listener);
}

function loadEffectivePlayerId() {
  if (typeof window === "undefined") {
    return null;
  }

  const raw = window.localStorage.getItem(STORAGE_KEY);
  return raw && raw.trim().length > 0 ? raw.trim() : null;
}

function persistEffectivePlayerId(playerId: string | null) {
  if (typeof window === "undefined") {
    return;
  }

  if (!playerId) {
    window.localStorage.removeItem(STORAGE_KEY);
    return;
  }

  window.localStorage.setItem(STORAGE_KEY, playerId);
}
