// scripts/accessories/index.js
import { world, system, EffectTypes, EquipmentSlot } from "@minecraft/server";

export const INTERVAL = 20;
export const DUR = 40; // 2s (evita parpadeo)

let E = null;

function initEffects() {
  if (E) return;
  E = {
    blindness: EffectTypes.get("minecraft:blindness"),
    darkness: EffectTypes.get("minecraft:darkness"),
    slowFalling: EffectTypes.get("minecraft:slow_falling"),
    levitation: EffectTypes.get("minecraft:levitation"),
    speed: EffectTypes.get("minecraft:speed"),
    slowness: EffectTypes.get("minecraft:slowness"),
    haste: EffectTypes.get("minecraft:haste"),
    strength: EffectTypes.get("minecraft:strength"),
    healthBoost: EffectTypes.get("minecraft:health_boost"),
  };
}

function idOf(itemStack) {
  return itemStack?.typeId ?? null;
}
function getEq(player) {
  return player.getComponent("minecraft:equippable");
}
function safeAddEffect(player, effectType, amplifier = 0, duration = DUR) {
  if (!effectType) return;
  player.addEffect(effectType, duration, { amplifier, showParticles: false });
}
function safeRemoveEffect(player, effectType) {
  if (!effectType) return;
  if (player.getEffect(effectType)) player.removeEffect(effectType);
}
function setTag(player, tag, enabled) {
  if (enabled) {
    if (!player.hasTag(tag)) player.addTag(tag);
  } else {
    if (player.hasTag(tag)) player.removeTag(tag);
  }
}
function getEquipmentIds(player) {
  const eq = getEq(player);
  if (!eq) return null;
  return {
    [EquipmentSlot.Offhand]: idOf(eq.getEquipment(EquipmentSlot.Offhand)),
  };
}
function hasItemAnywhere(player, typeId) {
  const inv = player.getComponent("minecraft:inventory");
  if (!inv) return false;
  const c = inv.container;
  if (!c) return false;

  for (let i = 0; i < c.size; i++) {
    const it = c.getItem(i);
    if (it && it.typeId === typeId) return true;
  }
  return false;
}

function hasNearbyFamily(player, family, radius) {
  const dim = player.dimension;
  const loc = player.location;
  return dim.getEntities({ location: loc, maxDistance: radius, families: [family] }).length > 0;
}

function accessoriesTick(player, eqIds) {
  if (!E) return;

  const off = eqIds[EquipmentSlot.Offhand];

  // SILK MASK (inventario)
  const hasSilk = hasItemAnywhere(player, "dungeon:silk_mask");
  setTag(player, "silk_mask", hasSilk);
  if (player.hasTag("silk_mask")) {
    safeRemoveEffect(player, E.blindness);
    safeRemoveEffect(player, E.darkness);
     try { player.runCommand("fog @s remove dcave_fog"); } catch {}
  }

  // FEATHER HAT (offhand)
  if (off === "dungeon:feather_hat") {
    safeAddEffect(player, E.slowFalling, 255);
    safeRemoveEffect(player, E.levitation);
  }

  // CRYSTAL ARROW (offhand)
  const crystalArrow = off === "dungeon:crystal_arrow";
  setTag(player, "ammo_buff", crystalArrow);
  if (crystalArrow) {
     try { player.runCommand("kill @e[family=cursed_projectile,r=10]"); } catch {}
  }

  // LIGHTBOOTS (offhand)
  if (off === "dungeon:lightboots") {
    safeAddEffect(player, E.speed, 1);
    if (!player.hasTag("chitin")) safeRemoveEffect(player, E.slowness);
  }

  // MINER GLOVE (offhand)
  if (off === "dungeon:miner_glove") {
    safeAddEffect(player, E.haste, 2);
  }

  // HEAVY ROCK (offhand tag)
  setTag(player, "heavy_rock", off === "dungeon:heavy_rock");

  // MOONSTONE (offhand tag)
  setTag(player, "moonstone_item", off === "dungeon:moonstone");

  // SILVER RING (offhand + aura)
  if (off === "dungeon:silver_ring") {
    const bossNear = hasNearbyFamily(player, "undead_boss", 4.5);
    const undeadNear = hasNearbyFamily(player, "undead", 4.5);
    const werewolfNear = hasNearbyFamily(player, "werewolf", 4.5);

    if (bossNear) safeAddEffect(player, E.strength, 4);
    else if (undeadNear || werewolfNear) safeAddEffect(player, E.strength, 1);
  }

  // VAMPIRIC AMULET (inventario)
  setTag(player, "spectral_amulet", hasItemAnywhere(player, "dungeon:vampiric_amulet"));

  // HEARTS (offhand)
  if (off === "dungeon:ultimate_heart") safeAddEffect(player, E.healthBoost, 4);
  else if (off === "dungeon:super_heart") safeAddEffect(player, E.healthBoost, 2);
  else if (off === "dungeon:heart") safeAddEffect(player, E.healthBoost, 1);

  // TOTEM OF RECOVERY (inventario)
  setTag(player, "totemofrecovery", hasItemAnywhere(player, "dungeon:totemofrecovery"));
}

system.beforeEvents.startup.subscribe(() => {
  system.run(() => {
    initEffects();

    system.runInterval(() => {
      if (!E) return;

      for (const p of world.getAllPlayers()) {
        const eqIds = getEquipmentIds(p);
        if (!eqIds) continue;
        accessoriesTick(p, eqIds);
      }
    }, INTERVAL);
  });
});
