// data/scripts/playerSpawn.ts
import { ItemStack, system, world } from "@minecraft/server";
var spawnPoint = { x: 22, y: 122, z: 31 };
world.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;
  const joined = player.hasTag("joined");
  const introduction = player.hasTag("introduction");
  world.gameRules.sendCommandFeedback = false;
  if (!joined && !introduction) {
    player.setSpawnPoint({ ...spawnPoint, dimension: player.dimension });
    player.teleport(spawnPoint);
    player.addTag("joined");
    const inv = player.getComponent("inventory")?.container;
    if (!inv) return;
    const guideBook = new ItemStack("isb:guide_book", 1);
    inv.addItem(guideBook);
    system.runTimeout(() => {
      const existingObjective = world.scoreboard.getObjective("introduction");
      if (!existingObjective) {
        world.scoreboard.addObjective("introduction");
      }
      world.scoreboard.getObjective("introduction")?.setScore(player, 1);
      player.addTag("introduction");
    }, 8);
  }
  if (world.getDynamicProperty("isb:world_loaded")) return;
  world.setDynamicProperty("isb:world_loaded", true);
  player.runCommand("scriptevent isb:start");
});
system.runInterval(() => {
  for (const player of world.getPlayers({ tags: ["introduction"] })) {
    player.runCommand("function cinematics/introduction");
  }
});

// data/scripts/custom_components/customComponents.ts
import { system as system5 } from "@minecraft/server";

// data/scripts/custom_components/blocks/horizontalBlock.ts
import { world as world2, system as system2 } from "@minecraft/server";

// data/scripts/utils/blocks.ts
var shovelBlocks = [
  "minecraft:dirt",
  "minecraft:grass_block",
  "minecraft:coarse_dirt",
  "minecraft:podzol",
  "minecraft:mycelium",
  "minecraft:rooted_dirt"
];
var axeBlocks = [
  "minecraft:oak_log",
  "minecraft:spruce_log",
  "minecraft:birch_log",
  "minecraft:jungle_log",
  "minecraft:acacia_log",
  "minecraft:dark_oak_log",
  "minecraft:mangrove_log",
  "minecraft:crimson_stem",
  "minecraft:warped_stem",
  "minecraft:cherry_log",
  "minecraft:pale_oak_log",
  "minecraft:oak_wood",
  "minecraft:spruce_wood",
  "minecraft:birch_wood",
  "minecraft:jungle_wood",
  "minecraft:acacia_wood",
  "minecraft:dark_oak_wood",
  "minecraft:mangrove_wood",
  "minecraft:crimson_hyphae",
  "minecraft:warped_hyphae",
  "minecraft:cherry_wood",
  "minecraft:pale_oak_wood"
];
var hoeBlocks = [
  "minecraft:dirt",
  "minecraft:grass_block",
  "minecraft:coarse_dirt",
  "minecraft:podzol",
  "minecraft:mycelium",
  "minecraft:rooted_dirt"
];
function updateBlockState(block, state) {
  let permutation = block.permutation;
  for (const [key, value] of Object.entries(state)) {
    permutation = permutation.withState(key, value);
  }
  block.setPermutation(permutation);
}

// data/scripts/custom_components/blocks/horizontalBlock.ts
var HorizontalBlockComponent = class {
  onPlace(arg) {
    const block = arg.block;
    const facing = block.permutation.getState("minecraft:cardinal_direction");
    const isPairedBit = block.permutation.getState("isb:right_block_bit");
    if (isPairedBit) return;
    const offset = getOffsetFromFacing(facing);
    if (!offset) return;
    const pairedBlock = block.offset(offset);
    if (pairedBlock && !(pairedBlock.isAir || pairedBlock.isLiquid)) {
      HorizontalBlockManager.breakPairedBlock(block, true);
      return;
    }
    if (pairedBlock && (pairedBlock.isAir || pairedBlock.isLiquid) && !block.permutation.getState("isb:right_block_bit")) {
      HorizontalBlockManager.placePairedBlock(block, pairedBlock, facing);
    }
  }
  onTick(arg) {
    const block = arg.block;
    const facing = block.permutation.getState("minecraft:cardinal_direction");
    const isPairedBit = block.permutation.getState("isb:right_block_bit");
    const offset = getOffsetFromFacing(facing);
    if (!offset) return;
    const pairedBlock = block.offset(offset);
    const reverseOffset = { x: -offset.x, y: -offset.y, z: -offset.z };
    const reversePairedBlock = block.offset(reverseOffset);
    if (!isPairedBit && pairedBlock?.typeId !== block.typeId) {
      HorizontalBlockManager.breakPairedBlock(block, true);
    }
    if (isPairedBit && reversePairedBlock?.typeId !== block.typeId) {
      HorizontalBlockManager.breakPairedBlock(block, true);
    }
  }
};
world2.beforeEvents.playerBreakBlock.subscribe((data) => {
  const block = data.block;
  if (!block.hasTag("isb:table") && !block.hasTag("isb:wall_shelf")) return;
  const isPairedBit = block.permutation.getState("isb:right_block_bit");
  const facing = block.permutation.getState("minecraft:cardinal_direction");
  if (!facing) return;
  const offset = getOffsetFromFacing(facing);
  if (!offset) return;
  const otherOffset = isPairedBit ? { x: -offset.x, y: -offset.y, z: -offset.z } : offset;
  const otherBlock = block.offset(otherOffset);
  if (!otherBlock) return;
  HorizontalBlockManager.breakPairedBlock(otherBlock, false);
});
var HorizontalBlockManager = class {
  static placePairedBlock(originBlock, pairedBlock, facing) {
    pairedBlock.setType(originBlock.typeId);
    updateBlockState(pairedBlock, { "isb:right_block_bit": true, "minecraft:cardinal_direction": facing });
  }
  static breakPairedBlock(block, destroy) {
    system2.run(() => {
      const loc = block.location;
      if (destroy) block.dimension.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air destroy`);
      block.dimension.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air`);
    });
  }
};
function getOffsetFromFacing(facing) {
  switch (facing) {
    case "north":
      return { x: -1, y: 0, z: 0 };
    case "south":
      return { x: 1, y: 0, z: 0 };
    case "west":
      return { x: 0, y: 0, z: 1 };
    case "east":
      return { x: 0, y: 0, z: -1 };
  }
  return void 0;
}

// data/scripts/custom_components/blocks/miniTotem.ts
import { world as world6 } from "@minecraft/server";

// data/scripts/islands/islandConfig.ts
var ISLAND_SPACING = 80;
var HEIGHT_VARIANCE = 4;
var BASE_Y_LEVEL = 64;
var islandData = {
  zero: {
    path: "spawnisland",
    location: {
      x: 0,
      y: BASE_Y_LEVEL,
      z: 0
    }
  },
  red: [
    { path: "redislands/redisland_1", probability: 25 },
    { path: "redislands/redisland_2", probability: 22 },
    { path: "redislands/redisland_3", probability: 18 },
    { path: "redislands/redisland_4", probability: 15 },
    { path: "redislands/bigredisland_1", probability: 12 },
    { path: "redislands/bigredisland_2", probability: 10 },
    { path: "redislands/bigredisland_3", probability: 8 },
    { path: "redislands/bigredisland_4", probability: 7 },
    { path: "redislands/bigredisland_5", probability: 5 },
    { path: "redislands/bigredisland_6", probability: 4 },
    { path: "redislands/bigredisland_7", probability: 4 },
    { path: "redislands/bigredisland_8", probability: 4 }
  ],
  yellow: [
    { path: "yellowislands/yellowisland_1", probability: 20 },
    { path: "yellowislands/yellowisland_2", probability: 15 },
    { path: "yellowislands/yellowisland_3", probability: 10 },
    { path: "yellowislands/yellowisland_4", probability: 15 }
  ],
  green: [
    { path: "greenislands/greenisland_1", probability: 25 },
    { path: "greenislands/greenisland_2", probability: 25 },
    { path: "greenislands/greenisland_3", probability: 25 },
    { path: "greenislands/greenisland_4", probability: 25 }
  ],
  special: [
    { path: "specialislands/specialisland_1", probability: 10 },
    { path: "specialislands/specialisland_2", probability: 10 },
    { path: "specialislands/specialisland_3", probability: 18 },
    { path: "specialislands/specialisland_4", probability: 20 }
  ]
};
var bossPaths = [
  "specialislands/specialisland_1",
  "specialislands/specialisland_2"
];
var uniquePaths = [
  "redislands/bigredisland_2",
  "redislands/bigredisland_8"
];

// data/scripts/utils/area.ts
function calculateAllowedArea(start) {
  const opposite = { x: start.x + ISLAND_SPACING, z: start.z + ISLAND_SPACING };
  return [start, opposite];
}
function getCornerFromLocation(pos) {
  const xBase = Math.floor(pos.x / ISLAND_SPACING) * ISLAND_SPACING;
  const zBase = Math.floor(pos.z / ISLAND_SPACING) * ISLAND_SPACING;
  return { x: xBase, y: BASE_Y_LEVEL, z: zBase };
}

