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

// Same metadata used in the placement script
const paintingData = {
  "bps_paint:painting_1x1": { width: 1, height: 1, center: 1 },
  "bps_paint:painting_1x2": { width: 1, height: 2, center: 2 },
  "bps_paint:painting_2x1": { width: 2, height: 1, center: 2 },
  "bps_paint:painting_2x2": { width: 2, height: 2, center: 3 },
  "bps_paint:painting_2x3": { width: 2, height: 3, center: 4 },
  "bps_paint:painting_2x4": { width: 2, height: 4, center: 5 },
  "bps_paint:painting_3x2": { width: 3, height: 2, center: 4 },
  "bps_paint:painting_3x3": { width: 3, height: 3, center: 5 },
  "bps_paint:painting_4x2": { width: 4, height: 2, center: 5 },
  "bps_paint:painting_4x3": { width: 4, height: 3, center: 9 },
  "bps_paint:painting_4x4": { width: 4, height: 4, center: 11 },
  "bps_paint:painting_2x3": { width: 2, height: 3, center: 5 },
  "bps_paint:painting_2x4": { width: 2, height: 4, center: 7 },
  "bps_paint:painting_3x3": { width: 3, height: 3, center: 7 },
};

system.run(() => {
  world.beforeEvents.playerBreakBlock.subscribe(event => {
    const block = event.block;
    const dim = block.dimension;
    const typeId = block.typeId;

    const painting = paintingData[typeId];
    if (!painting) return;

    const partId = block.permutation.getState("bps_paint:part_id");
    const direction = block.permutation.getState("minecraft:cardinal_direction");
    const blockLoc = block.location;

    const base = getBaseLocation(blockLoc, partId, direction, painting.width, painting.height);
    if (!base) return;

    system.run(() => {
      removePainting(dim, base, direction, typeId, painting.width, painting.height);
    });
  });
});

function getBaseLocation(loc, partId, direction, width, height) {
  const index = partId - 1;
  const row = Math.floor(index / width);
  const col = index % width;

  const dy = row - (height - 1);
  let dx = 0, dz = 0;

  switch (direction) {
    case "north": dx = -col; break;
    case "south": dx = col; break;
    case "east":  dz = -col; break;
    case "west":  dz = col; break;
    default: return null;
  }

  return {
    x: loc.x + dx,
    y: loc.y + dy,
    z: loc.z + dz
  };
}

function removePainting(dim, base, direction, typeId, width, height) {
  for (let row = 0; row < height; row++) {
    for (let col = 0; col < width; col++) {
      let x = base.x;
      let y = base.y + (height - 1 - row);
      let z = base.z;

      switch (direction) {
        case "north": x += col; break;
        case "south": x -= col; break;
        case "east":  z += col; break;
        case "west":  z -= col; break;
      }

      try {
        const tBlock = dim.getBlock({ x, y, z });
        if (tBlock?.typeId === typeId) {
          const facing = tBlock.permutation.getState("minecraft:cardinal_direction");
          if (facing === direction) {
            tBlock.setType("minecraft:air");
          }
        }
      } catch {}
    }
  }
}
