import { create } from 'zustand';

const STORAGE_KEY = 'cup26:favorite';

function readFavorite(): string | null {
  try {
    return localStorage.getItem(STORAGE_KEY);
  } catch {
    return null;
  }
}

interface FavoriteState {
  favorite: string | null;
  toggleFavorite: (team: string) => void;
}

/** One starred team — its next match gets pinned on the Live tab. */
export const useFavoriteStore = create<FavoriteState>((set, get) => ({
  favorite: readFavorite(),
  toggleFavorite: (team) => {
    const next = get().favorite === team ? null : team;
    try {
      if (next) localStorage.setItem(STORAGE_KEY, next);
      else localStorage.removeItem(STORAGE_KEY);
    } catch { /* private mode */ }
    set({ favorite: next });
  },
}));