// data/scripts/utils/database.ts
import { world as world3 } from "@minecraft/server";
var typeMap = {
  red: "r",
  green: "g",
  yellow: "y",
  special: "s",
  main: "m"
};
var reverseTypeMap = Object.fromEntries(
  Object.entries(typeMap).map(([k, v]) => [v, k])
);
function encodeType(type) {
  return typeMap[type] ?? type;
}
function decodeType(code) {
  return reverseTypeMap[code] ?? code;
}
function compressAreaData(data) {
  return {
    p: [data.position.x, data.position.y, data.position.z],
    a: data.area,
    t: encodeType(data.type),
    s: data.started ? 1 : 0,
    d: data.completed ? 1 : 0,
    h: data.path
  };
}
function decompressAreaData(data) {
  const [x, y, z] = data.p;
  return {
    position: { x, y, z },
    area: data.a,
    type: decodeType(data.t),
    started: data.s === 1,
    completed: data.d === 1,
    path: data.h
  };
}
function vec3Key(vec) {
  return `${vec.x},${vec.y},${vec.z}`;
}
function keyFromCompressed(p) {
  return `${p[0]},${p[1]},${p[2]}`;
}
var MAX_SIZE = 32e3;
var countProp = "allowed_areas_count";
function saveAreaData(data) {
  const compressed = compressAreaData(data);
  const keyToInsert = keyFromCompressed(compressed.p);
  const jsonEntry = JSON.stringify(compressed);
  let count = world3.getDynamicProperty(countProp) ?? 0;
  for (let i = 0; i < count; i++) {
    const key = `allowed_areas_${i}`;
    const raw = world3.getDynamicProperty(key);
    if (!raw) continue;
    const batch = JSON.parse(raw);
    const filtered = batch.filter((entry) => keyFromCompressed(entry.p) !== keyToInsert);
    if (filtered.length !== batch.length) {
      world3.setDynamicProperty(key, JSON.stringify(filtered));
    }
  }
  for (let i = 0; i <= count; i++) {
    const key = `allowed_areas_${i}`;
    const raw = world3.getDynamicProperty(key);
    if (!raw) {
      world3.setDynamicProperty(key, JSON.stringify([compressed]));
      if (i === count) world3.setDynamicProperty(countProp, count + 1);
      return;
    }
    const batch = JSON.parse(raw);
    const newSize = raw.length + jsonEntry.length;
    if (newSize < MAX_SIZE) {
      batch.push(compressed);
      world3.setDynamicProperty(key, JSON.stringify(batch));
      return;
    }
    if (i === count) {
      world3.setDynamicProperty(key, JSON.stringify([compressed]));
      world3.setDynamicProperty(countProp, count + 1);
      return;
    }
  }
}
function getAllAreaData() {
  const count = world3.getDynamicProperty(countProp) ?? 0;
  const all = [];
  for (let i = 0; i < count; i++) {
    const raw = world3.getDynamicProperty(`allowed_areas_${i}`);
    if (!raw) continue;
    const batch = JSON.parse(raw);
    all.push(...batch.map(decompressAreaData));
  }
  return all;
}
function getAreaDataFromVec3(pos) {
  try {
    const key = vec3Key(pos);
    const all = getAllAreaData();
    return all.find((data) => vec3Key(data.position) === key);
  } catch {
    return void 0;
  }
}
function updateAreaProperty(pos, updates) {
  const current = getAreaDataFromVec3(pos);
  if (!current) return false;
  const updated = {
    ...current,
    ...updates
  };
  saveAreaData(updated);
  return true;
}

// data/scripts/utils/quest.ts
import { world as world5 } from "@minecraft/server";

// data/scripts/utils/inventory.ts
function searchItem(entity, itemId, requiredAmount) {
  const inv = entity.getComponent("inventory")?.container;
  if (!inv) return;
  const foundSlots = [];
  let total = 0;
  for (let i = 0; i < inv.size; i++) {
    const item = inv.getItem(i);
    if (item && item.typeId === itemId) {
      total += item.amount;
      foundSlots.push(i);
      if (total >= requiredAmount) {
        return { slots: foundSlots, totalAmount: total };
      }
    }
  }
  return void 0;
}
function consumeItems(entity, itemId, amountToConsume) {
  const inv = entity.getComponent("inventory")?.container;
  if (!inv) return;
  const result = searchItem(entity, itemId, amountToConsume);
  if (!result) return false;
  let remaining = amountToConsume;
  for (const slot of result.slots) {
    const item = inv.getItem(slot);
    if (!item) continue;
    if (item.amount > remaining) {
      const newItem = decreaseItem(item, remaining);
      inv.setItem(slot, newItem);
      break;
    } else {
      remaining -= item.amount;
      inv.setItem(slot, void 0);
    }
  }
  return true;
}
function decreaseItem(item, amount) {
  if (item.amount > amount) {
    item.amount = item.amount - amount;
    return item;
  } else {
    return void 0;
  }
}

