// ─── Equipment Crafting Actions ────────────────────────────────────────────
// Note: The main implementation is now in craftingStore.ts
// These wrappers are kept for backward compatibility but are no longer used directly

import type { GameState } from '../types';
import * as CraftingEquipment from '../crafting-equipment';

// Wrapper functions kept for backward compatibility
// The actual implementation is in craftingStore.ts using CraftingEquipment functions directly

export function startCraftingEquipment(
  blueprintId: string,
  get: () => GameState,
  set: (fn: (state: GameState) => Partial<GameState>) => void
): boolean {
  const state = get();

  const check = CraftingEquipment.canStartEquipmentCrafting(
    blueprintId,
    state.lootInventory.blueprints.includes(blueprintId),
    state.lootInventory.materials,
    state.rawMana,
    state.currentAction
  );

  if (!check.canCraft) return false;

  const result = CraftingEquipment.initializeEquipmentCrafting(
    blueprintId,
    state.lootInventory.materials,
    state.rawMana
  );

  set((state) => ({
    lootInventory: {
      ...state.lootInventory,
      materials: result.newMaterials,
    },
    rawMana: state.rawMana - result.manaCost,
    currentAction: 'craft' as const,
    equipmentCraftingProgress: result.progress,
  }));

  return true;
}

export function cancelEquipmentCrafting(
  get: () => GameState,
  set: (fn: (state: GameState) => Partial<GameState>) => void
) {
  set((state) => {
    const progress = state.equipmentCraftingProgress;
    if (!progress) return { currentAction: 'meditate' as const, equipmentCraftingProgress: null };

    const cancelResult = CraftingEquipment.cancelEquipmentCrafting(
      progress.blueprintId,
      progress.manaSpent
    );

    return {
      currentAction: 'meditate' as const,
      equipmentCraftingProgress: null,
      rawMana: state.rawMana + cancelResult.manaRefund,
      log: [cancelResult.logMessage, ...state.log.slice(0, 49)],
    };
  });
}

export function deleteMaterial(
  materialId: string,
  amount: number,
  get: () => GameState,
  set: (fn: (state: GameState) => Partial<GameState>) => void
) {
  set((state) => {
    const newMaterials = { ...state.lootInventory.materials };
    const currentAmount = newMaterials[materialId] || 0;
    const newAmount = Math.max(0, currentAmount - amount);

    if (newAmount <= 0) {
      delete newMaterials[materialId];
    } else {
      newMaterials[materialId] = newAmount;
    }

    return {
      lootInventory: {
        ...state.lootInventory,
        materials: newMaterials,
      },
      log: [`🗑️ Deleted ${amount}x ${materialId}.`, ...state.log.slice(0, 49)],
    };
  });
}
