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

const POSE_MODIFIER_ITEM_ID = "mebesm:toy_pose_modifier";
const COOLDOWN_MS = 340;
const PLAYER_COOLDOWNS = new Map();

const createCycle = (baseId, count) => {
  const ids = [baseId];
  for (let i = 1; i <= count; i++) ids.push(`${baseId}${i}`);
  ids.push(baseId);
  return ids;
};

const BLOCK_CYCLES = {
  "mebesm:bron": createCycle("mebesm:bron", 6),
  "mebesm:boogie_bot": createCycle("mebesm:boogie_bot", 6),
  "mebesm:cat_bee": createCycle("mebesm:cat_bee", 6),
  "mebesm:huggy_wuggy_toy": createCycle("mebesm:huggy_wuggy_toy", 4),
  "mebesm:toy_huggy_box": createCycle("mebesm:toy_huggy_box", 6),
  "mebesm:boogie_bot_box": createCycle("mebesm:boogie_bot_box", 5),
  "mebesm:kissy_missy_toy": createCycle("mebesm:kissy_missy_toy", 4),
  "mebesm:candy_cat_box": createCycle("mebesm:candy_cat_box", 3),
  "mebesm:cube_yellow": createCycle("mebesm:cube_yellow", 3),
  "mebesm:cube_red": createCycle("mebesm:cube_red", 3),
  "mebesm:cube_blue": createCycle("mebesm:cube_blue", 3),
  "mebesm:cube_wooden": createCycle("mebesm:cube_wooden", 3),
  "mebesm:limon_toy": createCycle("mebesm:limon_toy", 3),
  "mebesm:barrel_red": createCycle("mebesm:barrel_red", 2),
  "mebesm:barrel_yellow": createCycle("mebesm:barrel_yellow", 2),
  "mebesm:barrel_blue": createCycle("mebesm:barrel_blue", 2),
};

const ALL_CYCLIC_BLOCKS = Object.values(BLOCK_CYCLES)
  .flat()
  .filter((id, index, self) => self.indexOf(id) === index);

const BLOCK_TO_BASE_ID = new Map();
for (const baseId in BLOCK_CYCLES) {
  const cycle = BLOCK_CYCLES[baseId];
  for (let i = 0; i < cycle.length - 1; i++) {
    BLOCK_TO_BASE_ID.set(cycle[i], baseId);
  }
}

function get_next_block_id(currentBlockId) {
  const baseId = BLOCK_TO_BASE_ID.get(currentBlockId);
  if (!baseId) return null;
  const cycle = BLOCK_CYCLES[baseId];
  const currentIndex = cycle.indexOf(currentBlockId);
  if (currentIndex !== -1 && currentIndex < cycle.length - 1) return cycle[currentIndex + 1];
  return null;
}

function getBlockDirectionState(block) {
  let blockStates = {};
  try {
    const direction = block.permutation.getState("minecraft:cardinal_direction");
    if (direction) blockStates = { "minecraft:cardinal_direction": direction };
  } catch { }
  return blockStates;
}

world.beforeEvents.itemUseOn.subscribe(event => {
  const { source, itemStack, block } = event;

  if (!(source instanceof Player) || !itemStack || itemStack.typeId !== POSE_MODIFIER_ITEM_ID) return;

  const currentBlockId = block.typeId;
  const player = source;

  if (!ALL_CYCLIC_BLOCKS.includes(currentBlockId)) return;

  const lastUseTime = PLAYER_COOLDOWNS.get(player.id) || 0;
  const currentTime = Date.now();

  if (currentTime - lastUseTime < COOLDOWN_MS) {
    event.cancel = true;
    return;
  }

  const nextBlockId = get_next_block_id(currentBlockId);

  if (nextBlockId) {
    event.cancel = true;
    PLAYER_COOLDOWNS.set(player.id, currentTime);

    system.run(() => {
      const directionStates = getBlockDirectionState(block);
      const newPermutation = BlockPermutation.resolve(nextBlockId, directionStates);
      block.setPermutation(newPermutation);

      const blockLocation = block.location;
      const particleLocation = {
        x: blockLocation.x + 0.5,
        y: blockLocation.y + 0.5,
        z: blockLocation.z + 0.5
      };

      block.dimension.spawnParticle("mebesm:toy_boom", particleLocation, newPermutation);
      block.dimension.playSound("mob.besmc_nightmare_huggy.hurt", blockLocation, {
        pitch: 1.0,
        volume: 1.0
      });
    });
  }
});