// data/scripts/utils/island.ts
import { system as system3, TicksPerSecond, world as world4 } from "@minecraft/server";
var IslandUtils = class {
  static pickByProbability(islands, count) {
    const selectedIslands = [];
    const pool = [...islands];
    for (let i = 0; i < count; i++) {
      if (pool.length === 0) break;
      const pick = this.pickOne(pool);
      if (pick) {
        selectedIslands.push(pick);
        const index = pool.findIndex((i2) => i2.path === pick.path);
        if (index !== -1) pool.splice(index, 1);
      }
    }
    return selectedIslands;
  }
  static pickOne(islands) {
    const total = islands.reduce((sum, island) => sum + island.probability, 0);
    const rand = Math.random() * total;
    let cumulative = 0;
    for (const island of islands) {
      cumulative += island.probability;
      if (rand < cumulative) return island;
    }
    return null;
  }
};
var InitialIslandGenerator = class {
  static generate() {
    const { red, green, yellow } = islandData;
    const filteredRed = red.filter((island) => !island.path.includes("big"));
    const selectedRed = IslandUtils.pickByProbability(filteredRed, 1)[0];
    const selectedGreen = IslandUtils.pickByProbability(green, 1)[0];
    const selectedYellow = IslandUtils.pickByProbability(yellow, 1)[0];
    const remaining = [
      ...filteredRed,
      ...green,
      ...yellow
    ].filter(
      (island) => island.path !== selectedRed?.path && island.path !== selectedGreen?.path && island.path !== selectedYellow?.path
    );
    const randomPick = IslandUtils.pickByProbability(remaining, 1)[0];
    return [selectedRed, selectedGreen, selectedYellow, randomPick].filter(Boolean);
  }
};
var timerTick = 0;
var TimeTick = class {
  static setTimeTick(tick) {
    timerTick = tick;
  }
  static getTimeTick() {
    return timerTick;
  }
};
var IslandGenerator = class {
  static getUsedSpecials() {
    const raw = world4.getDynamicProperty("isb:used_specials");
    return raw ? JSON.parse(raw) : [];
  }
  static setUsedSpecials(used) {
    world4.setDynamicProperty("isb:used_specials", JSON.stringify(used));
  }
  static generate() {
    const usedSpecials = this.getUsedSpecials();
    const all = [
      ...islandData.red.filter((s) => !usedSpecials.includes(s.path)),
      ...islandData.green.filter((s) => !usedSpecials.includes(s.path)),
      ...islandData.yellow.filter((s) => !usedSpecials.includes(s.path)),
      ...islandData.special.filter((s) => !usedSpecials.includes(s.path))
    ];
    const selected = IslandUtils.pickByProbability(all, 4);
    const newUsed = [...usedSpecials];
    for (const island of selected) {
      if (uniquePaths.some((s) => s === island.path) && !newUsed.includes(island.path)) {
        newUsed.push(island.path);
      }
    }
    this.setUsedSpecials(newUsed);
    return selected;
  }
  static resetSpecials() {
    this.setUsedSpecials([]);
  }
};
function assignIslandPositions(islands, center) {
  const offsets = [
    { x: -ISLAND_SPACING, z: 0 },
    { x: 0, z: ISLAND_SPACING },
    { x: ISLAND_SPACING, z: 0 },
    { x: 0, z: -ISLAND_SPACING }
  ];
  return islands.slice(0, 4).map((island, index) => {
    const offset = offsets[index];
    return {
      location: {
        x: center.x + offset.x,
        y: randomYOffset(BASE_Y_LEVEL),
        z: center.z + offset.z
      },
      path: island.path
    };
  });
}
function generateIslands(entity, islands, main) {
  const allTickingAreas = [];
  islands.forEach((entry, i) => {
    const entityLoc = {
      x: entry.location.x,
      y: BASE_Y_LEVEL,
      z: entry.location.z
    };
    system3.runTimeout(() => {
      const name = `dummy_${randomInteger(1, 100)}_${i}`;
      entity.runCommand(`tickingarea add circle ${entityLoc.x} ${entityLoc.y} ${entityLoc.z} 4 ${name}`);
      allTickingAreas.push(entityLoc);
      if (i === islands.length - 1) {
        system3.runTimeout(() => {
          startGeneration(islands, allTickingAreas, entity, main);
        }, 10);
      }
    }, i * 5);
  });
}
function startGeneration(allIslands, allTickingAreas, entity, main) {
  const dimension = entity.dimension;
  let generatedCount = 0;
  allIslands.forEach((island) => {
    waitForChunkLoad(dimension, island.location, () => {
      const entityLoc = {
        x: island.location.x,
        y: BASE_Y_LEVEL,
        z: island.location.z
      };
      const data = getAreaDataFromVec3(entityLoc);
      if (!data) {
        const cornerEntity = dimension.spawnEntity("isb:corner", entityLoc);
        cornerEntity.setDynamicProperty("isb:corner_location", entityLoc);
        saveAreaData({
          position: entityLoc,
          area: calculateAllowedArea({ x: island.location.x, z: island.location.z }),
          type: getIslandType(island.path),
          started: false,
          completed: false,
          path: island.path
        });
        system3.runTimeout(() => {
          world4.structureManager.place(island.path, dimension, island.location);
        }, 4);
        generatedCount++;
      } else {
      }
    });
  });
  system3.runTimeout(() => {
    if (generatedCount > 0 && !main) {
      const bossIsland = containsBossPath(allIslands, bossPaths);
      const titleColor = bossIsland.found ? "\xA75" : "\xA77";
      if (bossIsland.found) {
        entity.runCommand(`playsound mob.enderdragon.growl @a ~ ~ ~ 1 1.5`);
      }
    }
  }, 70);
  clearTickingAreas(allTickingAreas, entity, 8);
}
function waitForChunkLoad(dimension, location, callback, attempts = 0) {
  try {
    dimension.getBlock(location);
    callback();
  } catch (e) {
    system3.runTimeout(() => {
      waitForChunkLoad(dimension, location, callback, attempts + 1);
    }, 5);
  }
}
function clearTickingAreas(locations, entity, delay) {
  system3.runTimeout(() => {
    for (const loc of locations) {
      entity.runCommand(`tickingarea remove ${loc.x} ${loc.y} ${loc.z}`);
    }
  }, delay * TicksPerSecond);
}
function containsBossPath(islands, bosses) {
  for (const island of islands) {
    if (bosses.includes(island.path)) {
      return { found: true, path: island.path };
    }
  }
  return { found: false };
}
function getIslandType(path) {
  if (path === islandData.zero.path) return "main";
  const groups = ["red", "yellow", "green", "special"];
  for (const group of groups) {
    if (islandData[group].some((island) => island.path === path)) {
      return group;
    }
  }
  return "none";
}
function randomInteger(min, max) {
  if (min > max) [min, max] = [max, min];
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomYOffset(base) {
  return base + Math.floor(Math.random() * (2 * HEIGHT_VARIANCE + 1)) - HEIGHT_VARIANCE;
}
function getAllPossibleIslands() {
  return [
    ...islandData.red,
    ...islandData.yellow,
    ...islandData.green,
    ...islandData.special
  ];
}
function assignAllIslandsToGrid(islands, startCenter) {
  const gridSize = Math.ceil(Math.sqrt(islands.length));
  const selectedIslands = [];
  islands.forEach((island, index) => {
    const row = Math.floor(index / gridSize);
    const col = index % gridSize;
    const location = {
      x: startCenter.x + (col - gridSize / 2) * ISLAND_SPACING * 1.5,
      y: randomYOffset(BASE_Y_LEVEL),
      z: startCenter.z + (row - gridSize / 2) * ISLAND_SPACING * 1.5
    };
    selectedIslands.push({
      location,
      path: island.path
    });
  });
  return selectedIslands;
}

// data/scripts/utils/quest.ts
var validBerries = [
  "minecraft:sweet_berries",
  "minecraft:glow_berries"
];
var questsTier = {
  easy: [
    { items: { "minecraft:carrot": 12, "minecraft:potato": 8, "minecraft:dirt": 5 } },
    { items: { "minecraft:cornflower": 9, "minecraft:wheat": 6 } },
    { items: { "minecraft:cornflower": 15, "minecraft:azure_bluet": 6 } }
  ],
  normal: [
    { items: { "minecraft:carrot": 24, "minecraft:wheat": 15, "minecraft:potato": 9 } },
    { items: { "minecraft:pumpkin": 12, "minecraft:apple": 9, "minecraft:potato": 9 } },
    { items: { "minecraft:cornflower": 18, "minecraft:beetroot": 15, "minecraft:string": 9 } }
  ],
  hard: [
    { items: { "minecraft:wheat": 48, "minecraft:melon_slice": 24, "minecraft:iron_nugget": 18 } },
    { items: { "minecraft:apple": 3, "minecraft:pumpkin": 15, "minecraft:waterlily": 9 } },
    { items: { "minecraft:golden_carrot": 23, "minecraft:azure_bluet": 12, "minecraft:honey_bottle": 2 } }
  ]
};
function missionCompleted(player, fadeIn = 1, fadeOut = 1, stay = 5) {
  player.runCommand(`titleraw @s times 15 30 15`);
  player.runCommand(`title @s title title_mission_complete`);
  player.runCommand(`titleraw @s times 0 0 0`);
  world5.setTimeOfDay(TimeTick.getTimeTick());
}
function generateRandomQuest() {
  const tiers = Object.keys(questsTier);
  const tier = tiers[Math.floor(Math.random() * tiers.length)];
  const questList = questsTier[tier];
  const quest = questList[Math.floor(Math.random() * questList.length)];
  return { tier, quest };
}
function formatItemName(itemId) {
  const name = itemId.includes(":") ? itemId.split(":")[1] : itemId;
  return name.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
function handleYellowQuestDelivery(entity, quest) {
  const inventory = entity.getComponent("inventory")?.container;
  entity.nameTag = "\xA76\xA7lYellow Totem";
  if (!inventory) return;
  let missing = false;
  for (const itemId in quest.items) {
    const requiredAmount = quest.items[itemId];
    if (itemId === "minecraft:berries") {
      let totalBerries = 0;
      for (const berry of validBerries) {
        const result = searchItem(entity, berry, requiredAmount);
        if (result) totalBerries += result.totalAmount;
      }
      if (totalBerries < requiredAmount) {
        missing = true;
        break;
      }
    } else {
      const result = searchItem(entity, itemId, requiredAmount);
      if (!result) {
        missing = true;
        break;
      }
    }
  }
  if (missing) return;
  for (const itemId in quest.items) {
    const requiredAmount = quest.items[itemId];
    if (itemId === "minecraft:berries") {
      let remaining = requiredAmount;
      for (const berry of validBerries) {
        const available = searchItem(entity, berry, remaining);
        if (!available) continue;
        const consumeAmount = Math.min(available.totalAmount, remaining);
        const success = consumeItems(entity, berry, consumeAmount);
        if (success) remaining -= consumeAmount;
        if (remaining <= 0) break;
      }
    } else {
      consumeItems(entity, itemId, requiredAmount);
    }
  }
  const altarID = entity.getDynamicProperty("isb:altar_id");
  const altar = world5.getEntity(altarID);
  if (!altar) return;
  const cornerLoc = getCornerFromLocation(entity.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData) return;
  altar.setProperty("isb:quest_completed", true);
  altar.setProperty("isb:animation", "give");
  altar.setDynamicProperty("isb:rewarded", true);
  updateAreaProperty(areaData.position, { completed: true });
  entity.triggerEvent("isb:drop_inventory");
  entity.runCommand(`titleraw @a[r=30] times 15 30 15`);
  entity.runCommand(`title @a[r=30] title ""`);
  entity.runCommand(`title @a[r=30] title title_new_island_spawning`);
  entity.runCommand(`titleraw @a[r=30] times 0 0 0`);
  entity.runCommand("playsound random.levelup @a[r=30] ~ ~ ~ 1");
}

// data/scripts/custom_components/blocks/miniTotem.ts
var ACTIVED_PERM = "isb:actived";
var MiniTotemComponent = class {
  onPlayerInteract(arg) {
    const block = arg.block;
    const player = arg.player;
    const cornerLoc = getCornerFromLocation(block.location);
    const areaData = getAreaDataFromVec3(cornerLoc);
    if (!areaData) return;
    if (areaData.completed) {
      player.sendMessage("\xA77[\xA7a!\xA77] This mission is completed.");
      player.playSound("block.end_portal_frame.fill", { location: player.location, volume: 1, pitch: 0.6 });
      return;
    }
    if (block.permutation.getState(ACTIVED_PERM)) {
      player.sendMessage("\xA77[\xA7c!\xA77] This totem has already been found.");
      return;
    }
    const cornerEntity = block.dimension.getEntities({ type: "isb:corner", location: cornerLoc, maxDistance: 2 })[0];
    if (!cornerEntity) return;
    const altarID = cornerEntity.getDynamicProperty("isb:altar_id");
    if (!altarID) {
      player.sendMessage("\xA77[\xA7e!\xA77] Find the \xA7aGreen Altar\xA77 to begin your mission.");
      player.playSound("block.end_portal_frame.fill", { location: player.location, volume: 1, pitch: 0.6 });
      return;
    }
    const altar = world6.getEntity(altarID);
    if (!altar) return;
    const maxMiniTotems = altar.getDynamicProperty("isb:max_mini_totems");
    if (!maxMiniTotems || maxMiniTotems === 0) return;
    const miniTotems = altar.getDynamicProperty("isb:mini_totems") ?? 0;
    const newMiniTotems = miniTotems + 1;
    altar.setDynamicProperty("isb:mini_totems", newMiniTotems);
    updateBlockState(block, { "isb:actived": true });
    player.sendMessage(`\xA77[\xA7b!\xA77] You have found \xA7b${newMiniTotems}\xA77/\xA7b${maxMiniTotems}\xA77 mini totems.`);
    player.playSound("random.levelup", { location: player.location, volume: 1, pitch: 1 });
    if (newMiniTotems >= maxMiniTotems) {
      updateAreaProperty(areaData.position, { completed: true });
      missionCompleted(player);
    }
  }
};

// data/scripts/custom_components/items/cooldown.ts
var CooldownComponent = class {
  onUse(arg) {
    if (arg.itemStack) triggerCooldown(arg.source, arg.itemStack);
  }
};
function triggerCooldown(source, item) {
  const cooldown = item?.getComponent("minecraft:cooldown");
  cooldown?.startCooldown(source);
}

// data/scripts/utils/item.ts
import { EquipmentSlot, GameMode } from "@minecraft/server";
function handleItemDurability(player, itemStack, amount = 1) {
  const durability = itemStack.getComponent("minecraft:durability");
  const enchantable = itemStack.getComponent("minecraft:enchantable");
  if (!durability) return;
  const actualDurability = durability.maxDurability - durability.damage;
  const unbreakingLevel = enchantable?.getEnchantment("unbreaking")?.level || 0;
  const isCreative = player.getGameMode() === GameMode.Creative;
  const chance = getDamageChance(unbreakingLevel);
  if (!isCreative && Math.random() < chance) {
    if (actualDurability > amount) {
      durability.damage += amount;
      player.getComponent("minecraft:equippable")?.setEquipment(EquipmentSlot.Mainhand, itemStack);
    } else {
      player.getComponent("minecraft:equippable")?.setEquipment(EquipmentSlot.Mainhand, void 0);
      player.playSound("random.break", { location: player.location, volume: 1, pitch: 1 });
    }
  }
}
function getDamageChance(unbreakingLevel) {
  switch (unbreakingLevel) {
    case 1:
      return 0.7;
    case 2:
      return 0.5;
    case 3:
      return 0.4;
    default:
      return 1;
  }
}

// data/scripts/custom_components/items/durability.ts
var DurabilityComponent = class {
  onMineBlock(arg) {
    const player = arg.source;
    const item = arg.itemStack;
    if (!item) return;
    handleItemDurability(player, arg.itemStack);
  }
};

// data/scripts/custom_components/items/onUseTool.ts
import { world as world7 } from "@minecraft/server";
var OnUseToolComponent = class {
  onUseOn(arg) {
  }
};
world7.afterEvents.itemStartUseOn.subscribe((event) => {
  const { itemStack: item, block, source: player } = event;
  if (!item) return;
  const itemId = item.typeId;
  const isShovel = itemId.includes("_shovel") && shovelBlocks.includes(block.typeId);
  const isAxe = itemId.includes("_axe") && axeBlocks.includes(block.typeId);
  const isHoe = itemId.includes("_hoe") && hoeBlocks.includes(block.typeId);
  if ((isShovel || isAxe || isHoe) && item.hasComponent("isb:on_use_tool_component")) {
    handleItemDurability(player, item);
  }
});

// data/scripts/custom_components/items/umbryteMace.ts
import { EntityDamageCause, TicksPerSecond as TicksPerSecond3 } from "@minecraft/server";
var UmbryteMaceComponent = class {
  onUse(arg) {
    const player = arg.source;
    const item = arg.itemStack;
    if (!item) return;
    const entities = player.dimension.getEntities({
      location: player.location,
      maxDistance: 4
    });
    handleItemDurability(player, item);
    for (const entity of entities) {
      if (entity.id === player.id) continue;
      const dx = entity.location.x - player.location.x;
      const dz = entity.location.z - player.location.z;
      const length = Math.sqrt(dx * dx + dz * dz);
      if (length === 0) continue;
      const strength = 1.5;
      const knockbackX = dx / length * strength;
      const knockbackZ = dz / length * strength;
      try {
        entity.applyKnockback({ x: knockbackX, z: knockbackZ }, 0.5);
        entity.applyDamage(4, { cause: EntityDamageCause.entityAttack, damagingEntity: player });
      } catch (error) {
      }
      entity.addEffect("slowness", 4 * TicksPerSecond3, { amplifier: 255, showParticles: false });
    }
  }
};

// data/scripts/custom_components/customComponents.ts
system5.beforeEvents.startup.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("isb:horizontal_block_component", new HorizontalBlockComponent());
  event.blockComponentRegistry.registerCustomComponent("isb:mini_totem_component", new MiniTotemComponent());
  event.itemComponentRegistry.registerCustomComponent("isb:cooldown_component", new CooldownComponent());
  event.itemComponentRegistry.registerCustomComponent("isb:durability_component", new DurabilityComponent());
  event.itemComponentRegistry.registerCustomComponent("isb:on_use_tool_component", new OnUseToolComponent());
  event.itemComponentRegistry.registerCustomComponent("isb:umbryte_mace_component", new UmbryteMaceComponent());
});

