import { startTransition, useEffectEvent, useState } from "react";
import type { MutableRefObject } from "react";
import { buildLegacyTotalCards } from "../legacy/interop.js";
import type {
  LegacyAchievementCatalogEntry,
  LegacyLifeInstance,
  LegacyTotalCard,
  LegacyTotals,
} from "../legacy/interop.js";

interface UseLegacySessionMetaResult {
  achievementCatalog: LegacyAchievementCatalogEntry[];
  refreshMeta: () => void;
  totalCards: LegacyTotalCard[];
  totals: LegacyTotals | null;
}

function normalizeAchievementCatalog(
  life: LegacyLifeInstance,
): LegacyAchievementCatalogEntry[] {
  return life.getAchievements().map((entry) => ({
    ...entry,
    hide: Boolean(entry.hide),
  }));
}

export function useLegacySessionMeta(
  lifeRef: MutableRefObject<LegacyLifeInstance | null>,
): UseLegacySessionMetaResult {
  const [totals, setTotals] = useState<LegacyTotals | null>(null);
  const [totalCards, setTotalCards] = useState<LegacyTotalCard[]>([]);
  const [achievementCatalog, setAchievementCatalog] = useState<
    LegacyAchievementCatalogEntry[]
  >([]);

  const refreshMeta = useEffectEvent(() => {
    const life = lifeRef.current;
    if (!life) {
      return;
    }

    const nextTotals = life.getTotal();
    const nextAchievementCatalog = normalizeAchievementCatalog(life);

    startTransition(() => {
      setTotals(nextTotals);
      setTotalCards(buildLegacyTotalCards(nextTotals));
      setAchievementCatalog(nextAchievementCatalog);
    });
  });

  return {
    achievementCatalog,
    refreshMeta,
    totalCards,
    totals,
  };
}
