import { system, world, ItemStack } from "@minecraft/server";
import "./break_painting.js";
import "./painting_ui.js";
import "./validate_space.js";

import giveASingleBook from "./giveSingleBook";
import { showMainMenuForm } from "./mainMenuForm";

// Painting size and center metadata
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: 1 },
  "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: 13 },
  "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.afterEvents.playerPlaceBlock.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");
    if (partId !== painting.center) return;

    const direction = block.permutation.getState("minecraft:cardinal_direction");
    const base = block.location;


    if (!isAreaClear(dim, base, direction, painting.width, painting.height, painting.center)) {
      try {
        dim.getBlock(base).setType("minecraft:air");

        const item = new ItemStack(typeId, 1);
        dim.spawnItem(item, {
          x: base.x + 0.5,
          y: base.y + 0.25,
          z: base.z + 0.5
        });

        event.player.runCommandAsync(
          `titleraw @s actionbar {"rawtext":[{"translate":"message.bps_paint:no_space.text"}]}`
        );

      } catch (e) {
      }
      return;
    }

    placePainting(dim, base, painting.width, painting.height, direction, painting.center, typeId);
  });
});

function placePainting(dim, base, width, height, direction, centerPart, typeId) {
  let part = 1;

  for (let row = 0; row < height; row++) {
    for (let col = 0; col < width; col++) {
      if (part === centerPart) {
        part++;
        continue;
      }

      let x = base.x;
      let y = base.y + (height - 1 - row);
      let z = base.z;

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

      placePart(dim, x, y, z, part, direction, typeId);
      part++;
    }
  }
}

function placePart(dim, x, y, z, part, direction, typeId) {
  try {
    const tBlock = dim.getBlock({ x, y, z });
    tBlock.setType(typeId);
    tBlock.setPermutation(
      tBlock.permutation
        .withState("bps_paint:part_id", part)
        .withState("minecraft:cardinal_direction", direction)
    );
  } catch (e) {
  }
}

function isAreaClear(dim, base, direction, width, height, centerPart) {
  let part = 1;

  for (let row = 0; row < height; row++) {
    for (let col = 0; col < width; col++) {
      if (part === centerPart) {
        part++;
        continue;
      }

      let x = base.x;
      let y = base.y + (height - 1 - row);
      let z = base.z;

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

      const block = dim.getBlock({ x, y, z });
      if (!block || (!block.isAir && block.typeId !== "minecraft:replaceable")) {
        return false;
      }

      part++;
    }
  }

  return true;
}





/* ====== CONFIG ====== */
const EASEL_TYPE_ID = "bps_paint:easel";

// What to drop (change these to your item and amount)
const DROP_ITEM_ID = "bps_paint:easel"; // e.g. "bps_paint:easel_item"
const DROP_ITEM_COUNT = 1;

// Only react to player-caused damage?
const PLAYER_ONLY = true;

// Prevent double-trigger per hit
const HANDLED_TAG = "bps_paint:handled";

/* ====== HIT → DROP + DESPAWN ====== */
world.afterEvents.entityHurt.subscribe((ev) => {
  const entity = ev.hurtEntity;
  if (!entity || entity.typeId !== EASEL_TYPE_ID) return;

  if (PLAYER_ONLY) {
    const src = ev.damageSource?.damagingEntity;
    if (!src || src.typeId !== "minecraft:player") return;
  }

  // Avoid multiple triggers in same moment
  if (entity.hasTag(HANDLED_TAG)) return;
  entity.addTag(HANDLED_TAG);

  const dim = entity.dimension;
  const pos = entity.location;

  // Spawn the configured item
  try {
    dim.spawnItem(new ItemStack(DROP_ITEM_ID, DROP_ITEM_COUNT), pos);
  } catch (e) {
    // Optional: log in chat if you need debugging
    // world.sendMessage(`[bps_paint DEBUG] spawnItem failed: ${e}`);
  }

  // Despawn the easel instantly
  try {
    entity.remove();
  } catch (e) {
    // world.sendMessage(`[bps_paint DEBUG] remove() failed: ${e}`);
  }
});








// Guide Book Stuff



const BOOK_ID = "bps_paint:guide_book" // Change this to be the name of your book item.

world.afterEvents.itemUse.subscribe(event => {
  if (event.itemStack.typeId != "bps_paint:guide_book") return;

  const player = event.source;

showMainMenuForm(player)
 
})

giveASingleBook({
	itemTypeId: BOOK_ID
});