// data/scripts/entities/titanium_revenant.ts
import { EntityDamageCause as EntityDamageCause2, GameMode as GameMode2, ItemStack as ItemStack3, system as system6, world as world8 } from "@minecraft/server";
function parseParams(message) {
  const params = {};
  for (const part of message.split(" ")) {
    const [key, value] = part.split("=");
    if (key && value) params[key] = parseFloat(value);
  }
  return params;
}
function getTargetPosition(source, viewDir, offset) {
  return {
    x: source.location.x + viewDir.x * offset,
    y: source.location.y + viewDir.y * offset,
    z: source.location.z + viewDir.z * offset
  };
}
system6.afterEvents.scriptEventReceive.subscribe(({ id, sourceEntity: source, message }) => {
  if (id !== "isb:area_attack" || !source) return;
  const { offset = 2, radius = 2, damage = 6, knockback = 0, knockbackH = 0, knockbackV = 0 } = parseParams(message);
  const viewDir = source.getViewDirection();
  const targetPos = getTargetPosition(source, viewDir, offset);
  const nearby = source.dimension.getEntities({
    location: targetPos,
    maxDistance: radius,
    excludeGameModes: [GameMode2.Creative, GameMode2.Spectator],
    excludeTypes: [
      "minecraft:item",
      "minecraft:xp_orb",
      "minecraft:arrow",
      "minecraft:thrown_trident",
      "minecraft:snowball",
      "minecraft:ender_pearl"
    ],
    excludeFamilies: ["dummy", "container", "minecart", "arrow", "projectile", "bullet"]
  });
  let hitCount = 0;
  for (const entity of nearby) {
    if (entity.id === source.id) continue;
    try {
      entity.applyDamage(damage, {
        cause: EntityDamageCause2.entityAttack,
        damagingEntity: source
      });
      if (knockback > 0 || knockbackH > 0 || knockbackV > 0) {
        const x = viewDir.x * knockback * knockbackH;
        const z = viewDir.z * knockback * knockbackH;
        entity.applyKnockback({ x, z }, knockbackV);
      }
      hitCount++;
    } catch (e) {
    }
  }
});
world8.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  if (entity.typeId !== "isb:titanium_revenant_loot") return;
  const count = Math.floor(Math.random() * 3) + 5;
  const item = new ItemStack3("isb:titanium_scale", count);
  entity.dimension.spawnItem(item, entity.location);
});

// data/scripts/entities/board.ts
import { world as world9 } from "@minecraft/server";
var CONFIG = {
  BOARD_ENTITY_ID: "isb:board",
  ARROW_ENTITY_ID: "isb:board_arrow",
  PLAYER_ENTITY_ID: "minecraft:player",
  DIRECTION_PROPERTY: "isb:direction",
  BOARD_PROPERTY: "isb:board",
  BOARD_ID_PROPERTY: "isb:board_id",
  DIRECTIONS: {
    LEFT: "left",
    RIGHT: "right"
  },
  MAX_IMAGE_INDEX: 5,
  MIN_IMAGE_INDEX: 0
};
var BoardSystem = class {
  static initialize() {
    world9.afterEvents.entitySpawn.subscribe(this.handleEntitySpawn.bind(this));
    world9.afterEvents.entityHitEntity.subscribe(this.handleEntityHit.bind(this));
    world9.afterEvents.playerInteractWithEntity.subscribe(this.handlePlayerInteraction.bind(this));
  }
  static handleEntitySpawn(event) {
    const entity = event.entity;
    if (entity.typeId !== CONFIG.BOARD_ENTITY_ID) return;
    this.createArrowsForBoard(entity);
  }
  static handleEntityHit(event) {
    this.handleArrowInteraction(event.damagingEntity, event.hitEntity);
  }
  static handlePlayerInteraction(event) {
    this.handleArrowInteraction(event.player, event.target);
  }
  static createArrowsForBoard(boardEntity) {
    try {
      const leftArrow = boardEntity.dimension.spawnEntity(CONFIG.ARROW_ENTITY_ID, boardEntity.location);
      const rightArrow = boardEntity.dimension.spawnEntity(CONFIG.ARROW_ENTITY_ID, boardEntity.location);
      ArrowManager.setDirection(leftArrow, CONFIG.DIRECTIONS.LEFT);
      ArrowManager.setDirection(rightArrow, CONFIG.DIRECTIONS.RIGHT);
      ArrowManager.linkToBoard(leftArrow, boardEntity.id);
      ArrowManager.linkToBoard(rightArrow, boardEntity.id);
      this.addArrowsAsRiders(boardEntity, leftArrow, rightArrow);
    } catch (error) {
    }
  }
  static addArrowsAsRiders(board, leftArrow, rightArrow) {
    try {
      const rideable = board.getComponent("rideable");
      if (!rideable) {
        console.warn("Board entity does not have rideable component");
        return;
      }
      rideable.addRider(leftArrow);
      rideable.addRider(rightArrow);
    } catch (error) {
    }
  }
  static handleArrowInteraction(player, target) {
    if (!ValidationHelper.isValidArrowInteraction(player, target)) return;
    ArrowManager.processArrowClick(target);
  }
};
var ArrowManager = class {
  static setDirection(arrow, direction) {
    try {
      arrow.setProperty(CONFIG.DIRECTION_PROPERTY, direction);
    } catch (error) {
    }
  }
  static linkToBoard(arrow, boardId) {
    try {
      arrow.setDynamicProperty(CONFIG.BOARD_ID_PROPERTY, boardId);
    } catch (error) {
    }
  }
  static processArrowClick(arrow) {
    try {
      const direction = arrow.getProperty(CONFIG.DIRECTION_PROPERTY);
      const boardId = arrow.getDynamicProperty(CONFIG.BOARD_ID_PROPERTY);
      if (!direction || !boardId) {
        console.warn("Arrow missing direction or board ID");
        return;
      }
      const board = world9.getEntity(boardId);
      if (!board) {
        console.warn("Board entity not found");
        return;
      }
      ImageManager.updateBoardImage(board, direction);
    } catch (error) {
    }
  }
};
var ImageManager = class {
  static updateBoardImage(board, direction) {
    try {
      const currentImage = board.getProperty(CONFIG.BOARD_PROPERTY);
      const newImage = this.calculateNewImageIndex(currentImage, direction);
      board.setProperty(CONFIG.BOARD_PROPERTY, newImage);
    } catch (error) {
    }
  }
  static calculateNewImageIndex(currentIndex, direction) {
    if (direction === CONFIG.DIRECTIONS.LEFT) {
      return currentIndex === CONFIG.MIN_IMAGE_INDEX ? CONFIG.MAX_IMAGE_INDEX : currentIndex - 1;
    } else if (direction === CONFIG.DIRECTIONS.RIGHT) {
      return currentIndex === CONFIG.MAX_IMAGE_INDEX ? CONFIG.MIN_IMAGE_INDEX : currentIndex + 1;
    }
    console.warn(`Unknown direction: ${direction}`);
    return currentIndex;
  }
};
var ValidationHelper = class {
  static isValidArrowInteraction(player, target) {
    return target.typeId === CONFIG.ARROW_ENTITY_ID && player.typeId === CONFIG.PLAYER_ENTITY_ID;
  }
  static isBoardEntity(entity) {
    return entity.typeId === CONFIG.BOARD_ENTITY_ID;
  }
  static isArrowEntity(entity) {
    return entity.typeId === CONFIG.ARROW_ENTITY_ID;
  }
};
BoardSystem.initialize();

