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

const GRABPACK_MAP = {
  "mebesm:grabpack_blue": { proj: "mebesm:grabpack_blue_bullet", anim: "animation.grabpack.left_hand" },
  "mebesm:grabpack_blue_g": { proj: "mebesm:grabpack_blue_bullet", anim: "animation.grabpack.left_hand" },
  "mebesm:grabpack_blue_o": { proj: "mebesm:grabpack_blue_bullet", anim: "animation.grabpack.left_hand" },
  "mebesm:grabpack_blue_om": { proj: "mebesm:grabpack_blue_bullet", anim: "animation.grabpack.left_hand" },
  "mebesm:grabpack_blue_p": { proj: "mebesm:grabpack_blue_bullet", anim: "animation.grabpack.left_hand" },
  "mebesm:grabpack_blue_r": { proj: "mebesm:grabpack_blue_bullet", anim: "animation.grabpack.left_hand" },
  "mebesm:grabpack_green": { proj: "mebesm:grabpack_gren_bullet", anim: "animation.grabpack.right_hand" },
  "mebesm:grabpack_green_active": { proj: "mebesm:grabpack_gren_active_bullet", anim: "animation.grabpack.right_hand" },
  "mebesm:grabpack_omni": { proj: "mebesm:grabpack_omni_bullet", anim: "animation.grabpack.right_hand" },
  "mebesm:grabpack_orange": { proj: "mebesm:grabpack_orange_bullet", anim: "animation.grabpack.right_hand" },
  "mebesm:grabpack_purple": { proj: "mebesm:grabpack_purple_bullet", anim: "animation.grabpack.right_hand" },
  "mebesm:grabpack_red": { proj: "mebesm:grabpack_red_bullet", anim: "animation.grabpack.right_hand" },
  "mebesm:grabpack_green_and_blue": { proj: "mebesm:grabpack_gren_and_blue_bullet", anim: "animation.grabpack.left_right_hand" },
  "mebesm:grabpack_omni_and_blue": { proj: "mebesm:grabpack_omni_and_blue_bullet", anim: "animation.grabpack.left_right_hand" },
  "mebesm:grabpack_purple_and_blue": { proj: "mebesm:grabpack_purple_and_blue_bullet", anim: "animation.grabpack.left_right_hand" },
  "mebesm:grabpack_red_and_blue": { proj: "mebesm:grabpack_red_and_blue_bullet", anim: "animation.grabpack.left_right_hand" }
};

world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
  itemComponentRegistry.registerCustomComponent("grabpack:trigger", {
    onUse(event) {
      const { source: player, itemStack } = event;
      if (!player) return;

      const config = GRABPACK_MAP[itemStack.typeId];
      if (!config) return;

      const headLoc = player.getHeadLocation();
      const viewVec = player.getViewDirection();
      const spawnPos = {
        x: headLoc.x + viewVec.x * 1.5,
        y: headLoc.y + viewVec.y * 1.5,
        z: headLoc.z + viewVec.z * 1.5
      };

      try {
        // Спавним снаряд
        const projectile = player.dimension.spawnEntity(config.proj, spawnPos);

        // УСТАНАВЛИВАЕМ ВЛАДЕЛЬЦА (чтобы игра знала, кто выстрелил)
        const projComp = projectile.getComponent("minecraft:projectile");
        if (projComp) {
          projComp.owner = player;
        }

        projectile.applyImpulse({ x: viewVec.x * 3, y: viewVec.y * 3, z: viewVec.z * 3 });
      } catch (e) {
        console.warn(`Ошибка спавна: ${config.proj}`);
      }

      const sound = (itemStack.typeId === "mebesm:grabpack_orange") ? "grabpack_orange" : "grabpack";
      player.dimension.playSound(sound, player.location);

      system.run(() => {
        player.playAnimation(config.anim, { blendOutTime: 0.2 });
      });
    }
  });
});

// СПАВН ОГНЯ ПРИ УДАРЕ О БЛОК (тут проверка владельца не обязательна, но добавлена для безопасности)
world.afterEvents.projectileHitBlock.subscribe((event) => {
  if (event.projectile.typeId === "mebesm:grabpack_orange_bullet") {
    const loc = event.location;
    system.run(() => {
      event.dimension.spawnEntity("mebesm:fire", loc);
    });
  }
});

// СПАВН ОГНЯ ПРИ УДАРЕ В СУЩНОСТЬ (С ПРОВЕРКОЙ НА ВЛАДЕЛЬЦА)
world.afterEvents.projectileHitEntity.subscribe((event) => {
  if (event.projectile.typeId === "mebesm:grabpack_orange_bullet") {
    const hitEntity = event.getEntityHit().entity;
    const projectile = event.projectile;
    const projComp = projectile.getComponent("minecraft:projectile");
    const owner = projComp?.owner;

    // Если сущность, в которую попали — это НЕ тот, кто стрелял
    if (hitEntity.id !== owner?.id) {
      const loc = event.location;
      system.run(() => {
        event.dimension.spawnEntity("mebesm:fire", loc);
      });
    }
  }
});