import { computeMaxMana, computeClickMana } from '../utils';
import type { GameCoordinatorState } from './gameStore.types';
import { useUIStore } from './uiStore';
import { usePrestigeStore } from './prestigeStore';
import { useManaStore } from './manaStore';
import { useCombatStore } from './combatStore';
import { useDisciplineStore } from './discipline-slice';
import { useAttunementStore } from './attunementStore';
import { useCraftingStore } from './craftingStore';
import { computeDisciplineEffects } from '../effects/discipline-effects';

// Exact localStorage keys matching each store's persist config `name`
const ALL_STORE_KEYS = [
  'mana-loop-game-storage',
  'mana-loop-mana',
  'mana-loop-combat',
  'mana-loop-prestige',
  'mana-loop-crafting',
  'mana-loop-attunements',
  'mana-loop-discipline-store',
  'mana-loop-ui-storage',
] as const;

export const createResetGame = (set: (state: Partial<GameCoordinatorState>) => void, initialState: GameCoordinatorState) => () => {
  // Clear all persisted state — must use exact keys from each store's persist config
  if (typeof window !== 'undefined') {
    for (const key of ALL_STORE_KEYS) {
      localStorage.removeItem(key);
    }
  }

  const startFloor = 1;

  useUIStore.getState().reset();
  usePrestigeStore.getState().resetPrestige();
  useManaStore.getState().resetMana({});
  useCombatStore.getState().resetCombat(startFloor);
  useDisciplineStore.getState().resetDisciplines();
  useAttunementStore.getState().resetAttunements();
  useCraftingStore.getState().resetCrafting();

  set({
    ...initialState,
    initialized: true,
  });
};

export const createGatherMana = () => () => {
  const prestigeState = usePrestigeStore.getState();
  const disciplineEffects = computeDisciplineEffects();

  // Compute click mana with discipline bonuses
  const cm = computeClickMana(disciplineEffects);

  const max = computeMaxMana(
    { prestigeUpgrades: prestigeState.prestigeUpgrades },
    undefined,
    disciplineEffects,
  );

  useManaStore.getState().gatherMana(cm, max);
};
