/**
 * Zentrale LocalStorage-Schluessel und kleine Helper fuer wiederkehrende
 * Client-Daten (anonyme ID, Teilnehmer-ID, Session-Code, Anzeigename).
 * Alle Zugriffe sind window-safe, damit sie auch in Server-Komponenten/
 ersten Render nicht crashen.
 */

export const STORAGE_KEYS = {
  anonymousId: 'yumder_anonymous_id',
  participantId: 'yumder_participant_id',
  sessionCode: 'yumder_session_code',
  displayName: 'yumder_display_name',
  lastCity: 'yumder_last_city',
  tutorialSeen: 'yumder_tutorial_seen',
} as const;

export function getStoredDisplayName(): string | null {
  if (typeof window === 'undefined') return null;
  try {
    return window.localStorage.getItem(STORAGE_KEYS.displayName);
  } catch {
    return null;
  }
}

export function setStoredDisplayName(name: string | null | undefined): void {
  if (typeof window === 'undefined') return;
  try {
    if (name && name.trim()) {
      window.localStorage.setItem(STORAGE_KEYS.displayName, name.trim());
    } else {
      window.localStorage.removeItem(STORAGE_KEYS.displayName);
    }
  } catch {
    // LocalStorage kann deaktiviert sein - dann einfach nichts speichern.
  }
}

export function getStoredLastCity(): string | null {
  if (typeof window === 'undefined') return null;
  try {
    return window.localStorage.getItem(STORAGE_KEYS.lastCity);
  } catch {
    return null;
  }
}

export function setStoredLastCity(city: string | null | undefined): void {
  if (typeof window === 'undefined') return;
  try {
    if (city && city.trim()) {
      window.localStorage.setItem(STORAGE_KEYS.lastCity, city.trim());
    } else {
      window.localStorage.removeItem(STORAGE_KEYS.lastCity);
    }
  } catch {
    // LocalStorage kann deaktiviert sein - dann einfach nichts speichern.
  }
}

/**
 * Liefert die aktive Teilnahme dieses Geraets (participantId + Code), sofern
 * beide noch im LocalStorage liegen. Basis fuer den "Weiter swipen"-Resume-
 * Button auf der Startseite. Window-safe.
 */
export function getActiveSession(): { participantId: string | null; code: string | null } {
  if (typeof window === 'undefined') return { participantId: null, code: null };
  try {
    return {
      participantId: window.localStorage.getItem(STORAGE_KEYS.participantId),
      code: window.localStorage.getItem(STORAGE_KEYS.sessionCode),
    };
  } catch {
    return { participantId: null, code: null };
  }
}
