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

export const tungsten_armor = {
  id: "tungsten",
  intervaloTicks: 0,
  piezas: [
    "dungeon:tungsten_helmet",
    "dungeon:tungsten_chestplate",
    "dungeon:tungsten_leggings",
    "dungeon:tungsten_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) {
    // --- 1. CARGA LENTA (ESCUDO fijo cada 30s si no lo tiene)
    data.lastShieldTime = data.lastShieldTime ?? 0;
    const now = Date.now();

    // Verifica si tiene absorción ya activa (no duplicar)
    const hasAbsorption = player.getEffect("absorption") !== undefined;

    if (now - data.lastShieldTime >= 30000 && !hasAbsorption) {
      player.runCommand("effect @s absorption 60 1 true");
      data.lastShieldTime = now;
    }

    // --- 2. CORAZÓN REFRACTARIO (RODEADO DE ENEMIGOS)
    const mobs = world.getDimension("overworld").getEntities({
      location: player.location,
      maxDistance: 5,
      families: ["monster"],
      excludeFamilies: ["player"]
    });

    data.lastSurrounded = data.lastSurrounded ?? 0;
    const surrounded = mobs.length >= 3;

    if (surrounded) {
      data.lastSurrounded = now;
      player.addEffect("resistance", 20, { amplifier: 2 });

    } else if (now - data.lastSurrounded < 3000) {
      player.addEffect("resistance", 20, { amplifier: 2 });
    }
  }
};