// data/scripts/entities/spawners.ts
import { system as system7, world as world10 } from "@minecraft/server";
var CONFIG2 = {
  spawners: {
    "isb:yellow_spawner": [
      {
        type: "minecraft:villager",
        limit: { min: 3, max: 4 }
      },
      {
        type: "minecraft:iron_golem",
        limit: 2
      }
    ],
    "isb:green_spawner": {
      type: [
        "minecraft:chicken",
        "minecraft:cow",
        "minecraft:pig",
        "minecraft:sheep",
        "isb:bear",
        "isb:butterfly",
        "isb:crocodile",
        "isb:elk",
        "isb:lion",
        "isb:rhinoceros",
        "isb:snail"
      ],
      limit: { min: 2, max: 3 }
    },
    "isb:villager_furn_spawner": {
      type: "isb:villager_furntrader",
      limit: 1
    }
  },
  radius: 15
};
system7.runInterval(() => {
  for (const player of world10.getPlayers({ tags: ["joined"] })) {
    const spawners = player.dimension.getEntities({ families: ["isb_spawners"], location: player.location, maxDistance: 16 });
    if (spawners.length <= 0) continue;
    for (const spawner of spawners) {
      if (!spawner || !spawner.isValid) continue;
      const entity = spawner;
      const spawnerType = entity.typeId;
      const spawnerConfig = CONFIG2.spawners[spawnerType];
      if (!spawnerConfig) return;
      const dimension = entity.dimension;
      const configs = Array.isArray(spawnerConfig) ? spawnerConfig : [spawnerConfig];
      let spawnedAny = false;
      for (const config of configs) {
        const mobType = config.type;
        const mobLimit = getMobLimit(config.limit);
        for (let i = 0; i < mobLimit; i++) {
          const spawnPos = getRandomNearbyPosition(entity.location, CONFIG2.radius, dimension);
          if (spawnPos) {
            const chosenMobType = Array.isArray(mobType) ? mobType[Math.floor(Math.random() * mobType.length)] : mobType;
            const spawned = dimension.spawnEntity(chosenMobType, spawnPos);
            if (spawned) spawnedAny = true;
          }
        }
      }
      if (spawnedAny) entity.remove();
    }
  }
}, 20);
function getMobLimit(limit) {
  if (typeof limit === "number") {
    return limit;
  } else if (limit && typeof limit.min === "number" && typeof limit.max === "number") {
    const min = Math.max(0, Math.floor(limit.min));
    const max = Math.max(min, Math.floor(limit.max));
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  return 1;
}
function getRandomNearbyPosition(center, radius, dimension) {
  for (let i = 0; i < 20; i++) {
    const dx = (Math.random() * 2 - 1) * radius;
    const dz = (Math.random() * 2 - 1) * radius;
    const x = Math.floor(center.x + dx);
    const z = Math.floor(center.z + dz);
    const baseY = Math.floor(center.y);
    for (let dy = 2; dy >= -3; dy--) {
      const y = baseY + dy;
      const ground = dimension.getBlock({ x, y: y - 1, z });
      const air = dimension.getBlock({ x, y, z });
      if (ground && ground.typeId !== "minecraft:air" && air?.typeId === "minecraft:air") {
        return { x, y, z };
      }
    }
  }
  return null;
}

// data/scripts/entities/dragon.ts
import { ItemStack as ItemStack4, system as system8, world as world11 } from "@minecraft/server";
world11.afterEvents.dataDrivenEntityTrigger.subscribe(({ entity: e, eventId: id }) => {
  if (e.typeId == "isb:dragon_generic_tamed" && (id == "isb:ground_fireball_attack" || id == "isb:fly_fireball_attack")) {
    system8.runTimeout(() => {
      if (e.getComponent("minecraft:can_fly")) {
        e.runCommand("playanimation @s ice_breath root 2.33");
      }
      const projectileEntity = e.dimension.spawnEntity("isb:dragon_fireball", { x: e.getHeadLocation().x, y: e.getHeadLocation().y - 1, z: e.getHeadLocation().z });
      e.runCommand("playsound mob.ghast.fireball @p");
      const projectile = projectileEntity.getComponent("projectile");
      projectile.owner = e;
      projectile.shoot({ x: e.getViewDirection().x * 4, y: e.getViewDirection().y * 2, z: e.getViewDirection().z * 4 });
    }, 20);
  }
});
world11.afterEvents.entityHurt.subscribe(({ damageSource: source, hurtEntity: hit }) => {
  const cause = source.cause;
  const damaging = source.damagingEntity;
  if (damaging && damaging.typeId.includes("isb:dragon_generic") && hit) {
    hit.addTag("target");
  }
  if (damaging && hit.typeId.includes("isb:dragon_generic")) {
    damaging.addTag("target");
  }
  if (damaging && damaging.typeId.includes("isb:dragon_generic") && hit && damaging.getComponent("minecraft:is_illager_captain")) {
    const direction = {
      x: hit.location.x - damaging.location.x,
      y: hit.location.y - damaging.location.y,
      z: hit.location.z - damaging.location.z
    };
    const magnitude = Math.sqrt(direction.x * direction.x + direction.z * direction.z);
    const normalized = {
      x: direction.x / magnitude,
      z: direction.z / magnitude
    };
    const hStrength = 1.5;
    const vStrength = 0.5;
    hit.applyKnockback({ x: normalized.x * hStrength, z: normalized.z * hStrength }, vStrength);
  }
  if (damaging && damaging.typeId.includes("isb:dragon_generic_tamed") && hit && damaging.getProperty("isb:tail_attack") == true) {
    const direction = {
      x: hit.location.x - damaging.location.x,
      y: hit.location.y - damaging.location.y,
      z: hit.location.z - damaging.location.z
    };
    const magnitude = Math.sqrt(direction.x * direction.x + direction.z * direction.z);
    const normalized = {
      x: direction.x / magnitude,
      z: direction.z / magnitude
    };
    const hStrength = 1.5;
    const vStrength = 0.5;
    hit.applyKnockback({ x: normalized.x * hStrength, z: normalized.z * hStrength }, vStrength);
  }
  if (damaging && damaging.typeId.includes("isb:dragon_generic_tamed") && hit && damaging.getProperty("isb:step_ground_attack") == true) {
    const direction = {
      x: hit.location.x - damaging.location.x,
      y: hit.location.y - damaging.location.y,
      z: hit.location.z - damaging.location.z
    };
    const magnitude = Math.sqrt(direction.x * direction.x + direction.z * direction.z);
    const normalized = {
      x: direction.x / magnitude,
      z: direction.z / magnitude
    };
    const hStrength = 1;
    const vStrength = 1.5;
    hit.applyKnockback({ x: normalized.x * hStrength, z: normalized.z * hStrength }, vStrength);
  }
  if (damaging && damaging.typeId.includes("isb:flame") && hit && cause == "contact") {
    hit.setOnFire(5);
  }
});
world11.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  if (!entity || !entity.isValid) return;
  const dimension = entity.dimension;
  const location = entity.location;
  if (entity.typeId !== "isb:dragon_generic_loot") return;
  const count = Math.floor(Math.random() * 3) + 3;
  const item = new ItemStack4("isb:black_dragon_scale", count);
  dimension.spawnItem(item, location);
  for (let i = 0; i < 20; i++) {
    dimension.spawnEntity("minecraft:xp_orb", location);
  }
});

// data/scripts/islands/islandManager.ts
import { system as system9 } from "@minecraft/server";
system9.afterEvents.scriptEventReceive.subscribe((event) => {
  const id = event.id;
  const entity = event?.sourceEntity;
  if (id === "isb:start" && entity) {
    const center = islandData.zero.location;
    const islands = InitialIslandGenerator.generate();
    const placedIslands = assignIslandPositions(islands, center);
    generateIslands(entity, [{ location: center, path: "spawnisland" }, ...placedIslands], true);
  } else if (id === "isb:spawn_random" && entity && entity.typeId === "isb:corner") {
    const center = entity.getDynamicProperty("isb:corner_location");
    const islands = IslandGenerator.generate();
    const placedIslands = assignIslandPositions(islands, center);
    generateIslands(entity, placedIslands, false);
  } else if (id === "isb:unlock_all" && entity) {
    let allPossibleIslands = getAllPossibleIslands();
    const center = islandData.zero.location;
    const bossIslands = islandData.special.filter(
      (island) => bossPaths.includes(island.path)
    );
    const hasBossIsland = allPossibleIslands.some(
      (island) => bossPaths.includes(island.path)
    );
    if (!hasBossIsland && bossIslands.length > 0) {
      const randomBossIsland = bossIslands[Math.floor(Math.random() * bossIslands.length)];
      allPossibleIslands = [randomBossIsland, ...allPossibleIslands];
    }
    const allIslandsToGenerate = assignAllIslandsToGrid(allPossibleIslands, center);
    generateIslands(entity, allIslandsToGenerate, false);
    system9.runTimeout(() => {
      const allAreas = getAllAreaData();
      let unlockedCount = 0;
      let generatedCount = 0;
      for (const area of allAreas) {
        if (!area.completed) {
          const success = updateAreaProperty(area.position, { completed: true });
          if (success) {
            unlockedCount++;
            const isNewIsland = allIslandsToGenerate.some(
              (island) => Math.abs(area.position.x - island.location.x) < 1 && Math.abs(area.position.z - island.location.z) < 1
            );
            if (isNewIsland) {
              generatedCount++;
            }
          }
        }
      }
      if (unlockedCount > 0) {
        entity.runCommand(`titleraw @a[r=100] times 15 30 15`);
        entity.runCommand(`title @a[r=100] title ""`);
        entity.runCommand(`title @a[r=100] title {"rawtext":[{"text":"\xA7aAll islands have been unlocked!"}]}`);
        entity.runCommand(`title @a[r=100] subtitle {"rawtext":[{"text":"\xA77${unlockedCount} islands unlocked (${generatedCount} new)"}]}`);
        entity.runCommand(`titleraw @a[r=100] times 0 0 0`);
        entity.runCommand("playsound random.levelup @a[r=100] ~ ~ ~ 1");
      }
    }, 200);
  }
});

// data/scripts/islands/islandHelper.ts
import { Player as Player4, system as system10, world as world12 } from "@minecraft/server";
var BOSS_CONFIGS = {
  "specialislands/specialisland_1": {
    entity: "isb:titanium_revenant",
    offset: { x: 28.5, y: 39, z: 30.5 },
    rotation: { y: 90, x: 0 }
  },
  "specialislands/specialisland_2": {
    entity: "isb:dragon_generic",
    offset: { x: 28, y: 80, z: 31 },
    rotation: { y: 90, x: 0 }
  }
};
var colorCodes = {
  special: "\xA75",
  green: "\xA7a",
  yellow: "\xA7e",
  red: "\xA7c"
};
world12.afterEvents.entityDie.subscribe((event) => {
  if (event.deadEntity instanceof Player4) {
    world12.setTimeOfDay(TimeTick.getTimeTick());
  }
});
system10.runInterval(() => {
  for (const player of world12.getPlayers({ excludeTags: ["introduction"] })) {
    const currentCorner = getCornerFromLocation(player.location);
    const currentPosKey = `${Math.floor(player.location.x)}_${Math.floor(player.location.z)}`;
    const lastPosKey = player.getDynamicProperty("isb:last_pos");
    if (lastPosKey === currentPosKey) continue;
    player.setDynamicProperty("isb:last_pos", currentPosKey);
    const areaData = getAreaDataFromVec3(currentCorner);
    if (!areaData) continue;
    const currentCornerKey = `${currentCorner.x}_${currentCorner.z}`;
    const lastCornerKey = player.getDynamicProperty("isb:last_corner");
    const lastAreaType = player.getDynamicProperty("isb:last_areaType");
    if (currentCornerKey !== lastCornerKey) {
      player.setDynamicProperty("isb:last_corner", currentCornerKey);
      player.setDynamicProperty("isb:last_areaType", areaData.type);
      if (lastAreaType === "red" && areaData.type !== "red") {
        player.runCommand(`titleraw @s times 0 0 0`);
        player.runCommand(`title @s title ""`);
        player.runCommand(`titleraw @s title {"rawtext":[{"text":"hud:dungeon:hide_ui"}]}`);
        world12.setTimeOfDay(TimeTick.getTimeTick());
      }
      const getColorCode = (type) => colorCodes[type] || "\xA77";
      let displayType = areaData.type;
      if (areaData.type === "special" && (areaData.path === "specialislands/specialisland_3" || areaData.path === "specialislands/specialisland_4")) {
        displayType = "green";
      }
      const typeCapitalized = displayType.charAt(0).toUpperCase() + displayType.slice(1);
      const color = getColorCode(displayType);
      if (!areaData.started && areaData.type !== "none" && areaData.type !== "special" && areaData.type !== "main") {
        player.onScreenDisplay.setActionBar(`\xA77Find the ${color}${typeCapitalized} Altar\xA77 to begin your mission.`);
      } else if (!areaData.completed && areaData.type !== "none" && areaData.type !== "main") {
        if (bossPaths.includes(areaData.path)) {
          player.onScreenDisplay.setActionBar(`\xA77Defeat the boss and find the ${color}${typeCapitalized} Altar\xA77.`);
        } else if (!areaData.started) {
          player.onScreenDisplay.setActionBar(`\xA77Find the ${color}${typeCapitalized} Altar\xA77 to begin your mission.`);
        }
      }
    }
    const bossConfig = BOSS_CONFIGS[areaData.path];
    if (bossConfig && !areaData.started) {
      try {
        const bossLoc = {
          x: areaData.position.x + bossConfig.offset.x,
          y: areaData.position.y + bossConfig.offset.y,
          z: areaData.position.z + bossConfig.offset.z
        };
        const boss = player.dimension.spawnEntity(bossConfig.entity, bossLoc);
        boss.setDynamicProperty("isb:corner_loc", areaData.position);
        boss.teleport(bossLoc, { rotation: bossConfig.rotation });
        updateAreaProperty(areaData.position, { started: true, completed: areaData.completed });
      } catch (error) {
      }
    }
  }
}, 5);

