import { EffectType, system } from "@minecraft/server";
import { randomBuddyName } from "./getBuddyName";
import { checkBuddyProperties } from "./getBuddyPart";
import { roarAttack } from "./attack";

export function randomInt(min, max) {
  return min + ((Math.random() * (max - min + 1)) | 0);
}

system.afterEvents.scriptEventReceive.subscribe((eventData) => {
  if (eventData.id === "arcedge_bap:set_baby_properties") {
    const buddy_baby = eventData.sourceEntity;

    if (!buddy_baby) return;

    let closestPlayer = null;
    let closestDistanceSq = Infinity;

    const entityLocation = buddy_baby.location;

    for (const player of buddy_baby.dimension.getPlayers()) {
      const playerLocation = player.location;

      const dx = playerLocation.x - entityLocation.x;
      const dy = playerLocation.y - entityLocation.y;
      const dz = playerLocation.z - entityLocation.z;

      const distanceSq = dx * dx + dy * dy + dz * dz;

      if (distanceSq < closestDistanceSq) {
        closestDistanceSq = distanceSq;
        closestPlayer = player;
      }
    }

    if (closestPlayer.getDynamicProperty("first_baby_buddy_spawn") == false) {
      closestPlayer.sendMessage([
        {
          translate: "arcedge_bap.baby_buddy.summon"
        },
      ]);
      closestPlayer.setDynamicProperty("first_baby_buddy_spawn", true)
    }

    const head = randomInt(1, 16)
    const torso = randomInt(1, 16)
    const legs = randomInt(1, 16)

    buddy_baby.setProperty("arcedge_bap:head_part", head)
    buddy_baby.setProperty("arcedge_bap:torso_part", torso)
    buddy_baby.setProperty("arcedge_bap:legs_part", legs)

    buddy_baby.nameTag = randomBuddyName();

    buddy_baby.addEffect("instant_health", 1, {
      amplifier: 255,
      showParticles: false,
    });

    if (head == torso && torso == legs) {
      buddy_baby.triggerEvent("arcedge_bap:increase_base_stats")
    }

    if (head == 1 || torso == 1 || legs == 1)
      buddy_baby.triggerEvent("arcedge_bap:buddy_axoltol_abilities");
    if (head == 3 || torso == 3 || legs == 3)
      buddy_baby.triggerEvent("arcedge_bap:buddy_elephant_abilities");
    if (head == 7 || torso == 7 || legs == 7)
      buddy_baby.triggerEvent("arcedge_bap:buddy_lion_abilities");
    if (head == 9 || torso == 9 || legs == 9)
      buddy_baby.triggerEvent("arcedge_bap:buddy_mouse_abilities");
    if (head == 10 || torso == 10 || legs == 10)
      buddy_baby.triggerEvent("arcedge_bap:buddy_panther_abilities");
    if (head == 11 || torso == 11 || legs == 11)
      buddy_baby.triggerEvent("arcedge_bap:buddy_parrot_abilities");
    if (head == 14 || torso == 14 || legs == 14)
      buddy_baby.triggerEvent("arcedge_bap:buddy_tiger_abilities");
    if (head == 15 || torso == 15 || legs == 15)
      buddy_baby.triggerEvent("arcedge_bap:buddy_turtle_abilities");
  }

  if (eventData.id === "arcedge_bap:despawn_buddy_trader") {
    const buddy_trader = eventData.sourceEntity;
    buddy_trader.dimension.spawnParticle("arcedge_bap:disappear", {
      x: buddy_trader.location.x,
      y: buddy_trader.location.y + 1,
      z: buddy_trader.location.z,
    });
    system.runTimeout(() => {
      buddy_trader.triggerEvent("arcedge_bap:trigger_despawn");
    }, 10);
  }

  if (eventData.id === "arcedge_bap:tiger_roar_attack") {
    roarAttack(eventData.sourceEntity, "tiger");

    eventData.sourceEntity.dimension.playSound("arcedge_bap.buddy.roar", eventData.sourceEntity.location);
    system.runTimeout(() => {
      const nearbyEntities = eventData.sourceEntity.dimension.getEntities({
        location: eventData.sourceEntity.location,
        maxDistance: 8,
        excludeFamilies: ["arcedge_bap:buddy"],
      });

      for (const target of nearbyEntities) {
        try {
          if (
            target.id === eventData.sourceEntity.id ||
            eventData.sourceEntity.getComponent("minecraft:tameable")
              .tamedToPlayer == target
          )
            continue;
          target.applyDamage(8, { cause: "entityAttack" });

          const tLoc = target.location;
          const sLoc = eventData.sourceEntity.location;

          const dx = tLoc.x - sLoc.x;
          const dz = tLoc.z - sLoc.z;
          const magnitude = Math.sqrt(dx * dx + dz * dz) || 1;

          const direction = {
            x: dx / magnitude,
            z: dz / magnitude,
          };

          target.applyKnockback(direction, 0.7);
        } catch { }
      }
    }, 10);
  }

  if (eventData.id === "arcedge_bap:parrot_roar_attack") {
    roarAttack(eventData.sourceEntity, "parrot");
    eventData.sourceEntity.dimension.playSound("arcedge_bap.buddy.roar2", eventData.sourceEntity.location);
    system.runTimeout(() => {
      const nearbyEntities = eventData.sourceEntity.dimension.getEntities({
        location: eventData.sourceEntity.location,
        maxDistance: 8,
        excludeFamilies: ["arcedge_bap:buddy"],
      });

      for (const target of nearbyEntities) {
        try {
          if (
            target.id === eventData.sourceEntity.id ||
            eventData.sourceEntity.getComponent("minecraft:tameable")
              .tamedToPlayer == target
          )
            continue;

          target.addEffect("slowness", 80, { amplifier: 255, showParticles: true });
        } catch { }
      }
    }, 10);
  }
});
