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

export function checkWater(event) {
  const entity = event.sourceEntity;
  const overworld = world.getDimension("overworld");

  // Origin: 2 blocks below the entity
  const origin = {
    x: Math.floor(entity.location.x),
    y: Math.floor(entity.location.y) - 2,
    z: Math.floor(entity.location.z),
  };

  // Block types to check against
  const validBlocks = [
    "minecraft:water",
    "minecraft:kelp",
    "minecraft:seagrass",
    "minecraft:coral_fan",
  ];

  let allBlocksValid = true;

  // Iterate through a 15x15 area and 5 blocks down
  for (let dx = -7; dx <= 7; dx++) {
    for (let dz = -7; dz <= 7; dz++) {
      for (let dy = 0; dy > -5; dy--) {
        const blockPos = {
          x: origin.x + dx,
          y: origin.y + dy,
          z: origin.z + dz,
        };

        // Get the block at the current position
        const block = overworld.getBlock(blockPos);

        // Ensure block exists and is of a valid type
        if (!block || !validBlocks.includes(block.typeId)) {
          allBlocksValid = false;
          break;
        }
      }
      if (!allBlocksValid) break;
    }
    if (!allBlocksValid) break;
  }

  // If all blocks are valid, send the message
  if (allBlocksValid) entity.runCommand(`summon sbs_tra:tentacles ~ ~ ~`);
}
