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

const MARKER = "kick:wendigo_altar";
const CANDLE = "minecraft:red_candle";

const pattern = [
  [1, 0, 0, CANDLE],
  [-1, 0, 0, CANDLE],
  [0, 0, 1, CANDLE],
  [0, 0, -1, CANDLE],
];

function checkStructure(dim, x, y, z) {
  for (const [dx, dy, dz, type] of pattern) {
    const block = dim.getBlock({ x: x + dx, y: y + dy, z: z + dz });
    if (!block || block.typeId !== type) return false;
    if (!block.permutation.getState("lit")) return false;
  }

  const center = dim.getBlock({ x, y, z });
  if (!center || center.typeId !== MARKER) return false;

  return true;
}

world.afterEvents.playerPlaceBlock.subscribe(ev => {
  const b = ev.block;
  const player = ev.player
  const dim = b.dimension;

  for (let dx = -1; dx <= 1; dx++) {
    for (let dy = -1; dy <= 1; dy++) {
      for (let dz = -1; dz <= 1; dz++) {

        const block = dim.getBlock({
          x: b.location.x + dx,
          y: b.location.y + dy,
          z: b.location.z + dz
        });

        if (block?.typeId === MARKER) {
          const { x, y, z } = block.location;
          if (checkStructure(dim, x, y, z)) {
            world.sendMessage("§c§lWENDIGO SHRINE COMPLETED");
            player.runCommand('effect @s darkness 3 20 true')
            system.run(() => {
              player.runCommand('fill ~-15 ~0 ~-15 ~15 ~14 ~15 air replace kick:wendigo_altar')
              player.runCommand('summon kick:wendigo_player_real ~ ~ ~1')
            })
          }
        }
      }
    }
  }
});