import { system, world, EquipmentSlot} from "@minecraft/server"
import { swordSweep, getWeaponType, isRangedWeapon} from "./combat_mechanic";
import { CombatAnimation, ENABLE_HIT_CHECK } from "./combat_config";

system.afterEvents.scriptEventReceive.subscribe((event) => {
  const entity = event.sourceEntity;
  if (!entity || entity.typeId !== "imc:entity_placeholder") return;

  if (event.id === "imc:tp") {
    let tags = entity.getTags();
    let tpTag = tags.find((tag) => tag.startsWith("id:"));
    entity.runCommand(
      // `tp @s @a[tag=${tpTag}]`
      `ride @s start_riding @p[tag=${tpTag}] teleport_rider`
    );
  }
});


world.afterEvents.entityHurt.subscribe((event) => {
  const entity = event.hurtEntity;
  if (!entity.getComponent("minecraft:health")) return;
  // if (entity.typeId !== "imc:entity_hit_check") return;

  const damage = event.damage;
  const source = event.damageSource;
  const player = source.damagingEntity;
  const projectile = source.damagingProjectile;

  if (!player || player.typeId !== "minecraft:player" || projectile) return;

  // --- Get weapon type and corresponding radius & angle ---
  const weaponType = getWeaponType(player.getComponent("minecraft:equippable")?.getEquipment(EquipmentSlot.Mainhand)?.typeId ?? "");
  const comboInfo = CombatAnimation[weaponType];
  // fallback if somehow missing
  const radius = comboInfo?.radius ?? 5;
  const angle = comboInfo?.angle ?? 60;
  // trigger swordSweep using dynamic radius & angle
  swordSweep(player, radius, angle, damage, source.cause);
});


// ----------------------
// Interval Check
// ----------------------
// Map to store each player's last known mode
const lastPlayerModes = new Map();

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    if (!ENABLE_HIT_CHECK) return;
    const usingRanged = isRangedWeapon(player);
    const projectileNearby = checkProjectilesNearPlayer(player, 5);
    const isRanged = usingRanged || projectileNearby;

    const mode = isRanged ? "ranged" : "normal";
    const lastMode = lastPlayerModes.get(player.id);

    // Only trigger when mode changes
    if (mode !== lastMode) {
      player.runCommand(`/event entity @e[type=imc:entity_hit_check,tag=id:${player.id}] ${mode}`);
      lastPlayerModes.set(player.id, mode);
    }
  }

  // Optional cleanup: remove entries for players who left
  for (const id of lastPlayerModes.keys()) {
    if (!world.getPlayers().some(p => p.id === id)) {
      lastPlayerModes.delete(id);
    }
  }
});



export function checkProjectilesNearPlayer(player, radius = 5) {
  const nearbyProjectiles = player.dimension.getEntities({
    location: player.location,
    maxDistance: radius,
  }).filter(e => e.hasComponent("projectile"));

  for (const entity of nearbyProjectiles) {
    if (entity.isOnGround === false || entity.isOnGround === undefined) {
      return true;
    }
  }
  return false;
}
