// ─── Combat Room Enchantments Phase ────────────────────────────────────────────
// Extracted from combat-actions.ts to keep the store under the 400-line limit.
// Implements the room enchantment tick: coverage growth, DoT/debuff/buff application.

import type { CombatState, CombatStore } from './combat-state.types';
import type { EnemyState, EquipmentInstance, FloorState } from '../types';
import { getGuardianForFloor } from '../data/guardian-encounters';
import { computeDisciplineEffects } from '../effects/discipline-effects';
import { useCraftingStore } from './craftingStore';
import {
  computeCoveragePerTick,
  applyRoomEnchantmentTick,
  getEquippedRoomEnchantments,
} from '../utils/room-enchantments-utils';

type GetFn = () => CombatStore;
type SetFn = (state: Partial<CombatState>) => void;

/**
 * Process the room enchantment phase of a combat tick.
 * Called after the DoT/debuff phase while floorHP > 0 and action is 'climb'.
 *
 * Returns updated floorHP, currentRoom, and log messages.
 */
export function processRoomEnchantmentPhase(params: {
  get: GetFn;
  set: SetFn;
  floorHP: number;
  currentRoom: FloorState;
  currentFloor: number;
  rawMana: number;
  logMessages: string[];
  onFloorCleared: (floor: number, wasGuardian: boolean) => void;
}): {
  floorHP: number;
  floorMaxHP: number;
  currentFloor: number;
  currentRoom: FloorState;
  logMessages: string[];
} {
  const { get, set, floorHP: initialFloorHP, currentRoom: inputRoom, currentFloor: inputFloor, rawMana, logMessages, onFloorCleared } = params;
  const state = get();

  let floorHP = initialFloorHP;
  let currentRoom = inputRoom;
  let currentFloor = inputFloor;
  let floorMaxHP = state.floorMaxHP;

  if (floorHP <= 0 || state.currentAction !== 'climb') {
    return { floorHP, floorMaxHP, currentFloor, currentRoom, logMessages };
  }

  // Initialize roomEnchantment if null and player has footwear room enchants
  if (!currentRoom.roomEnchantment) {
    const craftingState = useCraftingStore.getState();
    const equippedInstances = (craftingState.equippedInstances || {}) as Record<string, string | null>;
    const equipmentInstances = (craftingState.equipmentInstances || {}) as Record<string, EquipmentInstance>;
    const roomEnchants = getEquippedRoomEnchantments(equippedInstances, equipmentInstances);
    if (roomEnchants.length > 0) {
      const startCoverage = state.lastRoomCoverage || 0;
      currentRoom = {
        ...currentRoom,
        roomEnchantment: { coverage: startCoverage },
      };
      set({ currentRoom });
    }
  }

  // Apply room enchantment effects if active
  if (currentRoom.roomEnchantment) {
    const discEffects = computeDisciplineEffects();
    const coverageRateBonus = discEffects.bonuses.roomCoverageRate || 0;
    const auraMagnitudeBonus = discEffects.bonuses.roomEnchantmentAuraMagnitude || 0;
    const coveragePerTick = computeCoveragePerTick(coverageRateBonus);
    const newCoverage = Math.min(100, currentRoom.roomEnchantment.coverage + coveragePerTick);
    const auraMultiplier = 1 + auraMagnitudeBonus;

    const craftingState = useCraftingStore.getState();
    const equippedInstances = (craftingState.equippedInstances || {}) as Record<string, string | null>;
    const equipmentInstances = (craftingState.equipmentInstances || {}) as Record<string, EquipmentInstance>;
    const roomEnchants = getEquippedRoomEnchantments(equippedInstances, equipmentInstances);

    if (roomEnchants.length > 0) {
      const tickResult = applyRoomEnchantmentTick({
        coverage: newCoverage,
        auraMagnitudeMultiplier: auraMultiplier,
        equippedRoomEnchantments: roomEnchants,
        enemies: currentRoom.enemies,
        rawMana,
      });

      // Update enemies and recalculate floorHP
      currentRoom = {
        ...currentRoom,
        roomEnchantment: { coverage: newCoverage },
        enemies: tickResult.enemies,
      };
      floorHP = tickResult.enemies.reduce((sum, e) => sum + Math.max(0, e.hp), 0);
      set({ currentRoom, floorHP });

      // Log player buffs (cast speed multiplier from transference buff)
      if (tickResult.playerBuffs.castSpeedMultiplier > 0) {
        logMessages.push(
          `✨ Room aura: +${(tickResult.playerBuffs.castSpeedMultiplier * 100).toFixed(1)}% cast speed`,
        );
      }

      // Check if room was cleared by room enchantment damage
      if (floorHP <= 0) {
        const guardian = getGuardianForFloor(currentFloor);
        onFloorCleared(currentFloor, !!guardian);
        get().advanceRoomOrFloor();
        const newState = get();
        currentFloor = newState.currentFloor;
        floorMaxHP = newState.floorMaxHP;
        floorHP = newState.floorHP;
        currentRoom = newState.currentRoom;
      }
    }
  }

  return { floorHP, floorMaxHP, currentFloor, currentRoom, logMessages };
}