// data/scripts/islands/preventConstruction.ts
import { BlockVolume, BlockVolumeIntersection, Direction, system as system11, world as world13 } from "@minecraft/server";
world13.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  const block = event.block;
  const dimension = block.dimension;
  const blockFace = event.blockFace;
  const player = event.player;
  const directionMethods = {
    [Direction.Down]: () => block.below(),
    [Direction.Up]: () => block.above(),
    [Direction.North]: () => block.north(),
    [Direction.South]: () => block.south(),
    [Direction.East]: () => block.east(),
    [Direction.West]: () => block.west()
  };
  const targetBlock = directionMethods[blockFace]?.() ?? block;
  const blockVolume = new BlockVolume(targetBlock.location, targetBlock.location);
  const allowedAreas = getAllAreaData();
  let allowed = false;
  for (const area of allowedAreas) {
    const [start, end] = area.area;
    const allowedVolume = new BlockVolume(
      { x: start.x, y: dimension.heightRange.min, z: start.z },
      { x: end.x, y: dimension.heightRange.max, z: end.z }
    );
    const intersects = blockVolume.intersects(allowedVolume);
    if (intersects === BlockVolumeIntersection.Intersects) {
      allowed = true;
      break;
    }
  }
  if (!allowed) {
    event.cancel = true;
    player.sendMessage("\xA77[\xA7c!\xA77] You can't build further, unlock new islands to expand the area!");
    system11.run(() => player.playSound("block.end_portal_frame.fill", { location: player.location, volume: 1, pitch: 0.6 }));
  }
});

// data/scripts/islands/preventBreaking.ts
import { system as system12, world as world14 } from "@minecraft/server";
var restrictedPaths = [
  "specialislands/specialisland_1"
];
var structureBlocks = [
  "minecraft:polished_deepslate_stairs",
  "minecraft:polished_deepslate",
  "minecraft:dirt",
  "minecraft:grass_block",
  "minecraft:deepslate_tiles",
  "minecraft:cracked_deepslate_bricks",
  "minecraft:deepslate_bricks",
  "minecraft:blackstone_wall",
  "minecraft:deepslate",
  "minecraft:polished_deepslate_slab",
  "minecraft:polished_tuff",
  "minecraft:chain",
  "minecraft:skeleton_skull",
  "minecraft:deepslate_brick_stairs",
  "minecraft:mossy_stone_bricks",
  "minecraft:lantern",
  "minecraft:deepslate_brick_wall",
  "minecraft:black_candle",
  "minecraft:iron_bars",
  "minecraft:candle",
  "minecraft:campfire",
  "minecraft:pale_oak_slab",
  "minecraft:torch",
  "minecraft:normal_stone_stairs",
  "minecraft:stone",
  "minecraft:polished_deepslate_double_slab",
  "minecraft:pale_oak_trapdoor",
  "minecraft:chest",
  "minecraft:reinforced_deepslate",
  "minecraft:deepslate_brick_slab",
  "minecraft:pale_oak_wood"
];
world14.beforeEvents.playerBreakBlock.subscribe((event) => {
  const block = event.block;
  const player = event.player;
  const cornerLoc = getCornerFromLocation(block.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData) return;
  const cornerEntity = block.dimension.getEntities({ type: "isb:corner", location: cornerLoc, maxDistance: 2 })[0];
  if (!cornerEntity) return;
  const isRestricted = restrictedPaths.includes(areaData.path);
  const isProtectedBlock = structureBlocks.includes(block.typeId);
  if (isRestricted && !areaData.completed && isProtectedBlock) {
    event.cancel = true;
    player.sendMessage("\xA77[\xA7c!\xA77] You can't break this protected block.");
    system12.run(() => player.playSound("block.end_portal_frame.fill", { location: player.location, volume: 1, pitch: 0.6 }));
  }
});
world14.beforeEvents.explosion.subscribe((event) => {
  const impactedBlocks = event.getImpactedBlocks();
  if (!impactedBlocks || impactedBlocks.length === 0) return;
  const firstBlock = impactedBlocks[0];
  const cornerLoc = getCornerFromLocation(firstBlock.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData) return;
  const cornerEntity = event.dimension.getEntities({ type: "isb:corner", location: cornerLoc, maxDistance: 2 })[0];
  if (!cornerEntity) return;
  const isRestricted = restrictedPaths.includes(areaData.path);
  if (!isRestricted || areaData.completed) return;
  const blocksToProtect = impactedBlocks.filter(
    (block) => structureBlocks.includes(block.typeId)
  );
  if (blocksToProtect.length > 0) {
    const allowedToBreak = impactedBlocks.filter(
      (block) => !blocksToProtect.includes(block)
    );
    event.setImpactedBlocks(allowedToBreak);
  }
});

// data/scripts/quests/altar/setMission.ts
import { BlockVolume as BlockVolume2, system as system13, TimeOfDay, world as world15 } from "@minecraft/server";
var altars = [
  "isb:altar_green_entity",
  "isb:altar_purple_entity",
  "isb:altar_red_entity",
  "isb:altar_yellow_entity"
];
var MINI_TOTEM_TYPES = ["isb:mini_totem_a", "isb:mini_totem_b"];
var MOB_SPAWNER_ID = "minecraft:mob_spawner";
world15.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const entity = event.target;
  const player = event.player;
  const dimension = player.dimension;
  if (!altars.includes(entity.typeId)) return;
  const cornerLoc = getCornerFromLocation(entity.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  const rewarded = entity.getDynamicProperty("isb:rewarded");
  if (!areaData) return;
  if (areaData.type === "main") return;
  if (areaData?.completed && rewarded) {
    player.sendMessage("\xA77[\xA7a!\xA77] This mission is completed.");
    player.playSound("block.end_portal_frame.fill", { location: player.location, volume: 1, pitch: 0.6 });
    return;
  }
  if (!areaData.started) {
    const cornerEntity = entity.dimension.getEntities({ type: "isb:corner", location: cornerLoc, maxDistance: 2 })[0];
    if (!cornerEntity) return;
    entity.setDynamicProperty("isb:corner_id", cornerEntity.id);
    cornerEntity.setDynamicProperty("isb:altar_id", entity.id);
    if (entity.typeId === "isb:altar_green_entity") {
      const [start, end] = areaData.area;
      const volume = new BlockVolume2(
        { x: start.x, y: dimension.heightRange.min, z: start.z },
        { x: end.x, y: dimension.heightRange.max, z: end.z }
      );
      const blockVolume = dimension.getBlocks(volume, { includeTypes: MINI_TOTEM_TYPES }, true);
      const blockIterator = blockVolume.getBlockLocationIterator();
      const totemCount = Array.from(blockIterator).length;
      if (totemCount === 0) return;
      entity.setDynamicProperty("isb:max_mini_totems", totemCount);
      player.sendMessage(`\xA77[\xA7e!\xA77] New objective: \xA7eFind ${totemCount} mini totems around the island.`);
      player.runCommand(`titleraw @s times 15 30 15`);
      player.runCommand(`title @s title title_dungeon_begins`);
      player.runCommand(`titleraw @s times 0 0 0`);
    }
    if (entity.typeId === "isb:altar_red_entity") {
      const [start, end] = areaData.area;
      const volume = new BlockVolume2(
        { x: start.x, y: dimension.heightRange.min, z: start.z },
        { x: end.x, y: dimension.heightRange.max, z: end.z }
      );
      const blockVolume = dimension.getBlocks(volume, { includeTypes: [MOB_SPAWNER_ID] }, true);
      const blockIterator = blockVolume.getBlockLocationIterator();
      const spawnerCount = Array.from(blockIterator).length;
      if (spawnerCount === 0) return;
      entity.setDynamicProperty("isb:max_spawners", spawnerCount);
      player.sendMessage(`\xA77[\xA7e!\xA77] New objective: \xA7eDestroy ${spawnerCount} mob spawners around the island.`);
      let message = `hud:dungeon:\xA7f\xA7lYou destroyed 0/${spawnerCount} mob spawners.`;
      player.runCommand(`titleraw @s times 15 30 15`);
      player.runCommand(`title @s title title_dungeon_begins`);
      player.runCommand(`titleraw @s times 0 0 0`);
      TimeTick.setTimeTick(world15.getTimeOfDay());
      world15.setTimeOfDay(TimeOfDay.Midnight);
      system13.runTimeout(() => {
        player.runCommand(`titleraw @s times 0 0 0`);
        player.runCommand(`title @s title ""`);
        player.runCommand(`titleraw @s title {"rawtext":[{"text":"${message}"}]}`);
      }, 60);
    }
    if (entity.typeId === "isb:altar_yellow_entity") {
      const questData = generateRandomQuest();
      const quest = JSON.stringify(questData);
      const items = questData.quest.items;
      const itemList = Object.entries(items).map(([item, amount]) => `${formatItemName(item)} [${amount}]`).join(", ");
      const dummy = entity.dimension.spawnEntity("isb:yellow_dummy", entity.location);
      entity.setDynamicProperty("isb:dummy_id", dummy.id);
      dummy.setDynamicProperty("isb:altar_id", entity.id);
      dummy.setDynamicProperty("isb:quest", quest);
      player.sendMessage(`\xA77[\xA7e!\xA77] New objective: \xA7eCollect and deliver the following items: ${itemList}.`);
      player.runCommand(`titleraw @s times 15 30 15`);
      player.runCommand(`title @s title title_dungeon_begins`);
      player.runCommand(`titleraw @s times 0 0 0`);
    }
    updateAreaProperty(areaData.position, { started: true });
  }
});
system13.afterEvents.scriptEventReceive.subscribe((event) => {
  const { id, sourceEntity } = event;
  if (id === "isb:altar" && sourceEntity) {
    const loc = sourceEntity.location;
    const cornerLoc = getCornerFromLocation(loc);
    const areaData = getAreaDataFromVec3(cornerLoc);
    const cornerEntity = sourceEntity.dimension.getEntities({ type: "isb:corner", location: cornerLoc, maxDistance: 2 })[0];
    if (!areaData || !cornerEntity) return;
    updateAreaProperty(areaData.position, { started: false, completed: false });
    cornerEntity.setDynamicProperty("isb:altar_id", void 0);
  }
});

