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

const teamName = "Ka Studios";
const addonName = "Dynamic Tree Generation Add-On";
const guideBookStructure = "ka_bt:ka_bt_book";
const givenBookString = `${teamName}_${addonName}:givenBook`;

const FOOD_ITEMS = new Set([
  "ka_bt:spruce_syrup",
  "ka_bt:spruce_cone_salad",
  "ka_bt:acorn_cake",
  "ka_bt:apple_cake",
  "ka_bt:chopped_fruit",
  "ka_bt:birch_catkin_cookie",
  "ka_bt:apple_juice",
  "ka_bt:iced_fir_cone",
  "ka_bt:spruce_sweet_cone_jam",
  "ka_bt:forest_cookie"
]);

const GOOD_EFFECTS = [
  { id: "speed", seconds: 25, amplifier: 1 },
  { id: "regeneration", seconds: 12, amplifier: 1 },
  { id: "strength", seconds: 20, amplifier: 1 },
  { id: "resistance", seconds: 20, amplifier: 0 },
  { id: "jump_boost", seconds: 25, amplifier: 1 },
  { id: "absorption", seconds: 30, amplifier: 1 }
];

function randomIndex(max) {
  return Math.floor(Math.random() * max);
}

world.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;
  try {
    if (player.getDynamicProperty(givenBookString)) return;

    player.runCommand(`structure load ${guideBookStructure} ~~~`);
    player.runCommand(
      `tellraw @a {"rawtext":[{"text":"§eDynamic Tree Generation Add-On Guide Book has been provided"}]}`
    );

    player.setDynamicProperty(givenBookString, true);
  } catch (e) {
  
  }
});

world.afterEvents.itemCompleteUse.subscribe((ev) => {
  const item = ev.itemStack;
  const player = ev.source;

  if (!(player instanceof Player)) return;
  if (!item) return;

  const itemId = item.typeId;
  if (!FOOD_ITEMS.has(itemId)) return;

  const effect = GOOD_EFFECTS[randomIndex(GOOD_EFFECTS.length)];

  player.runCommand(
    `effect @s ${effect.id} ${effect.seconds} ${effect.amplifier} true`
  );
});
