import { EquipmentSlot, world, Player } from "@minecraft/server";

const ecoBuffCooldown = new Map();

function applyEcoBuffs(player) {
  const now = Date.now();
  const lastBuff = ecoBuffCooldown.get(player.id) ?? 0;

  if (now - lastBuff < 2500) return; // cooldown de 2.5 segundos
  if (Math.random() > 0.25) return;   // 25% de probabilidad

  const effects = [
    { id: "regeneration", duration: 200, amplifier: 0 },
    { id: "speed", duration: 200, amplifier: 0 },
    { id: "resistance", duration: 200, amplifier: 1 },
    { id: "absorption", duration: 200, amplifier: 0 }
  ];

  const randomEffect = effects[Math.floor(Math.random() * effects.length)];
  player.addEffect(randomEffect.id, randomEffect.duration, { amplifier: randomEffect.amplifier });

  ecoBuffCooldown.set(player.id, now);
}

export const jade_armor = {
  id: "jade",
  intervaloTicks: 0,
  piezas: [
    "dungeon:jade_helmet",
    "dungeon:jade_chestplate",
    "dungeon:jade_leggings",
    "dungeon:jade_boots"
  ],

  verificar(equip) {
    return this.piezas.every((id, i) => {
      const slot = [EquipmentSlot.Head, EquipmentSlot.Chest, EquipmentSlot.Legs, EquipmentSlot.Feet][i];
      const item = equip.getEquipment(slot);
      return item && item.typeId === id;
    });
  },

  actualizar(player, data) {
    const now = Date.now();
    const dim = world.getDimension("overworld");

    // --- AURA DE TRANQUILIDAD ---
    data.lastIgnoredCheck = data.lastIgnoredCheck ?? now;

    const mobs = dim.getEntities({
      location: player.location,
      maxDistance: 16,
      families: ["monster"],
      excludeFamilies: ["player"]
    });

    let ignored = true;

    for (const mob of mobs) {
      const look = mob.getViewDirection();
      const toPlayer = {
        x: player.location.x - mob.location.x,
        y: player.location.y - mob.location.y,
        z: player.location.z - mob.location.z
      };
      const dot = look.x * toPlayer.x + look.y * toPlayer.y + look.z * toPlayer.z;
      const distSq = toPlayer.x ** 2 + toPlayer.y ** 2 + toPlayer.z ** 2;

      // Si el mob te mira directamente y está cerca, rompe la "tranquilidad"
      if (dot > 0 && distSq < 16) {
        ignored = false;
        break;
      }
    }

    if (ignored) {
      if (now - data.lastIgnoredCheck >= 5000) {
        player.addEffect("regeneration", 320, { amplifier: 0 });
        data.lastIgnoredCheck = now;
      }
    } else {
      data.lastIgnoredCheck = now;
    }

    // --- ECO DEL ESPÍRITU ---

    // ⚡ Evento de golpe para eco espiritual
    world.afterEvents.entityHurt.subscribe(({ damageSource, hurtEntity, damage }) => {

      if (damage <= 0) return;
      const attacker = damageSource.damagingEntity;
      if (!(attacker instanceof Player)) return;
      const defender = hurtEntity;
      if (attacker.hasTag("jade_armor")) {
        applyEcoBuffs(attacker, defender, 0.5, 0.25);
      }

    })
  }
};
