
/**
 * Match-Verlauf pro Geraet, komplett ohne Account/Server-Anbindung.
 *
 * Speichert die letzten 5 Matches (inkl. Joker-Ergebnisse) im LocalStorage
 * des Geraets - unabhaengig von der jeweiligen Session, damit man auch nach
 * Session-Ende noch sieht "Zuletzt bei euch: Trattoria Bella Vista" und bei
 * Bedarf spaeter nochmal hinwill, ganz ohne Registrierung.
 *
 * UPDATE: participants (Anzeigenamen der zum Match-Zeitpunkt aktiven
 * Teilnehmer) wird jetzt zusaetzlich gespeichert - fuer die neue
 * Mini-Avatar-Reihe "Wer war dabei?" pro Eintrag. Optional/rueckwaerts-
 * kompatibel: aeltere, bereits gespeicherte Eintraege ohne dieses Feld
 * zeigen einfach keine Avatare an, statt zu crashen.
 */

export interface MatchHistoryEntry {
  id: string;
  name: string;
  isJoker: boolean;
  timestamp: number;
  address?: string;
  participants?: string[];
  sessionCode?: string;
}

const STORAGE_KEY = 'yumder_match_history';
const MAX_ENTRIES = 5;

export function getMatchHistory(): MatchHistoryEntry[] {
  if (typeof window === 'undefined') return [];
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed as MatchHistoryEntry[];
  } catch {
    return [];
  }
}

export function addMatchToHistory(
  name: string,
  isJoker: boolean,
  address?: string | null,
  participants?: string[],
  sessionCode?: string | null,
): MatchHistoryEntry[] {
  if (typeof window === 'undefined') return [];
  const entry: MatchHistoryEntry = {
    id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    name,
    isJoker,
    timestamp: Date.now(),
    address: address || undefined,
    participants: participants && participants.length > 0 ? participants : undefined,
    sessionCode: sessionCode || undefined,
  };
  const next = [entry, ...getMatchHistory()].slice(0, MAX_ENTRIES);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
  return next;
}

export function removeMatchFromHistory(id: string): MatchHistoryEntry[] {
  if (typeof window === 'undefined') return [];
  const next = getMatchHistory().filter((e) => e.id !== id);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
  return next;
}

export function clearMatchHistory(): MatchHistoryEntry[] {
  if (typeof window === 'undefined') return [];
  localStorage.setItem(STORAGE_KEY, JSON.stringify([]));
  return [];
}
