// ─── Equipment Crafting Pipeline ──────────────────────────────────────────────
// Extracted from craftingStore.ts to keep it under the 400-line file limit.
// Handles start/cancel of equipment crafting and fabricator crafting.

import type { CraftingState } from '../craftingStore.types';
import * as CraftingEquipment from '../../crafting-equipment';
import {
  getFabricatorRecipe,
  deductFabricatorMana,
  deductMaterials,
  makeFabricatorProgress,
  refundFabricatorMana,
  getCraftingCostReduction,
  applyCostReduction,
} from '../../crafting-fabricator';
import { useManaStore } from '../manaStore';
import { useCombatStore } from '../combatStore';
import { useUIStore } from '../uiStore';

type GetFn = () => CraftingState;
type SetFn = (partial: Partial<CraftingState>) => void;

export function startCraftingEquipment(
  blueprintId: string,
  get: GetFn,
  set: SetFn,
): boolean {
  const state = get();
  const rawMana = useManaStore.getState().rawMana;
  const currentAction = useCombatStore.getState().currentAction;
  const check = CraftingEquipment.canStartEquipmentCrafting(
    blueprintId,
    state.lootInventory.blueprints.includes(blueprintId),
    state.lootInventory.materials,
    rawMana,
    currentAction,
  );
  if (!check.canCraft) return false;
  const result = CraftingEquipment.initializeEquipmentCrafting(
    blueprintId,
    state.lootInventory.materials,
    rawMana,
  );
  set((s) => ({
    lootInventory: { ...s.lootInventory, materials: result.newMaterials },
    equipmentCraftingProgress: result.progress,
  }));
  useManaStore.setState((s) => ({ rawMana: s.rawMana - result.manaCost }));
  useCombatStore.setState({ currentAction: 'craft' });
  return true;
}

export function cancelEquipmentCrafting(get: GetFn, set: SetFn): void {
  const progress = get().equipmentCraftingProgress;
  if (!progress) return;

  const isFabricator = progress.blueprintId.startsWith('fabricator-');

  if (isFabricator) {
    // Fabricator recipe cancel: refund elemental/raw mana and materials
    const recipeId = progress.blueprintId.replace('fabricator-', '');
    const recipe = getFabricatorRecipe(recipeId);
    if (recipe) {
      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);

      // Refund the correct mana type
      const rawMana = useManaStore.getState().rawMana;
      const elements = useManaStore.getState().elements;
      const refunded = refundFabricatorMana(recipe, manaRefund, rawMana, elements);
      useManaStore.setState({ rawMana: refunded.rawMana, elements: refunded.elements });

      // Refund materials — flat 50% per spec §6.3
      const reduction = getCraftingCostReduction();
      const currentMaterials = get().lootInventory.materials;
      const refundedMaterials = { ...currentMaterials };
      for (const [matId, rawAmount] of Object.entries(recipe.materials)) {
        const reducedAmount = applyCostReduction(rawAmount, reduction);
        const refundAmount = Math.floor(reducedAmount * 0.5);
        if (refundAmount > 0) {
          refundedMaterials[matId] = (refundedMaterials[matId] || 0) + refundAmount;
        }
      }
      set({ equipmentCraftingProgress: null, lootInventory: { ...get().lootInventory, materials: refundedMaterials } });
      useUIStore.getState().addLog(`🚫 Fabricator crafting cancelled. Refunded ${manaRefund} ${recipe.manaType} mana.`);
    } else {
      set({ equipmentCraftingProgress: null });
    }
  } else {
    // Standard equipment crafting cancel
    const cancelResult = CraftingEquipment.cancelEquipmentCrafting(
      progress.blueprintId,
      progress.manaSpent,
      progress.progress,
      progress.required,
    );
    // Refund materials — flat 50% per spec §6.3
    const recipe = CraftingEquipment.getRecipe(progress.blueprintId);
    if (recipe) {
      const currentMaterials = get().lootInventory.materials;
      const refundedMaterials = { ...currentMaterials };
      for (const [matId, amount] of Object.entries(recipe.materials)) {
        const refundAmount = Math.floor(amount * 0.5);
        if (refundAmount > 0) {
          refundedMaterials[matId] = (refundedMaterials[matId] || 0) + refundAmount;
        }
      }
      set({ equipmentCraftingProgress: null, lootInventory: { ...get().lootInventory, materials: refundedMaterials } });
    } else {
      set({ equipmentCraftingProgress: null });
    }
    useManaStore.setState((s) => ({ rawMana: s.rawMana + cancelResult.manaRefund }));
    useUIStore.getState().addLog(cancelResult.logMessage);
  }
  useCombatStore.setState({ currentAction: 'meditate' });
}

export function startFabricatorCrafting(recipeId: string, get: GetFn, set: SetFn): boolean {
  const state = get();
  const currentAction = useCombatStore.getState().currentAction;
  if (currentAction !== 'meditate') return false;

  const recipe = getFabricatorRecipe(recipeId);
  if (!recipe) return false;

  const rawMana = useManaStore.getState().rawMana;
  const elements = useManaStore.getState().elements;

  const deducted = deductFabricatorMana(recipe, rawMana, elements);
  if (!deducted) return false;

  // deductMaterials already applies cost reduction internally via getCraftingCostReduction()
  const newMaterials = deductMaterials(recipe, state.lootInventory.materials);
  const progress = makeFabricatorProgress(recipeId, recipe.equipmentTypeId, recipe.craftTime, recipe.manaCost);

  useManaStore.setState({ rawMana: deducted.rawMana, elements: deducted.elements });
  set((s) => ({ lootInventory: { ...s.lootInventory, materials: newMaterials }, equipmentCraftingProgress: progress }));
  useCombatStore.setState({ currentAction: 'craft' });
  return true;
}
