import { calcInsight, getFloorMaxHP } from '../utils';
import type { GameCoordinatorState } from './gameStore.types';
import { makeInitialSpells } from './combatStore';
import { SPELLS_DEF } from '../constants';
import { useUIStore } from './uiStore';
import { usePrestigeStore } from './prestigeStore';
import { useManaStore } from './manaStore';
import { useCombatStore } from './combatStore';
import { useDisciplineStore } from './discipline-slice';
import { computeDisciplineEffects } from '../effects/discipline-effects';

export const createStartNewLoop = (set: (state: Partial<GameCoordinatorState>) => void) => () => {
  const prestigeState = usePrestigeStore.getState();
  const combatState = useCombatStore.getState();
  const manaState = useManaStore.getState();

  const disciplineEffects = computeDisciplineEffects();
  const insightGained = prestigeState.loopInsight || calcInsight({
    maxFloorReached: combatState.maxFloorReached,
    totalManaGathered: manaState.totalManaGathered,
    signedPacts: prestigeState.signedPacts,
    prestigeUpgrades: prestigeState.prestigeUpgrades,
  }, disciplineEffects);

  const total = prestigeState.insight + insightGained;

  const pu = prestigeState.prestigeUpgrades;
  const startFloor = 1 + (pu.spireKey || 0) * 2;

  // Reset and update all stores for new loop
  useUIStore.setState({
    gameOver: false,
    victory: false,
    paused: false,
    logs: ['✨ The loop begins. You start with Mana Bolt. Gather your strength, mage.'],
  });

  usePrestigeStore.getState().resetPrestigeForNewLoop(
    total,
    pu,
  );
  usePrestigeStore.getState().incrementLoopCount();

  useManaStore.getState().resetMana(pu);
  useDisciplineStore.getState().resetDisciplines();

  // Reset combat with starting floor and any spells from prestige upgrades
  const startSpells = makeInitialSpells();
  if (pu.spellMemory) {
    const availableSpells = Object.keys(SPELLS_DEF).filter(s => s !== 'manaBolt');
    const shuffled = availableSpells.sort(() => Math.random() - 0.5);
    for (let i = 0; i < Math.min(pu.spellMemory, shuffled.length); i++) {
      startSpells[shuffled[i]] = { learned: true, level: 1, studyProgress: 0 };
    }
  }

  useCombatStore.setState({
    currentFloor: startFloor,
    floorHP: getFloorMaxHP(startFloor),
    floorMaxHP: getFloorMaxHP(startFloor),
    maxFloorReached: startFloor,
    activeSpell: 'manaBolt',
    currentAction: 'meditate',
    castProgress: 0,
    spells: startSpells,
  });

  set({
    day: 1,
    hour: 0,
    incursionStrength: 0,
    containmentWards: 0,
  });
};
