import { world, system, Direction } from "@minecraft/server";
const cooldowns = /* @__PURE__ */ new Set();
const activeSeats = /* @__PURE__ */ new Map();
const seatCheckIntervals = /* @__PURE__ */ new Map();
const cooldownDuration = 5;
const SEAT_DATA_KEY = "maca_probuilder:seat_data";
let loadedSeatData = null;
world.afterEvents.worldInitialize.subscribe(() => {
  system.runTimeout(() => {
    loadedSeatData = loadSeatData();
  }, 10);
});
world.afterEvents.playerJoin.subscribe((event) => {
  system.runTimeout(() => {
    const { playerId } = event;
    if (!loadedSeatData || Object.keys(loadedSeatData).length === 0) {
      return;
    }
    const playerHasSeats = Object.values(loadedSeatData).some((seatData) => seatData.playerId === playerId);
    if (!playerHasSeats) {
      return;
    }
    const player = world.getAllPlayers().find((p) => p.id === playerId);
    if (player) {
      startPlayerMonitor(player);
    } else {
      return;
    }
  }, 50);
});
world.afterEvents.playerLeave.subscribe((event) => {
  const { playerId } = event;
  stopPlayerMonitor(playerId);
});
world.beforeEvents.worldInitialize.subscribe((eventData) => {
  eventData.blockComponentRegistry.registerCustomComponent(
    "maca_probuilder:sit_down",
    {
      onPlayerInteract(eventData2) {
        const player = eventData2.player;
        const blockLocation = eventData2.block.location;
        const dimension = world.getDimension(player.dimension.id);
        const currentBlock = eventData2.block;
        if (!currentBlock.hasTag("maca_probuilder:is_chair")) {
          return;
        }
        if (!player.isSneaking) {
          eventData2.cancel = true;
        }
        const blockFace = eventData2.blockFace;
        if (blockFace === Direction.Down)
          return;
        if (player.isSneaking)
          return;
        const playerY = Math.floor(player.location.y);
        if (!player.isOnGround || Math.abs(blockLocation.y - playerY) >= 3) {
          return;
        }
        const isSeatPresent = dimension.getEntities().some((entity) => {
          if (entity.typeId === "maca_probuilder:seat") {
            const entityLocation = entity.location;
            return Math.floor(entityLocation.x) === Math.floor(blockLocation.x) && Math.floor(entityLocation.y) === Math.floor(blockLocation.y) && Math.floor(entityLocation.z) === Math.floor(blockLocation.z);
          }
          return false;
        });
        if (isSeatPresent)
          return;
        const playerId = player.id;
        if (cooldowns.has(playerId))
          return;
        cooldowns.add(playerId);
        system.runTimeout(() => cooldowns.delete(playerId), cooldownDuration);
        system.runTimeout(() => {
          const blockPermutation = currentBlock.permutation;
          const cardinalDirection = blockPermutation.getState(
            "minecraft:cardinal_direction"
          );
          let seatRotation = 0;
          switch (cardinalDirection) {
            case "north":
              seatRotation = 0;
              break;
            case "west":
              seatRotation = 270;
              break;
            case "south":
              seatRotation = 180;
              break;
            case "east":
              seatRotation = 90;
              break;
            default:
              seatRotation = 0;
              break;
          }
          let offset = 0.35;
          if (currentBlock?.hasTag("maca_probuilder:low_chair")) {
            switch (currentBlock.typeId) {
              case "maca_probuilder:wooden_chair":
                offset = 0.2;
                break;
              case "maca_probuilder:wooden_stool":
                offset = 0.1;
                break;
              case "maca_probuilder:small_stool":
                offset = 0;
                break;
            }
          }
          const seat = dimension.spawnEntity("maca_probuilder:seat", {
            x: blockLocation.x + 0.5,
            y: blockLocation.y + offset,
            z: blockLocation.z + 0.5
          });
          seat.setRotation({ x: 0, y: seatRotation });
          seat.getComponent("rideable").addRider(player);
          activeSeats.set(seat.id, blockLocation);
          activeSeats.set(seat.id, {
            x: Math.floor(blockLocation.x),
            y: Math.floor(blockLocation.y),
            z: Math.floor(blockLocation.z),
            dimension: dimension.id,
            playerId: player.id
          });
          saveSeatData();
          startPlayerMonitor(player);
        }, 5);
      }
    }
  );
});
world.afterEvents.entityHurt.subscribe((eventData) => {
  const entity = eventData.hurtEntity;
  if (entity.typeId !== "minecraft:player")
    return;
  const player = entity;
  const dimension = world.getDimension(player.dimension.id);
  const seatEntities = dimension.getEntities().filter((e) => e.typeId === "maca_probuilder:seat");
  seatEntities.forEach((seatEntity) => {
    const distance = Math.sqrt(
      Math.pow(player.location.x - seatEntity.location.x, 2) + Math.pow(player.location.y - seatEntity.location.y, 2) + Math.pow(player.location.z - seatEntity.location.z, 2)
    );
    if (distance <= 0.5) {
      seatEntity.remove();
      activeSeats.delete(seatEntity.id);
      saveSeatData();
      const playerSeats = Array.from(activeSeats.values()).filter((seat) => seat.playerId === player.id);
      if (playerSeats.length === 0) {
        stopPlayerMonitor(player.id);
      }
    }
  });
});
function startPlayerMonitor(player) {
  if (!player || !player.id) {
    return;
  }
  if (seatCheckIntervals.has(player.id)) {
    return;
  }
  const interval = system.runInterval(() => {
    for (const [seatId, locationData] of activeSeats) {
      if (locationData.playerId !== player.id)
        continue;
      const seatEntity = world.getEntity(seatId);
      if (!seatEntity) {
        activeSeats.delete(seatId);
        saveSeatData();
        continue;
      }
      const dimension = world.getDimension(locationData.dimension);
      const currentBlock = dimension.getBlock(locationData);
      const isBlockRemoved = currentBlock.typeId === "minecraft:air" || currentBlock.typeId === "minecraft:water" || currentBlock.typeId === "minecraft:lava";
      const nearbyPlayers = dimension.getPlayers({
        location: seatEntity.location,
        maxDistance: 0.5
      });
      if (isBlockRemoved || nearbyPlayers.length === 0) {
        seatEntity.remove();
        activeSeats.delete(seatId);
        saveSeatData();
      }
    }
    const playerSeats = Array.from(activeSeats.values()).filter((seat) => seat.playerId === player.id);
    if (playerSeats.length === 0) {
      stopPlayerMonitor(player.id);
    }
  }, 10);
  seatCheckIntervals.set(player.id, interval);
}
function stopPlayerMonitor(playerId) {
  if (seatCheckIntervals.has(playerId)) {
    system.clearRun(seatCheckIntervals.get(playerId));
    seatCheckIntervals.delete(playerId);
  }
}
function saveSeatData() {
  const seatData = Object.fromEntries(activeSeats);
  world.setDynamicProperty(SEAT_DATA_KEY, JSON.stringify(seatData));
}
function loadSeatData() {
  const seatData = world.getDynamicProperty(SEAT_DATA_KEY);
  if (seatData) {
    const parsedData = JSON.parse(seatData);
    for (const [seatId, locationData] of Object.entries(parsedData)) {
      activeSeats.set(seatId, locationData);
    }
    return parsedData;
  } else {
    return null;
  }
}
