// ─── Enchantment Application Actions ────────────────────────────────────────

import type { CraftingState } from '../stores/craftingStore.types';
import type { GameAction } from '../types';
import * as CraftingApply from '../crafting-apply';
import { useManaStore } from '../stores/manaStore';
import { useUIStore } from '../stores/uiStore';

/**
 * Start applying an enchantment design to an equipment instance.
 * Note: currentAction must be passed from the combat store.
 */
export function startApplying(
  equipmentInstanceId: string,
  designId: string,
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void,
  currentAction: GameAction,
): boolean {
  const state = get();
  const instance = state.equipmentInstances[equipmentInstanceId];
  const design = state.completedEnchantmentDesigns.find(d => d.id === designId);

  const validation = CraftingApply.canApplyEnchantment(
    instance,
    design,
    currentAction
  );
  if (!validation.canApply) return false;

  set({
    applicationProgress: CraftingApply.initializeApplicationProgress(
      equipmentInstanceId,
      designId,
      design!
    ),
  });

  return true;
}

export function pauseApplication(
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void
) {
  const state = get();
  if (!state.applicationProgress) return;
  set({
    applicationProgress: {
      ...state.applicationProgress,
      paused: true,
    },
  });
}

export function resumeApplication(
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void
) {
  const state = get();
  if (!state.applicationProgress) return;
  set({
    applicationProgress: {
      ...state.applicationProgress,
      paused: false,
    },
  });
}

export function cancelApplication(
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void
) {
  const state = get();
  const progress = state.applicationProgress;
  if (!progress) return;

  // Refund mana proportionally to remaining progress
  const remainingFraction = progress.required > 0
    ? Math.max(0, (progress.required - progress.progress) / progress.required)
    : 1;
  // Full refund for unspent progress, 50% for spent progress
  const refundRate = remainingFraction + (1 - remainingFraction) * 0.5;
  const manaRefund = Math.floor(progress.manaSpent * refundRate);

  if (manaRefund > 0) {
    useManaStore.setState((s) => ({ rawMana: s.rawMana + manaRefund }));
  }
  useUIStore.getState().addLog(`🚫 Enchantment application cancelled. Refunded ${manaRefund} mana.`);
  set({
    applicationProgress: null,
  });
}