// data/scripts/quests/altar/missionProgress.ts
import { BlockVolume as BlockVolume3, system as system14, TimeOfDay as TimeOfDay2, world as world16 } from "@minecraft/server";
world16.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const entity = event.target;
  const player = event.player;
  if (!altars.includes(entity.typeId) && entity.typeId !== "isb:yellow_dummy") return;
  const cornerLoc = getCornerFromLocation(entity.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData) return;
  const rewarded = entity.getDynamicProperty("isb:rewarded");
  if (!areaData.completed && areaData.started && !rewarded) {
    if (entity.typeId === "isb:altar_green_entity") {
      const miniTotems = entity.getDynamicProperty("isb:mini_totems") ?? 0;
      const maxMiniTotems = entity.getDynamicProperty("isb:max_mini_totems");
      player.sendMessage(`\xA77[\xA7b!\xA77] Mini totems found: \xA7b${miniTotems}\xA77/\xA7b${maxMiniTotems}\xA77.`);
    }
    if (entity.typeId === "isb:altar_red_entity") {
      const spawnersDestroyed = entity.getDynamicProperty("isb:spawners_destroyed") ?? 0;
      const maxSpawners = entity.getDynamicProperty("isb:max_spawners");
      player.sendMessage(`\xA77[\xA7b!\xA77] Mob spawners destroyed: \xA7b${spawnersDestroyed}\xA77/\xA7b${maxSpawners}\xA77.`);
      if (TimeTick.getTimeTick() === 0) {
        TimeTick.setTimeTick(world16.getTimeOfDay());
      }
      world16.setTimeOfDay(TimeOfDay2.Midnight);
      let message = `hud:dungeon:\xA7f\xA7lYou destroyed ${spawnersDestroyed}/${maxSpawners} mob spawners.`;
      player.runCommand(`titleraw @s times 0 0 0`);
      player.runCommand(`title @s title ""`);
      player.runCommand(`titleraw @s title {"rawtext":[{"text":"${message}"}]}`);
    }
    if (entity.typeId === "isb:altar_purple_entity") {
      player.sendMessage(`\xA77[\xA7b!\xA77] Defeat the boss to complete this island.`);
    }
    if (entity.typeId === "isb:yellow_dummy") {
      const questData = entity.getDynamicProperty("isb:quest");
      const quest = JSON.parse(questData);
      const items = quest.quest.items;
      const itemList = Object.entries(items).map(([item, amount]) => `${formatItemName(item)} [${amount}]`).join(", ");
      player.sendMessage(`\xA77[\xA7e!\xA77] Collect and deliver the following items: \xA7e${itemList}\xA77.`);
    }
  }
});
var MINI_TOTEM_TYPES2 = ["isb:mini_totem_a", "isb:mini_totem_b"];
var PARTICLE_ID = "isb:skysoul_give_green";
var totemPhase = /* @__PURE__ */ new Map();
var TICKS_PER_FRAME = 4;
var RING_POINTS = 32;
var SLICE_WIDTH = 1;
var POINT_STRIDE = 2;
var PHASE_STEP = 3;
system14.runInterval(() => {
  const dimensions = ["overworld", "nether", "the_end"];
  const seenThisFrame = /* @__PURE__ */ new Set();
  for (const dimId of dimensions) {
    let dimension;
    try {
      dimension = world16.getDimension(dimId);
    } catch {
      continue;
    }
    const greenAltars = dimension.getEntities({ type: "isb:altar_green_entity" });
    for (const altar of greenAltars) {
      const cornerLoc = getCornerFromLocation(altar.location);
      const areaData = getAreaDataFromVec3(cornerLoc);
      if (!areaData) continue;
      const rewarded = altar.getDynamicProperty("isb:rewarded");
      const maxMiniTotems = altar.getDynamicProperty("isb:max_mini_totems");
      if (!areaData.started || areaData.completed || rewarded || !maxMiniTotems || maxMiniTotems === 0) continue;
      const [start, end] = areaData.area;
      const volume = new BlockVolume3(
        { x: start.x, y: dimension.heightRange.min, z: start.z },
        { x: end.x, y: dimension.heightRange.max, z: end.z }
      );
      const blockVolume = dimension.getBlocks(volume, { includeTypes: MINI_TOTEM_TYPES2 }, true);
      const it = blockVolume.getBlockLocationIterator();
      for (const loc of it) {
        const block = dimension.getBlock(loc);
        if (!block) continue;
        const isActivated = block.permutation.getState("isb:actived") ?? false;
        if (isActivated) continue;
        const center = { x: loc.x + 0.5, y: loc.y + 0.15, z: loc.z + 0.5 };
        const hasNearbyPlayer = world16.getPlayers().some((p) => {
          if (p.dimension !== dimension) return false;
          const dx = p.location.x - center.x;
          const dy = p.location.y - center.y;
          const dz = p.location.z - center.z;
          return dx * dx + dy * dy + dz * dz <= 48 * 48;
        });
        if (!hasNearbyPlayer) continue;
        const key = `${dimId}:${loc.x},${loc.y},${loc.z}`;
        const prev = totemPhase.get(key) ?? 0;
        const phase = (prev + PHASE_STEP) % RING_POINTS;
        totemPhase.set(key, phase);
        seenThisFrame.add(key);
        const radius = 0.88;
        for (let k = Math.max(0, phase - SLICE_WIDTH); k <= phase; k += POINT_STRIDE) {
          const angle = k / RING_POINTS * Math.PI * 2;
          const px = center.x + Math.cos(angle) * radius;
          const pz = center.z + Math.sin(angle) * radius;
          const py = center.y + 0.05 + Math.sin(angle * 2) * 0.01;
          try {
            dimension.spawnParticle(PARTICLE_ID, { x: px, y: py, z: pz });
          } catch {
            try {
              dimension.runCommandAsync(`particle ${PARTICLE_ID} ${px} ${py} ${pz}`);
            } catch {
            }
          }
        }
      }
    }
  }
  for (const key of totemPhase.keys()) {
    if (!seenThisFrame.has(key)) totemPhase.delete(key);
  }
}, TICKS_PER_FRAME);

// data/scripts/quests/altar/completeMission.ts
import { world as world17 } from "@minecraft/server";
world17.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const entity = event.target;
  const player = event.player;
  if (!altars.includes(entity.typeId)) return;
  const cornerLoc = getCornerFromLocation(entity.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData) return;
  const rewarded = entity.getDynamicProperty("isb:rewarded");
  if (areaData?.completed && !rewarded) {
    entity.setProperty("isb:quest_completed", true);
    entity.setProperty("isb:animation", "give");
    entity.setDynamicProperty("isb:rewarded", true);
    player.runCommand(`titleraw @s times 15 30 15`);
    player.runCommand(`title @s title ""`);
    player.runCommand(`title @s title title_new_island_spawning`);
    player.runCommand(`titleraw @s times 0 0 0`);
    player.playSound("random.levelup", { location: player.location, volume: 1, pitch: 1 });
  }
});

// data/scripts/quests/altar/reward.ts
import { ItemStack as ItemStack5, system as system15, world as world18 } from "@minecraft/server";
var REWARD_EVENT_ID = "isb:reward";
var SPAWN_EVENT_ID = "isb:spawn_random";
var NOTIFICATION_RADIUS = 30;
var SPAWN_OFFSET = 1.2;
var PURPLE_ALTAR_TYPE = "isb:altar_purple_entity";
var MESSAGES = {
  unlucky: `{"rawtext":[{"text":"\xA77[\xA7c!\xA77] It seems you're unlucky. No Skysoul here."}]}`,
  success: '{"rawtext":[{"text":"\xA77[\xA7a!\xA77] The skies reward your efforts with a Skysoul."}]}'
};
function extractColorFromAltarType(typeId) {
  const parts = typeId.split(":");
  if (parts.length < 2) return null;
  const colorParts = parts[1]?.split("_");
  return colorParts?.[1] || null;
}
function calculateSpawnLocation(entity) {
  const viewDir = entity.getViewDirection();
  return {
    x: entity.location.x + viewDir.x * SPAWN_OFFSET,
    y: entity.location.y + viewDir.y * SPAWN_OFFSET,
    z: entity.location.z + viewDir.z * SPAWN_OFFSET
  };
}
function notifyPlayers(entity, message) {
  entity.runCommand(`tellraw @a[r=${NOTIFICATION_RADIUS}] ${message}`);
}
function spawnRewardItem(entity, color) {
  const soul = new ItemStack5(`isb:sky_soul_${color}`, 1);
  const spawnLocation = calculateSpawnLocation(entity);
  entity.dimension.spawnItem(soul, spawnLocation);
}
function processAltarReward(entity) {
  if (entity.typeId === PURPLE_ALTAR_TYPE) {
    if (entity.typeId !== "isb:altar_purple_entity") notifyPlayers(entity, MESSAGES.success);
    return;
  }
  const color = extractColorFromAltarType(entity.typeId);
  if (!color) return;
  if (!entity.isValid) return;
  spawnRewardItem(entity, color);
  if (entity.typeId !== "isb:altar_purple_entity") notifyPlayers(entity, MESSAGES.success);
}
function handleCornerEvent(entity) {
  const cornerID = entity.getDynamicProperty("isb:corner_id");
  let corner;
  if (cornerID) {
    corner = world18.getEntity(cornerID);
  }
  if (!corner && entity.isValid) {
    const cornerLoc = getCornerFromLocation(entity.location);
    const nearbyCorners = entity.dimension.getEntities({
      type: "isb:corner",
      location: cornerLoc,
      maxDistance: 2
    });
    corner = nearbyCorners[0];
    if (!corner) return false;
  }
  corner.runCommand(`scriptevent ${SPAWN_EVENT_ID}`);
  return true;
}
function handleRewardEvent(event) {
  const { id, sourceEntity: entity } = event;
  if (id !== REWARD_EVENT_ID || !entity || !altars.includes(entity.typeId)) return;
  if (!handleCornerEvent(entity)) {
    return;
  }
  try {
    processAltarReward(entity);
  } catch (error) {
    console.error("Error processing altar reward:", error);
  }
}
system15.afterEvents.scriptEventReceive.subscribe(handleRewardEvent);

