import { startTransition, useEffect } from "react";
import {
  createLegacyLife,
  loadLegacySpecialThanks,
  onLegacyAchievement,
} from "../legacy/interop.js";
import type { LegacyAchievementEvent } from "../legacy/interop.js";
import type { LegacySessionBootstrapProps } from "./legacySessionActionTypes";
import {
  createLegacyAchievementActivity,
  createLegacyPackLoadedActivity,
} from "./legacySessionMessages";
import { shuffleEntries } from "./legacySessionUtils";

export function useLegacySessionBootstrap({
  addActivity,
  clearError,
  lifeRef,
  refreshDraft,
  refreshMeta,
  setIsBusy,
  setIsReady,
  setSpecialThanks,
  showError,
}: LegacySessionBootstrapProps) {
  useEffect(() => {
    const life = createLegacyLife();
    lifeRef.current = life;
    setIsBusy(true);

    void (async () => {
      try {
        const loadedSpecialThanks = await Promise.all([
          life.initial(),
          loadLegacySpecialThanks(),
        ]).then(([, entries]) => entries);

        startTransition(() => {
          setIsReady(true);
          clearError();
          setSpecialThanks(shuffleEntries(loadedSpecialThanks));
        });
        addActivity(createLegacyPackLoadedActivity());
        refreshDraft();
      } catch (error) {
        showError(
          error instanceof Error
            ? error.message
            : "Failed to load legacy data.",
        );
      } finally {
        setIsBusy(false);
      }
    })();

    return onLegacyAchievement((achievement: LegacyAchievementEvent) => {
      addActivity(createLegacyAchievementActivity(achievement));
      refreshMeta();
    });
  }, [
    addActivity,
    clearError,
    lifeRef,
    refreshDraft,
    refreshMeta,
    setIsBusy,
    setIsReady,
    setSpecialThanks,
    showError,
  ]);
}
