import { system, world } from "@minecraft/server";
import { playAnimationWithClock, AnimationHelper } from "./animation_controller";
import { playSound } from "./combat_mechanic";
import { PARRY_RESISTANCE, PARRY_COOLDOWN_TICKS, PARRY_WINDOW_TICKS } from "./combat_config";
// Store parry states
export const parryStates = new Map();
export const parryCooldowns = new Map(); // player.id → cooldown expiry tick

// ----------------------
// Activate Parry
// ----------------------
export function activateParry(player) {
  const now = system.currentTick;

  // still in cooldown?
  if ((parryCooldowns.get(player.id) ?? 0) > now) {
    player.runCommand(`title @s actionbar §cParry cooling down...`);
    return;
  }

  const expiry = now + PARRY_WINDOW_TICKS;

  // 🟢 Store both startTick and expiry
  parryStates.set(player.id, { startTick: now, expiry });

  // Set cooldown
  parryCooldowns.set(player.id, now + PARRY_COOLDOWN_TICKS);

  player.runCommand(`title @s actionbar §bParry Ready!`);
  
  playAnimationWithClock(player, AnimationHelper("animation.combat.parry", player), 20);
  player.addEffect("resistance", PARRY_WINDOW_TICKS, { amplifier: PARRY_RESISTANCE, showParticles: true });

  // Auto cleanup
  system.runTimeout(() => {
    const state = parryStates.get(player.id);
    if (state && state.expiry === expiry) {
      parryStates.delete(player.id);
    }
  }, PARRY_WINDOW_TICKS);
}

// ----------------------
// Listen for entity damage
// ----------------------
world.afterEvents.entityHurt.subscribe(ev => {
  const { hurtEntity, damageSource } = ev;

  if (hurtEntity.typeId !== "minecraft:player") return;
  if (!damageSource?.damagingEntity) return; // ✅ skip non-attacker damage (fire, magic, fall, etc.)

  const state = parryStates.get(hurtEntity.id);
  const cooldown = parryCooldowns.get(hurtEntity.id);
  if (!state || !cooldown) return;

  // ✅ correct
  if (system.currentTick <= state.expiry) {
    // ✅ Parry successful
    parryStates.delete(hurtEntity.id);
    hurtEntity.addEffect("resistance", PARRY_WINDOW_TICKS + 10, { amplifier: PARRY_RESISTANCE, showParticles: true });
    const elapsed = system.currentTick - state.startTick;
    const isPerfect = elapsed <= 5; // test window

    const parry_volume = hurtEntity.getDynamicProperty("parry_volume");

    if (isPerfect) {
      hurtEntity.runCommand(`title @s actionbar §ePerfect Parry!`);
      hurtEntity.runCommand(`playsound perfect_parry @a ~~~ ${parry_volume}`);
      playAnimationWithClock(hurtEntity, AnimationHelper("animation.combat.parry_done", hurtEntity), 20);
      hurtEntity.runCommand(`camerashake add @s 0.8 1 positional`);
      hurtEntity.runCommand(`/particle imc_pa:perfect_parry ~~~`);
    } else {
      hurtEntity.runCommand(`title @s actionbar §aParry!`);
      hurtEntity.runCommand(`playsound parry @a ~~~ ${parry_volume}`);
      playAnimationWithClock(hurtEntity, AnimationHelper("animation.combat.parry_done", hurtEntity), 20);
      hurtEntity.runCommand(`camerashake add @s 0.5 1 positional`);
      hurtEntity.runCommand(`/particle imc_pa:parry ~~~`);
    }

    playSound(hurtEntity);

    if (damageSource?.damagingEntity) {
      const attacker = damageSource.damagingEntity;
      const damageCause = damageSource.cause;

      if (attacker.hasComponent("minecraft:health")) {
        const healthComp = attacker.getComponent("minecraft:health");
        const maxHealth = healthComp.effectiveMax;

        // Base % depending on parry type
        const percent = isPerfect ? 0.1 : 0.05;

        // Calculate reflect damage capped at 30% of max health
        const reflectDamage = Math.min(
        maxHealth * percent, // scale with current health
        maxHealth * 0.3 // but never exceed 30% of max
        );
        // console.warn(attacker.typeId)

        attacker.applyDamage(5 + reflectDamage, {
        cause: damageSource.cause
        });

        if (isPerfect) {
          attacker.addEffect("weakness", 200, { amplifier: 10, showParticles: true });
          attacker.addEffect("slowness", 100, { amplifier: 255, showParticles: true });
          attacker.addEffect("blindness", 120, { amplifier: 5, showParticles: true });
        } else {
          attacker.addEffect("weakness", 100, { amplifier: 5, showParticles: true });
          attacker.addEffect("slowness", 60, { amplifier: 2, showParticles: true });
          attacker.addEffect("blindness", 20, { amplifier: 5, showParticles: true });
        }

        const dx = attacker.location.x - hurtEntity.location.x;
        const dz = attacker.location.z - hurtEntity.location.z;
        const dist = Math.sqrt(dx * dx + dz * dz) || 1;
        if (attacker.typeId != "minecraft:player"){
          attacker.applyImpulse({
          x: (dx / dist) * 0.5,
          y: isPerfect ? 0.8 : 0.5,
          z: (dz / dist) * 0.5,
        })
        } else {
          attacker.applyKnockback((dx / dist) * 0.5, isPerfect ? 0.8 : 0.5,(dz / dist) * 0.5, 1)
        }
      }
    }
  }
});


