import { system } from "@minecraft/server";
import { ItemInventoryContents } from "../utilities.js";

export function summonSnowman(player, item) {
  system.run(() => {
    const dimension = player.dimension;
    const origin = player.location;
    const view = player.getViewDirection();

    const forward = {
      x: Math.round(view.x),
      z: Math.round(view.z),
    };

    // Get perpendicular direction for left/right (swap and negate)
    const left = { x: -forward.z, z: forward.x };
    const right = { x: forward.z, z: -forward.x };

    const contents = item
      ? new ItemInventoryContents(item).getContainer()?.content ?? []
      : [];

    const hasExtra = contents.some(
      (stack) => stack?.typeId === "pb_gat:orb_extra"
    );
    const hasPower = contents.some(
      (stack) => stack?.typeId === "pb_gat:orb_power"
    );
    const hasNitrogen = contents.some(
      (stack) => stack?.typeId === "pb_gat:orb_nitrogen"
    );
    const extendLife = contents.some(
      (stack) => stack?.typeId === "pb_gat:orb_life"
    );

    // Helper to spawn a turret at a location and tame it
    function spawnTurret(x, y, z, applyTags = {}, extendLife) {
      const entity = dimension.spawnEntity("pb_gat:snowman_turret", {
        x,
        y,
        z,
      });
      if (entity) {
        const tameComponent = entity.getComponent("minecraft:tameable");
        if (tameComponent) {
          tameComponent.tame(player);
        }
        if (extendLife) {
          entity.triggerEvent("pb_gat:extend_life");
        }

        if (applyTags.hasPower) {
          entity.addTag("pb_has_power");
        }
        if (applyTags.hasNitrogen) {
          entity.addTag("pb_has_nitrogen");
        }
      }
    }

    const y = Math.floor(origin.y);

    player.playSound("dig.powder_snow", {
      pitch: 0.9,
      volume: 1.5,
      location: player.location,
    });

    if (hasExtra) {
      const centerX = origin.x + forward.x * 2;
      const centerZ = origin.z + forward.z * 2;

      spawnTurret(
        centerX + left.x * 1.5,
        y + 0.5,
        centerZ + left.z * 1.5,
        {
          hasPower,
          hasNitrogen,
        },
        extendLife
      );
      spawnTurret(
        centerX + right.x * 1.5,
        y + 0.5,
        centerZ + right.z * 1.5,
        {
          hasPower,
          hasNitrogen,
        },
        extendLife
      );
    } else {
      const x = origin.x + forward.x * 2;
      const z = origin.z + forward.z * 2;
      spawnTurret(x, y + 0.5, z, { hasPower, hasNitrogen }, extendLife);
    }
  });
}
