/* ============================================================
   useGame — round/phase state machine on top of ships/squadrons
   Returns game flow state + handlers. Ships/squadrons live in App.
   ============================================================ */
const { useState: useStateGame, useCallback: useCbGame, useRef: useRefGame } = React;

function freshGame(sides, scenarioId) {
  const first = sides[0] || null;
  return {
    started: false,
    phase: "command",
    round: 1,
    firstFaction: first,          // initiative holder this round
    activeFaction: first,         // who activates next (ship/squadron phase)
    lastActivated: null,
    scenarioId,
    sqTurn: null,                 // squadron phase: { faction, left } — beurt-alternatie
    log: [],
    score: sides.reduce((o, f) => (o[f] = 0, o), {}),
    over: false,
    // gedeeld schadekaartendek — gebouwd/geschud bij spelstart, getrokken bij elke crit (§ damage-effects)
    damageDeck: buildDamageDeck((typeof window !== "undefined" && window.CATALOG_DATA && window.CATALOG_DATA.damage) || [], Math.random),
  };
}

function useGame() {
  const [g, setG] = useStateGame(null);
  const logRef = useRefGame(0);

  const addLog = useCbGame((text, kind = "info") => {
    setG((s) => s ? { ...s, log: [{ id: ++logRef.current, round: s.round, phase: s.phase, text, kind }, ...s.log].slice(0, 60) } : s);
  }, []);

  return { g, setG, addLog };
}

Object.assign(window, { freshGame, useGame });
