// ─── Transference Channel Combat Logic ─────────────────────────────────────────
// Extracted from combat-actions.ts to stay under the 400-line file limit.
// Handles Transference mana drain and speed multiplier application.

import { computeDisciplineEffects } from '../effects/discipline-effects';
import { useManaStore } from './manaStore';
import type { CombatStore, CombatState } from './combat-state.types';

// ─── Base Values ───────────────────────────────────────────────────────────────

const BASE_DRAIN_RATE = 0.08;
const BASE_SPEED_MULTIPLIER = 1.5;
const CHANNEL_EFFICIENCY_CAP = 0.60;

// ─── Effective Stat Computation ────────────────────────────────────────────────

export interface ChannelStats {
  speedMultiplier: number;
  drainRate: number;
}

/**
 * Compute effective channel speed multiplier and drain rate from discipline stats.
 *
 * Formulas:
 *   channelEfficiency = min(CHANNEL_EFFICIENCY_CAP, sum of efficiency perks)
 *   effectiveSpeedMultiplier = 1.5 + (channelIntensity × 0.5)
 *   effectiveDrainRate = 0.08 × (1 + channelIntensity × 1.0) × (1 - channelEfficiency)
 */
export function computeChannelStats(): ChannelStats {
  const effects = computeDisciplineEffects();
  const channelIntensity = effects.bonuses.channelIntensity || 0;
  const rawEfficiency = effects.bonuses.channelEfficiency || 0;
  const channelEfficiency = Math.min(CHANNEL_EFFICIENCY_CAP, rawEfficiency);

  const speedMultiplier = BASE_SPEED_MULTIPLIER + channelIntensity * 0.5;
  const drainRate = BASE_DRAIN_RATE * (1 + channelIntensity * 1.0) * (1 - channelEfficiency);

  return { speedMultiplier, drainRate };
}

// ─── Channel Drain ─────────────────────────────────────────────────────────────

/**
 * Apply one tick of Transference drain while channeling.
 * Returns the amount of Transference actually drained (0 if insufficient mana).
 */
export function applyChannelDrain(
  get: () => CombatStore,
  set: (s: Partial<CombatState>) => void,
  drainRate: number,
): number {
  const transference = useManaStore.getState().elements.transference;
  if (!transference || transference.current < drainRate) {
    set({ isChanneling: false });
    return 0;
  }
  useManaStore.getState().deductElement('transference', drainRate);
  return drainRate;
}

// ─── Speed Multiplier Application ──────────────────────────────────────────────

/**
 * Get the current channel speed multiplier.
 * Returns 1.0 if not channeling.
 */
export function getChannelMultiplier(
  get: () => CombatStore,
): number {
  const state = get();
  return state.isChanneling ? state.channelSpeedMultiplier : 1.0;
}