// data/scripts/quests/altar/destroy.ts
import { world as world19, system as system16, ItemStack as ItemStack6 } from "@minecraft/server";
var confirmationHits = /* @__PURE__ */ new Map();
world19.afterEvents.entityHitEntity.subscribe((event) => {
  const attacker = event.damagingEntity;
  const entity = event.hitEntity;
  if (attacker.typeId !== "minecraft:player") return;
  if (!altars.includes(entity.typeId) && entity.typeId !== "isb:yellow_dummy") return;
  const cornerLoc = getCornerFromLocation(entity.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  const rewarded = entity.getDynamicProperty("isb:rewarded");
  if (!areaData || !areaData.completed || !rewarded) return;
  const isSpecialLocation = entity.location.x === 8 && entity.location.y === 122 && entity.location.z === 28;
  if (!areaData && !isSpecialLocation) return;
  const entityId = entity.id;
  const currentTime = Date.now();
  if (confirmationHits.has(entityId)) {
    const hitData = confirmationHits.get(entityId);
    if (currentTime - hitData.timestamp <= 2e3) {
      destroyStatue(entity, attacker);
      confirmationHits.delete(entityId);
      return;
    }
  }
  showConfirmationMessage(attacker);
  confirmationHits.set(entityId, { timestamp: currentTime });
  system16.runTimeout(() => {
    confirmationHits.delete(entityId);
  }, 40);
});
function showConfirmationMessage(player) {
  if (!player || !player.onScreenDisplay) return;
  player.onScreenDisplay.setActionBar("\xA7cAre you sure you want to destroy the altar? Hit again to confirm.");
}
function destroyStatue(entity, player) {
  const location = entity.location;
  const dimension = entity.dimension;
  const ironAmount = Math.floor(Math.random() * 2) + 2;
  const goldAmount = Math.floor(Math.random() * 2) + 2;
  dimension.spawnItem(new ItemStack6("minecraft:iron_ingot", ironAmount), location);
  dimension.spawnItem(new ItemStack6("minecraft:gold_ingot", goldAmount), location);
  entity.remove();
  if (player && player.onScreenDisplay) {
    player.onScreenDisplay.setActionBar("\xA7aAltar destroyed.");
  }
}

// data/scripts/quests/type/redQuest.ts
import { system as system17, world as world20 } from "@minecraft/server";
var MOB_SPAWNER_ID2 = "minecraft:mob_spawner";
world20.beforeEvents.playerBreakBlock.subscribe((event) => {
  const block = event.block;
  const player = event.player;
  if (block.typeId !== MOB_SPAWNER_ID2) return;
  const cornerLoc = getCornerFromLocation(block.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData) return;
  if (!areaData.started) {
    player.sendMessage("\xA77[\xA7e!\xA77] Find the \xA7cRed Altar\xA77 to start the mission.");
    system17.run(() => player.playSound("block.end_portal_frame.fill", { location: player.location, volume: 1, pitch: 0.6 }));
    event.cancel = true;
  }
});
world20.afterEvents.playerBreakBlock.subscribe((event) => {
  const block = event.block;
  const blockID = event.brokenBlockPermutation.type.id;
  const player = event.player;
  if (blockID !== MOB_SPAWNER_ID2) return;
  const cornerLoc = getCornerFromLocation(block.location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData || areaData.completed || !areaData.started) return;
  const cornerEntity = block.dimension.getEntities({ type: "isb:corner", location: cornerLoc, maxDistance: 2 })[0];
  if (!cornerEntity) return;
  const altarID = cornerEntity.getDynamicProperty("isb:altar_id");
  if (!altarID) return;
  const altar = world20.getEntity(altarID);
  if (!altar) return;
  const maxSpawners = altar.getDynamicProperty("isb:max_spawners");
  if (!maxSpawners || maxSpawners === 0) return;
  const spawnersDestroyed = altar.getDynamicProperty("isb:spawners_destroyed") ?? 0;
  const newSpawners = spawnersDestroyed + 1;
  altar.setDynamicProperty("isb:spawners_destroyed", newSpawners);
  let message = `hud:dungeon:\xA7f\xA7lYou destroyed ${newSpawners}/${maxSpawners} mob spawners.`;
  player.runCommand(`titleraw @s times 0 0 0`);
  player.runCommand(`title @s title ""`);
  player.runCommand(`titleraw @s title {"rawtext":[{"text":"${message}"}]}`);
  if (newSpawners >= maxSpawners) {
    updateAreaProperty(areaData.position, { completed: true });
    missionCompleted(player);
  }
});

// data/scripts/quests/type/yellowQuest.ts
import { system as system18, world as world21 } from "@minecraft/server";
var CHECK_INTERVAL = 20;
system18.runInterval(() => {
  const dimension = world21.getDimension("overworld");
  const yellowDummys = dimension.getEntities({ type: "isb:yellow_dummy" });
  for (const dummy of yellowDummys) {
    const cornerLoc = getCornerFromLocation(dummy.location);
    const areaData = getAreaDataFromVec3(cornerLoc);
    if (!areaData) return;
    if (!areaData.completed && areaData.started) {
      const inv = dummy.getComponent("inventory")?.container;
      if (!inv) continue;
      const questData = dummy.getDynamicProperty("isb:quest");
      const quest = JSON.parse(questData);
      handleYellowQuestDelivery(dummy, quest.quest);
    }
  }
}, CHECK_INTERVAL);

// data/scripts/quests/type/specialQuest.ts
import { system as system19, BlockVolume as BlockVolume5, world as world22 } from "@minecraft/server";
world22.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
  const entity = event.entity;
  if (event.eventId === "isb:death" && entity?.typeId === "isb:titanium_revenant") {
    const loc = entity.location;
    const dim = entity.dimension;
    const corner = entity.getDynamicProperty("isb:corner_loc");
    const areaData = getAreaDataFromVec3(corner);
    try {
      if (!areaData || areaData.completed && areaData.type === "special") return;
      updateAreaProperty(areaData.position, { completed: true });
      system19.runTimeout(() => {
        const nearbyPlayers = entity.dimension.getPlayers({ location: entity.location, maxDistance: 40 });
        for (const p of nearbyPlayers) {
          missionCompleted(p);
        }
        openDoor(dim, loc, "minecraft:reinforced_deepslate", 4, 3);
      }, 30);
    } catch {
    }
  } else if (event.eventId === "isb:death_effect" && entity?.typeId === "isb:dragon_generic") {
    const corner = entity.getDynamicProperty("isb:corner_loc");
    const areaData = getAreaDataFromVec3(corner);
    try {
      if (!areaData || areaData.completed && areaData.type === "special") return;
      updateAreaProperty(areaData.position, { completed: true });
      const nearbyPlayers = entity.dimension.getPlayers({ location: entity.location, maxDistance: 40 });
      for (const p of nearbyPlayers) {
        missionCompleted(p);
      }
    } catch {
    }
  }
});
function openDoor(dimension, location, blockID, height, width) {
  const cornerLoc = getCornerFromLocation(location);
  const areaData = getAreaDataFromVec3(cornerLoc);
  if (!areaData) return;
  const [start, end] = areaData.area;
  const volume = new BlockVolume5(
    { x: start.x, y: dimension.heightRange.min, z: start.z },
    { x: end.x, y: dimension.heightRange.max, z: end.z }
  );
  const blockVolume = dimension.getBlocks(volume, { includeTypes: [blockID] }, true);
  const blockIterator = blockVolume.getBlockLocationIterator();
  const reinforcedSet = /* @__PURE__ */ new Set();
  for (const loc of blockIterator) {
    reinforcedSet.add(`${loc.x},${loc.y},${loc.z}`);
  }
  function isReinforced(x, y, z) {
    return reinforcedSet.has(`${x},${y},${z}`);
  }
  const alreadyChecked = /* @__PURE__ */ new Set();
  for (const locStr of reinforcedSet) {
    const [xStr, yStr, zStr] = locStr.split(",");
    const x = parseInt(xStr);
    const y = parseInt(yStr);
    const z = parseInt(zStr);
    for (const axis of ["x", "z"]) {
      const dx = axis === "x" ? 1 : 0;
      const dz = axis === "z" ? 1 : 0;
      const left = { x: x - dx, y, z: z - dz };
      const center = { x, y, z };
      const right = { x: x + dx, y, z: z + dz };
      if (isReinforced(left.x, left.y, left.z) && isReinforced(center.x, center.y, center.z) && isReinforced(right.x, right.y, right.z)) {
        let match = true;
        for (let dy = 1; dy < height; dy++) {
          if (!isReinforced(left.x, left.y - dy, left.z) || !isReinforced(center.x, center.y - dy, center.z) || !isReinforced(right.x, right.y - dy, right.z)) {
            match = false;
            break;
          }
        }
        if (match) {
          const baseX = left.x;
          const baseY = y - (height - 1);
          const baseZ = left.z;
          const key = `${baseX},${baseY},${baseZ},${axis}`;
          if (alreadyChecked.has(key)) continue;
          alreadyChecked.add(key);
          for (let dy = 0; dy < height; dy++) {
            system19.runTimeout(() => {
              for (let i = 0; i < width; i++) {
                const pos = {
                  x: baseX + i * dx,
                  y: baseY + dy,
                  z: baseZ + i * dz
                };
                const block = dimension.getBlock(pos);
                if (block?.typeId === blockID) {
                  block.setType("minecraft:air");
                }
              }
            }, dy * 6);
          }
          return;
        }
      }
    }
  }
}

// data/scripts/tutorial/tutorialTotem.ts
import { world as world23 } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
function ensureIntroObjective() {
  const existing = world23.scoreboard.getObjective("introduction");
  if (existing) return existing;
  return world23.scoreboard.addObjective("introduction");
}
function restartIntroduction(player) {
  const obj = ensureIntroObjective();
  obj?.setScore(player, 1);
  if (!player.hasTag("introduction")) player.addTag("introduction");
  try {
    player.onScreenDisplay.setTitle("Intro restarted", { subtitle: "Enjoy the cinematic again" });
  } catch {
  }
}
world23.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const entity = event.target;
  const player = event.player;
  if (!entity || !entity.isValid) return;
  if (!entity.hasTag || !entity.hasTag("tutorial_totem")) return;
  try {
    const form = new ActionFormData().title("Tutorial Totem").body("Do you want to restart the introductory cinematic?").button("Restart").button("Close");
    form.show(player).then((res) => {
      if (res.canceled) return;
      if (res.selection === 0) restartIntroduction(player);
    });
  } catch {
    restartIntroduction(player);
  }
});
