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

import { ActionFormData, ModalFormData } from "@minecraft/server-ui";

import * as minecraft from "@minecraft/server";
import * as ui from "@minecraft/server-ui";

Player.prototype.special_timer = 0;
Player.prototype.cooldown_timer = 0;
Player.prototype.despawn_timer = 0;

// Variable
const AllBackpacksBallons = [
  "bf_bp:ballons_backpack_armor",
  "bf_bp:black_ballons_backpack_armor",
  "bf_bp:purple_ballons_backpack_armor",
  "bf_bp:yellow_ballons_backpack_armor",
];

const NewsBackpacksCanFly = [
  "bf_bp:butterfly_backpack_armor",
  "bf_bp:blue_butterfly_backpack_armor",
  "bf_bp:magenta_butterfly_backpack_armor",
  "bf_bp:purple_butterfly_backpack_armor",
  "bf_bp:yellow_butterfly_backpack_armor",

  "bf_bp:demon_backpack_armor",
  "bf_bp:black_demon_backpack_armor",
  "bf_bp:enddragon_demon_backpack_armor",
  "bf_bp:purple_demon_backpack_armor",
  "bf_bp:red_demon_backpack_armor",

  "bf_bp:wings_backpack_armor",
  "bf_bp:black_wings_backpack_armor",
  "bf_bp:gold_wings_backpack_armor",
  "bf_bp:pink_wings_backpack_armor",
  "bf_bp:rainbow_wings_backpack_armor",
];

const NewsBackpacksLightSource = [
  "bf_bp:lantern_backpack_armor",
  "bf_bp:blue_lantern_backpack_armor",
  "bf_bp:green_lantern_backpack_armor",
  "bf_bp:purple_lantern_backpack_armor",
  "bf_bp:red_lantern_backpack_armor",

  "bf_bp:medieval_backpack_armor",
  "bf_bp:cyan_medieval_backpack_armor",
  "bf_bp:pink_medieval_backpack_armor",
  "bf_bp:red_medieval_backpack_armor",
  "bf_bp:yellow_medieval_backpack_armor",
];

const AxolotlWithSpecials = [
  "bf_bp:axolotl_backpack_armor",
  "bf_bp:red_axolotl_backpack_armor",
  "bf_bp:yellow_axolotl_backpack_armor",
  "bf_bp:green_axolotl_backpack_armor",
  "bf_bp:blue_axolotl_backpack_armor",
  "bf_bp:pink_axolotl_backpack_armor",
  "bf_bp:purple_axolotl_backpack_armor",
  "bf_bp:white_axolotl_backpack_armor",
  "bf_bp:black_axolotl_backpack_armor",
  "bf_bp:brown_axolotl_backpack_armor",
];
const CreeperWithSpecials = [
  "bf_bp:creeper_backpack_armor",
  "bf_bp:red_creeper_backpack_armor",
  "bf_bp:yellow_creeper_backpack_armor",
  "bf_bp:green_creeper_backpack_armor",
  "bf_bp:blue_creeper_backpack_armor",
  "bf_bp:pink_creeper_backpack_armor",
  "bf_bp:purple_creeper_backpack_armor",
  "bf_bp:white_creeper_backpack_armor",
  "bf_bp:black_creeper_backpack_armor",
  "bf_bp:brown_creeper_backpack_armor",
];
const DragonWingsWithSpecials = [
  "bf_bp:dragon_wings_backpack_armor",
  "bf_bp:red_dragon_wings_backpack_armor",
  "bf_bp:yellow_dragon_wings_backpack_armor",
  "bf_bp:green_dragon_wings_backpack_armor",
  "bf_bp:blue_dragon_wings_backpack_armor",
  "bf_bp:pink_dragon_wings_backpack_armor",
  "bf_bp:purple_dragon_wings_backpack_armor",
  "bf_bp:white_dragon_wings_backpack_armor",
  "bf_bp:black_dragon_wings_backpack_armor",
  "bf_bp:brown_dragon_wings_backpack_armor",
];
const EndermanWithSpecials = ["bf_bp:enderman_backpack_armor"];
const WardenWithSpecials = [
  "bf_bp:warden_backpack_armor",
  "bf_bp:red_warden_backpack_armor",
  "bf_bp:yellow_warden_backpack_armor",
  "bf_bp:green_warden_backpack_armor",
  "bf_bp:blue_warden_backpack_armor",
  "bf_bp:pink_warden_backpack_armor",
  "bf_bp:purple_warden_backpack_armor",
  "bf_bp:white_warden_backpack_armor",
  "bf_bp:black_warden_backpack_armor",
  "bf_bp:brown_warden_backpack_armor",
];
const WolfWithSpecials = [
  "bf_bp:wolf_backpack_armor",
  "bf_bp:red_wolf_backpack_armor",
  "bf_bp:yellow_wolf_backpack_armor",
  "bf_bp:green_wolf_backpack_armor",
  "bf_bp:blue_wolf_backpack_armor",
  "bf_bp:pink_wolf_backpack_armor",
  "bf_bp:purple_wolf_backpack_armor",
  "bf_bp:white_wolf_backpack_armor",
  "bf_bp:black_wolf_backpack_armor",
  "bf_bp:brown_wolf_backpack_armor",
];
const AllBackpacksArmorWithSpecials = [
  "bf_bp:axolotl_backpack_armor",
  "bf_bp:red_axolotl_backpack_armor",
  "bf_bp:yellow_axolotl_backpack_armor",
  "bf_bp:green_axolotl_backpack_armor",
  "bf_bp:blue_axolotl_backpack_armor",
  "bf_bp:pink_axolotl_backpack_armor",
  "bf_bp:purple_axolotl_backpack_armor",
  "bf_bp:white_axolotl_backpack_armor",
  "bf_bp:black_axolotl_backpack_armor",
  "bf_bp:brown_axolotl_backpack_armor",

  "bf_bp:creeper_backpack_armor",
  "bf_bp:red_creeper_backpack_armor",
  "bf_bp:yellow_creeper_backpack_armor",
  "bf_bp:green_creeper_backpack_armor",
  "bf_bp:blue_creeper_backpack_armor",
  "bf_bp:pink_creeper_backpack_armor",
  "bf_bp:purple_creeper_backpack_armor",
  "bf_bp:white_creeper_backpack_armor",
  "bf_bp:black_creeper_backpack_armor",
  "bf_bp:brown_creeper_backpack_armor",

  "bf_bp:dragon_wings_backpack_armor",
  "bf_bp:red_dragon_wings_backpack_armor",
  "bf_bp:yellow_dragon_wings_backpack_armor",
  "bf_bp:green_dragon_wings_backpack_armor",
  "bf_bp:blue_dragon_wings_backpack_armor",
  "bf_bp:pink_dragon_wings_backpack_armor",
  "bf_bp:purple_dragon_wings_backpack_armor",
  "bf_bp:white_dragon_wings_backpack_armor",
  "bf_bp:black_dragon_wings_backpack_armor",
  "bf_bp:brown_dragon_wings_backpack_armor",

  "bf_bp:enderman_backpack_armor",

  "bf_bp:warden_backpack_armor",
  "bf_bp:red_warden_backpack_armor",
  "bf_bp:yellow_warden_backpack_armor",
  "bf_bp:green_warden_backpack_armor",
  "bf_bp:blue_warden_backpack_armor",
  "bf_bp:pink_warden_backpack_armor",
  "bf_bp:purple_warden_backpack_armor",
  "bf_bp:white_warden_backpack_armor",
  "bf_bp:black_warden_backpack_armor",
  "bf_bp:brown_warden_backpack_armor",

  "bf_bp:wolf_backpack_armor",
  "bf_bp:red_wolf_backpack_armor",
  "bf_bp:yellow_wolf_backpack_armor",
  "bf_bp:green_wolf_backpack_armor",
  "bf_bp:blue_wolf_backpack_armor",
  "bf_bp:pink_wolf_backpack_armor",
  "bf_bp:purple_wolf_backpack_armor",
  "bf_bp:white_wolf_backpack_armor",
  "bf_bp:black_wolf_backpack_armor",
  "bf_bp:brown_wolf_backpack_armor",
];

const AllBackpacksId = [
  "chest",
  "4_chests",
  "alchemy",
  "axolotl",
  "ballons",
  "armadillo",
  "aquarium",
  "disco_ball",
  "popcorn",
  "potted_plant",
  "trashcan",
  "unicorn",
  "barrel",
  "camo",
  "cat",
  "checkerboard",
  "crafting",
  "creeper",
  "cute",
  "dark",
  "chainmail",
  "diamond",
  "leather",
  "gold",
  "elytra",
  "iron",
  "netherite",
  "dragon_wings",
  "enchant",
  "speaker",
  "enderman",
  "epic_chest",
  "furnace",
  "jetpack",
  "magic_ribbon",
  "ninja",
  "rgb",
  "rich",
  "turtleshell",
  "warden",
  "wolf",

  "demon",
  "easter",
  "cauldron",
  "butterfly",
  "heart",
  "lantern",
  "medieval",
  "present",
  "satchel",
  "pumpkin",
  "sheep",
  "snail",
  "steampunk",
  "transport",
  "traveler",
  "wings",
];

const backpacksId = [
  "bf_bp:aquarium_backpack",
  "bf_bp:disco_ball_backpack",
  "bf_bp:popcorn_backpack",
  "bf_bp:potted_plant_backpack",
  "bf_bp:trashcan_backpack",
  "bf_bp:unicorn_backpack",
  "bf_bp:chest_backpack",
  "bf_bp:4_chests_backpack",
  "bf_bp:alchemy_backpack",
  "bf_bp:axolotl_backpack",
  "bf_bp:ballons_backpack",
  "bf_bp:barrel_backpack",
  "bf_bp:camo_backpack",
  "bf_bp:chainmail_backpack",
  "bf_bp:diamond_backpack",
  "bf_bp:leather_backpack",
  "bf_bp:gold_backpack",
  "bf_bp:iron_backpack",
  "bf_bp:netherite_backpack",
  "bf_bp:cat_backpack",
  "bf_bp:checkerboard_backpack",
  "bf_bp:crafting_backpack",
  "bf_bp:creeper_backpack",
  "bf_bp:cute_backpack",
  "bf_bp:dark_backpack",
  "bf_bp:elytra_backpack",
  "bf_bp:dragon_wings_backpack",
  "bf_bp:enchant_backpack",
  "bf_bp:armadillo_backpack",
  "bf_bp:enderman_backpack",
  "bf_bp:speaker_backpack",
  "bf_bp:epic_chest_backpack",
  "bf_bp:furnace_backpack",
  "bf_bp:jetpack_backpack",
  "bf_bp:magic_ribbon_backpack",
  "bf_bp:ninja_backpack",
  "bf_bp:rgb_backpack",
  "bf_bp:rich_backpack",
  "bf_bp:turtleshell_backpack",
  "bf_bp:warden_backpack",
  "bf_bp:wolf_backpack",

  "bf_bp:demon_backpack",
  "bf_bp:easter_backpack",
  "bf_bp:cauldron_backpack",
  "bf_bp:butterfly_backpack",
  "bf_bp:heart_backpack",
  "bf_bp:lantern_backpack",
  "bf_bp:medieval_backpack",
  "bf_bp:present_backpack",
  "bf_bp:satchel_backpack",
  "bf_bp:pumpkin_backpack",
  "bf_bp:sheep_backpack",
  "bf_bp:snail_backpack",
  "bf_bp:steampunk_backpack",
  "bf_bp:transport_backpack",
  "bf_bp:traveler_backpack",
  "bf_bp:wings_backpack",
];

const colorEvents = [
  "color_0",
  "color_1",
  "color_2",
  "color_3",
  "color_4",
  "color_5",
  "color_6",
  "color_7",
  "color_8",
  "color_9",
  "color_10",
  "color_11",
  "color_12",
  "color_13",
  "color_14",
  "color_15",
  "color_16",
  "color_17",
];

const backpacksUseId = [
  "bf_bp:aquarium_backpack_armor_use",
  "bf_bp:disco_ball_backpack_armor_use",
  "bf_bp:popcorn_backpack_armor_use",
  "bf_bp:potted_plant_backpack_armor_use",
  "bf_bp:trashcan_backpack_armor_use",
  "bf_bp:unicorn_backpack_armor_use",
  "bf_bp:chest_backpack_armor_use",
  "bf_bp:4_chests_backpack_armor_use",
  "bf_bp:barrel_backpack_armor_use",
  "bf_bp:crafting_backpack_armor_use",
  "bf_bp:checkerboard_backpack_armor_use",
  "bf_bp:dark_backpack_armor_use",
  "bf_bp:dragon_wings_backpack_armor_use",
  "bf_bp:enchant_backpack_armor_use",
  "bf_bp:enderman_backpack_armor_use",
  "bf_bp:speaker_backpack_armor_use",
  "bf_bp:epic_chest_backpack_armor_use",
  "bf_bp:alchemy_backpack_armor_use",
  "bf_bp:elytra_backpack_armor_use",
  "bf_bp:axolotl_backpack_armor_use",
  "bf_bp:armadillo_backpack_armor_use",
  "bf_bp:creeper_backpack_armor_use",
  "bf_bp:chainmail_backpack_armor_use",
  "bf_bp:diamond_backpack_armor_use",
  "bf_bp:leather_backpack_armor_use",
  "bf_bp:gold_backpack_armor_use",
  "bf_bp:iron_backpack_armor_use",
  "bf_bp:netherite_backpack_armor_use",
  "bf_bp:warden_backpack_armor_use",
  "bf_bp:wolf_backpack_armor_use",
  "bf_bp:camo_backpack_armor_use",
  "bf_bp:cat_backpack_armor_use",
  "bf_bp:cute_backpack_armor_use",
  "bf_bp:magic_ribbon_backpack_armor_use",
  "bf_bp:ballons_backpack_armor_use",
  "bf_bp:furnace_backpack_armor_use",
  "bf_bp:jetpack_backpack_armor_use",
  "bf_bp:ninja_backpack_armor_use",
  "bf_bp:rgb_backpack_armor_use",
  "bf_bp:rich_backpack_armor_use",
  "bf_bp:turtleshell_backpack_armor_use",

  "bf_bp:demon_backpack_armor_use",
  "bf_bp:easter_backpack_armor_use",
  "bf_bp:cauldron_backpack_armor_use",
  "bf_bp:butterfly_backpack_armor_use",
  "bf_bp:heart_backpack_armor_use",
  "bf_bp:lantern_backpack_armor_use",
  "bf_bp:medieval_backpack_armor_use",
  "bf_bp:present_backpack_armor_use",
  "bf_bp:satchel_backpack_armor_use",
  "bf_bp:pumpkin_backpack_armor_use",
  "bf_bp:sheep_backpack_armor_use",
  "bf_bp:snail_backpack_armor_use",
  "bf_bp:steampunk_backpack_armor_use",
  "bf_bp:transport_backpack_armor_use",
  "bf_bp:traveler_backpack_armor_use",
  "bf_bp:wings_backpack_armor_use",
];

const BackpackNames = [
  {
    id: "bf_bp:chest_backpack",
    type: "chest",
    avaliableColors: {
      0: "chest",
      1: "red",
      2: "yellow",
      3: "green",
      4: "blue",
      5: "pink",
      6: "purple",
      7: "white",
      8: "black",
    },
    removeItem: "bf_bp:chest_backpack_armor_use",
  },
  {
    id: "bf_bp:4_chests_backpack",
    type: "4_chests",
    avaliableColors: {
      0: "4_chests",
    },
    removeItem: "bf_bp:4_chests_backpack_armor_use",
  },
  {
    id: "bf_bp:aquarium_backpack",
    type: "aquarium",
    avaliableColors: {
      0: "aquarium",
    },
    removeItem: "bf_bp:aquarium_backpack_armor_use",
  },
  {
    id: "bf_bp:disco_ball_backpack",
    type: "disco_ball",
    avaliableColors: {
      0: "disco_ball",
    },
    removeItem: "bf_bp:disco_ball_backpack_armor_use",
  },
  {
    id: "bf_bp:chainmail_backpack",
    type: "chainmail",
    avaliableColors: {
      0: "chainmail",
    },
    removeItem: "bf_bp:chainmail_backpack_armor_use",
  },
  {
    id: "bf_bp:elytra_backpack",
    type: "elytra",
    avaliableColors: {
      0: "elytra",
    },
    removeItem: "bf_bp:elytra_backpack_armor_use",
  },
  {
    id: "bf_bp:diamond_backpack",
    type: "diamond",
    avaliableColors: {
      0: "diamond",
    },
    removeItem: "bf_bp:diamond_backpack_armor_use",
  },
  {
    id: "bf_bp:leather_backpack",
    type: "leather",
    avaliableColors: {
      0: "leather",
    },
    removeItem: "bf_bp:leather_backpack_armor_use",
  },
  {
    id: "bf_bp:gold_backpack",
    type: "gold",
    avaliableColors: {
      0: "gold",
    },
    removeItem: "bf_bp:gold_backpack_armor_use",
  },
  {
    id: "bf_bp:iron_backpack",
    type: "iron",
    avaliableColors: {
      0: "iron",
    },
    removeItem: "bf_bp:iron_backpack_armor_use",
  },
  {
    id: "bf_bp:netherite_backpack",
    type: "netherite",
    avaliableColors: {
      0: "netherite",
    },
    removeItem: "bf_bp:netherite_backpack_armor_use",
  },
  {
    id: "bf_bp:popcorn_backpack",
    type: "popcorn",
    avaliableColors: {
      0: "popcorn",
    },
    removeItem: "bf_bp:popcorn_backpack_armor_use",
  },
  {
    id: "bf_bp:potted_plant_backpack",
    type: "potted_plant",
    avaliableColors: {
      0: "potted_plant",
      1: "flower2",
      2: "flower3",
      3: "flower4",
      4: "flower5",
      5: "flower6",
      6: "flower7",
      7: "flower8",
      8: "flower9",
      9: "flower10",
      10: "flower11",
      11: "flower12",
      12: "flower13",
      13: "flower14",
      14: "flower15",
      15: "flower16",
      16: "flower17",
      17: "flower17",
    },
    removeItem: "bf_bp:potted_plant_backpack_armor_use",
  },
  {
    id: "bf_bp:trashcan_backpack",
    type: "trashcan",
    avaliableColors: {
      0: "trashcan",
    },
    removeItem: "bf_bp:trashcan_backpack_armor_use",
  },
  {
    id: "bf_bp:unicorn_backpack",
    type: "unicorn",
    avaliableColors: {
      0: "unicorn",
    },
    removeItem: "bf_bp:unicorn_backpack_armor_use",
  },
  {
    id: "bf_bp:epic_chest_backpack",
    type: "epic_chest",
    avaliableColors: {
      0: "epic_chest",
      1: "red",
      2: "yellow",
      3: "green",
      4: "blue",
      5: "pink",
      6: "purple",
      7: "white",
      8: "black",
    },
    removeItem: "bf_bp:epic_chest_backpack_armor_use",
  },
  {
    id: "bf_bp:crafting_backpack",
    type: "crafting",
    avaliableColors: {
      0: "crafting",
      1: "red",
      2: "yellow",
      3: "green",
      4: "blue",
      5: "pink",
      6: "purple",
      7: "white",
      8: "black",
    },
    removeItem: "bf_bp:crafting_backpack_armor_use",
  },
  {
    id: "bf_bp:furnace_backpack",
    type: "furnace",
    avaliableColors: {
      0: "furnace",
      1: "red",
      2: "yellow",
      3: "green",
      4: "blue",
      5: "pink",
      6: "purple",
      7: "white",
      8: "black",
    },
    removeItem: "bf_bp:furnace_backpack_armor_use",
  },
  {
    id: "bf_bp:enchant_backpack",
    type: "enchant",
    avaliableColors: {
      0: "enchant",
    },
    removeItem: "bf_bp:enchant_backpack_armor_use",
  },
  {
    id: "bf_bp:alchemy_backpack",
    type: "alchemy",
    avaliableColors: {
      0: "alchemy",
      1: "yellow",
      2: "green",
      3: "blue",
      4: "pink",
      5: "purple",
      6: "white",
      7: "black",
    },
    removeItem: "bf_bp:alchemy_backpack_armor_use",
  },
  {
    id: "bf_bp:camo_backpack",
    type: "camo",
    avaliableColors: {
      0: "camo",
      1: "red",
      2: "pink",
      3: "blue",
      4: "brown",
    },
    removeItem: "bf_bp:camo_backpack_armor_use",
  },
  {
    id: "bf_bp:cat_backpack",
    type: "cat",
    avaliableColors: {
      0: "cat",
      1: "red",
      2: "pink",
      3: "blue",
      4: "black",
    },
    removeItem: "bf_bp:cat_backpack_armor_use",
  },
  {
    id: "bf_bp:cute_backpack",
    type: "cute",
    avaliableColors: {
      0: "cute",
      1: "red",
      2: "pink",
      3: "blue",
      4: "black",
    },
    removeItem: "bf_bp:cute_backpack_armor_use",
  },
  {
    id: "bf_bp:ballons_backpack",
    type: "ballons",
    avaliableColors: {
      0: "ballons",
      1: "purple",
      2: "yellow",
      3: "black",
    },
    removeItem: "bf_bp:ballons_backpack_armor_use",
  },
  {
    id: "bf_bp:barrel_backpack",
    type: "barrel",
    avaliableColors: {
      0: "barrel",
    },
    removeItem: "bf_bp:barrel_backpack_armor_use",
  },
  {
    id: "bf_bp:checkerboard_backpack",
    type: "checkerboard",
    avaliableColors: {
      0: "checkerboard",
    },
    removeItem: "bf_bp:checkerboard_backpack_armor_use",
  },
  {
    id: "bf_bp:dark_backpack",
    type: "dark",
    avaliableColors: {
      0: "dark",
    },
    removeItem: "bf_bp:dark_backpack_armor_use",
  },
  {
    id: "bf_bp:enchant_backpack",
    type: "enchant",
    avaliableColors: {
      0: "enchant",
    },
    removeItem: "bf_bp:enchant_backpack_armor_use",
  },
  {
    id: "bf_bp:jetpack_backpack",
    type: "jetpack",
    avaliableColors: {
      0: "jetpack",
    },
    removeItem: "bf_bp:jetpack_backpack_armor_use",
  },
  {
    id: "bf_bp:ninja_backpack",
    type: "ninja",
    avaliableColors: {
      0: "ninja",
    },
    removeItem: "bf_bp:ninja_backpack_armor_use",
  },
  {
    id: "bf_bp:enderman_backpack",
    type: "enderman",
    avaliableColors: {
      0: "enderman",
    },
    removeItem: "bf_bp:enderman_backpack_armor_use",
  },
  {
    id: "bf_bp:speaker_backpack",
    type: "speaker",
    avaliableColors: {
      0: "speaker",
      1: "speaker",
      2: "speaker",
      3: "speaker",
      4: "speaker",
      5: "speaker",
      6: "speaker",
      7: "speaker",
      8: "speaker",
      9: "speaker",
      10: "speaker",
      11: "speaker",
    },
    removeItem: "bf_bp:speaker_backpack_armor_use",
  },
  {
    id: "bf_bp:rgb_backpack",
    type: "rgb",
    avaliableColors: {
      0: "rgb",
    },
    removeItem: "bf_bp:rgb_backpack_armor_use",
  },
  {
    id: "bf_bp:rich_backpack",
    type: "rich",
    avaliableColors: {
      0: "rich",
    },
    removeItem: "bf_bp:rich_backpack_armor_use",
  },
  {
    id: "bf_bp:turtleshell_backpack",
    type: "turtleshell",
    avaliableColors: {
      0: "turtleshell",
    },
    removeItem: "bf_bp:turtleshell_backpack_armor_use",
  },
  {
    id: "bf_bp:armadillo_backpack",
    type: "armadillo",
    avaliableColors: {
      0: "armadillo",
    },
    removeItem: "bf_bp:armadillo_backpack_armor_use",
  },
  {
    id: "bf_bp:dragon_wings_backpack",
    type: "dragon_wings",
    avaliableColors: {
      0: "dragon_wings",
      1: "black",
      2: "yellow",
      3: "green",
      4: "blue",
      5: "pink",
      6: "purple",
      7: "white",
    },
    removeItem: "bf_bp:dragon_wings_backpack_armor_use",
  },
  {
    id: "bf_bp:warden_backpack",
    type: "warden",
    avaliableColors: {
      0: "warden",
      1: "yellow",
      2: "green",
      3: "pink",
      4: "white",
      5: "brown",
    },
    removeItem: "bf_bp:warden_backpack_armor_use",
  },
  {
    id: "bf_bp:wolf_backpack",
    type: "wolf",
    avaliableColors: {
      0: "wolf",
      1: "yellow",
      2: "green",
      3: "blue",
      4: "pink",
      5: "brown",
    },
    removeItem: "bf_bp:wolf_backpack_armor_use",
  },
  {
    id: "bf_bp:magic_ribbon_backpack",
    type: "magic_ribbon",
    avaliableColors: {
      0: "magic_ribbon",
      1: "purple",
      2: "pink",
      3: "blue",
      4: "green",
    },
    removeItem: "bf_bp:magic_ribbon_backpack_armor_use",
  },
  {
    id: "bf_bp:creeper_backpack",
    type: "creeper",
    avaliableColors: {
      0: "creeper",
      1: "yellow",
      2: "blue",
      3: "pink",
      4: "white",
      5: "brown",
    },
    removeItem: "bf_bp:creeper_backpack_armor_use",
  },
  {
    id: "bf_bp:axolotl_backpack",
    type: "axolotl",
    avaliableColors: {
      0: "axolotl",
      1: "yellow",
      2: "green",
      3: "purple",
      4: "white",
      5: "brown",
    },
    removeItem: "bf_bp:axolotl_backpack_armor_use",
  },

  {
    id: "bf_bp:butterfly_backpack",
    type: "butterfly",
    avaliableColors: {
      0: "butterfly",
      1: "blue",
      2: "magenta",
      3: "purple",
      4: "yellow",
    },
    removeItem: "bf_bp:butterfly_backpack_armor_use",
  },
  {
    id: "bf_bp:cauldron_backpack",
    type: "cauldron",
    avaliableColors: {
      0: "cauldron",
      1: "blue",
      2: "green",
      3: "pink",
      4: "red",
    },
    removeItem: "bf_bp:cauldron_backpack_armor_use",
  },
  {
    id: "bf_bp:demon_backpack",
    type: "demon",
    avaliableColors: {
      0: "demon",
      1: "black",
      2: "enddragon",
      3: "purple",
      4: "red",
    },
    removeItem: "bf_bp:demon_backpack_armor_use",
  },
  {
    id: "bf_bp:easter_backpack",
    type: "easter",
    avaliableColors: {
      0: "easter",
      1: "light_blue",
      2: "orange",
      3: "pink",
    },
    removeItem: "bf_bp:easter_backpack_armor_use",
  },
  {
    id: "bf_bp:heart_backpack",
    type: "heart",
    avaliableColors: {
      0: "heart",
      1: "blue",
      2: "gray",
      3: "pink",
      4: "purple",
    },
    removeItem: "bf_bp:heart_backpack_armor_use",
  },
  {
    id: "bf_bp:lantern_backpack",
    type: "lantern",
    avaliableColors: {
      0: "lantern",
      1: "blue",
      2: "green",
      3: "purple",
      4: "red",
    },
    removeItem: "bf_bp:lantern_backpack_armor_use",
  },
  {
    id: "bf_bp:medieval_backpack",
    type: "medieval",
    avaliableColors: {
      0: "medieval",
      1: "cyan",
      2: "pink",
      3: "red",
      4: "yellow",
    },
    removeItem: "bf_bp:medieval_backpack_armor_use",
  },
  {
    id: "bf_bp:present_backpack",
    type: "present",
    avaliableColors: {
      0: "present",
      1: "green",
      2: "green_r",
      3: "yellow",
    },
    removeItem: "bf_bp:present_backpack_armor_use",
  },
  {
    id: "bf_bp:pumpkin_backpack",
    type: "pumpkin",
    avaliableColors: {
      0: "pumpkin",
      1: "lightt",
      2: "scary",
      3: "smile",
    },
    removeItem: "bf_bp:pumpkin_backpack_armor_use",
  },
  {
    id: "bf_bp:satchel_backpack",
    type: "satchel",
    avaliableColors: {
      0: "satchel",
      1: "blue",
      2: "brown",
      3: "green",
    },
    removeItem: "bf_bp:satchel_backpack_armor_use",
  },
  {
    id: "bf_bp:sheep_backpack",
    type: "sheep",
    avaliableColors: {
      0: "sheep",
      1: "cyan",
      2: "green",
      3: "purple",
      4: "rainbow",
      5: "red",
    },
    removeItem: "bf_bp:sheep_backpack_armor_use",
  },
  {
    id: "bf_bp:snail_backpack",
    type: "snail",
    avaliableColors: {
      0: "snail",
      1: "brown",
      2: "green",
      3: "pink",
    },
    removeItem: "bf_bp:snail_backpack_armor_use",
  },
  {
    id: "bf_bp:steampunk_backpack",
    type: "steampunk",
    avaliableColors: {
      0: "steampunk",
      1: "blackstone",
      2: "exposed",
      3: "oxidizied",
      4: "rusty",
    },
    removeItem: "bf_bp:steampunk_backpack_armor_use",
  },
  {
    id: "bf_bp:transport_backpack",
    type: "transport",
    avaliableColors: {
      0: "transport",
      1: "blue",
      2: "gray",
      3: "pink",
      4: "white",
    },
    removeItem: "bf_bp:transport_backpack_armor_use",
  },
  {
    id: "bf_bp:traveler_backpack",
    type: "traveler",
    avaliableColors: {
      0: "traveler",
      1: "cyan",
      2: "green",
      3: "light_blue",
      4: "pink",
    },
    removeItem: "bf_bp:traveler_backpack_armor_use",
  },
  {
    id: "bf_bp:wings_backpack",
    type: "wings",
    avaliableColors: {
      0: "wings",
      1: "black",
      2: "gold",
      3: "rainbow",
      4: "pink",
    },
    removeItem: "bf_bp:wings_backpack_armor_use",
  },
];

function MenuConfig(player) {
  const form = new ActionFormData();
  form.title("Backpack Abilities");
  form.body("Select a backpack:");
  let functions = [];
  {
    form.button("Axolotl", "textures/bf/bp/icons/axolotl_backpack");
    functions.push((res) => {
      MenuToggle(player, "Axolotl");
    });
  }
  {
    form.button("Creeper", "textures/bf/bp/icons/creeper_backpack");
    functions.push((res) => {
      MenuToggle(player, "Creeper");
    });
  }
  {
    form.button("Dragon Wings", "textures/bf/bp/icons/dragon_backpack");
    functions.push((res) => {
      MenuToggle(player, "Dragon Wings");
    });
  }
  {
    form.button("Warden", "textures/bf/bp/icons/sculk_backpack");
    functions.push((res) => {
      MenuToggle(player, "Warden");
    });
  }
  {
    form.button("Wolf", "textures/bf/bp/icons/wolf_backpack");
    functions.push((res) => {
      MenuToggle(player, "Wolf");
    });
  }
  {
    form.button("Enderman", "textures/bf/bp/icons/enderman_backpack");
    functions.push((res) => {
      MenuToggle(player, "Enderman");
    });
  }

  form.show(player).then((res) => {
    const canceled = res.canceled;
    if (canceled == true) {
      return;
    }
    functions[res.selection]();
  });
}
function MenuToggle(player, name) {
  const form = new ModalFormData();
  form.title(name);
  if (name == "Axolotl") {
    if (player.getDynamicProperty("toggle_1") == 0) {
      form.toggle("Backpack Special", false);
    }
    if (player.getDynamicProperty("toggle_1") == 1) {
      form.toggle("Backpack Special", true);
    }
  }
  if (name == "Creeper") {
    if (player.getDynamicProperty("toggle_2") == 0) {
      form.toggle("Backpack Special", false);
    }
    if (player.getDynamicProperty("toggle_2") == 1) {
      form.toggle("Backpack Special", true);
    }
  }
  if (name == "Dragon Wings") {
    if (player.getDynamicProperty("toggle_3") == 0) {
      form.toggle("Backpack Special", false);
    }
    if (player.getDynamicProperty("toggle_3") == 1) {
      form.toggle("Backpack Special", true);
    }
  }
  if (name == "Warden") {
    if (player.getDynamicProperty("toggle_4") == 0) {
      form.toggle("Backpack Special", false);
    }
    if (player.getDynamicProperty("toggle_4") == 1) {
      form.toggle("Backpack Special", true);
    }
  }
  if (name == "Wolf") {
    if (player.getDynamicProperty("toggle_5") == 0) {
      form.toggle("Backpack Special", false);
    }
    if (player.getDynamicProperty("toggle_5") == 1) {
      form.toggle("Backpack Special", true);
    }
  }
  if (name == "Enderman") {
    if (player.getDynamicProperty("toggle_6") == 0) {
      form.toggle("Backpack Special", false);
    }
    if (player.getDynamicProperty("toggle_6") == 1) {
      form.toggle("Backpack Special", true);
    }
  }
  form.show(player).then((res) => {
    const canceled = res.canceled;
    if (canceled == true) {
      return;
    }

    if (res.formValues[0] == false) {
      if (name == "Axolotl") {
        player.setDynamicProperty("toggle_1", 0);
      }
      if (name == "Creeper") {
        player.setDynamicProperty("toggle_2", 0);
      }
      if (name == "Dragon Wings") {
        player.setDynamicProperty("toggle_3", 0);
      }
      if (name == "Warden") {
        player.setDynamicProperty("toggle_4", 0);
      }
      if (name == "Wolf") {
        player.setDynamicProperty("toggle_5", 0);
      }
      if (name == "Enderman") {
        player.setDynamicProperty("toggle_6", 0);
      }
      player.runCommand(
        `tellraw @s {"rawtext":[{"text":"§cYou don't have special skills in your backpack right now!"}]}`
      );
    }
    if (res.formValues[0] == true) {
      if (name == "Axolotl") {
        player.setDynamicProperty("toggle_1", 1);
      }
      if (name == "Creeper") {
        player.setDynamicProperty("toggle_2", 1);
      }
      if (name == "Dragon Wings") {
        player.setDynamicProperty("toggle_3", 1);
      }
      if (name == "Warden") {
        player.setDynamicProperty("toggle_4", 1);
      }
      if (name == "Wolf") {
        player.setDynamicProperty("toggle_5", 1);
      }
      if (name == "Enderman") {
        player.setDynamicProperty("toggle_6", 1);
      }
      player.runCommand(
        `tellraw @s {"rawtext":[{"text":"§aYou will have special skills in your backpack now!"}]}`
      );
    }
  });
}

const commandsRunInterval = [
  `execute as @s if entity @e[family=backpack,r=1.5,tag=pickedBackpack] at @s run tag @s add pickedBackpack`,
  `execute as @s if entity @e[family=backpack,r=1.5,tag=pickedBackpack,tag=pickedBlockBackpack] at @s run tag @s add pickedBlockBackpack`,
  `execute as @s if entity @e[family=backpack,r=1.5,tag=pickedBackpack] at @s run tag @s remove pickingBackpack`,
  `execute as @s unless entity @e[family=backpack,r=1.5,tag=pickedBackpack] at @s run tag @s remove pickedBackpack`,
  `execute as @s unless entity @e[family=backpack,r=1.5,tag=pickedBackpack] at @s run tag @s remove pickedBlockBackpack`,
];

const commandsRunInterval2 = [
  `execute as @s if entity @e[family=backpack,r=4] at @s run event entity @e[family=backpack,r=4] in_range`,
  `execute as @s if entity @e[type=bf_bp:speaker_backpack,rm=2,r=3] at @s run stopsound @s`,
  `execute as @s if entity @e[type=bf_bp:trashcan_backpack,rm=3,r=4] at @s run stopsound @s trashbin_backpack`,
  `execute as @s unless entity @e[type=bf_bp:trashcan_backpack,r=4] at @s run stopsound @s trashbin_backpack`,
  `execute as @s if entity @e[type=bf_bp:trashcan_backpack,r=3] at @s[tag=!trashcan_loc] run playsound trashbin_backpack @s`,
  `execute as @s if entity @e[type=bf_bp:trashcan_backpack,r=3] at @s run tag @s add trashcan_loc`,
  `execute as @s if entity @e[type=bf_bp:trashcan_backpack,rm=3,r=4] at @s run tag @s remove trashcan_loc`,
  `execute as @s if entity @e[type=bf_bp:disco_ball_backpack,rm=2,r=3] at @s run stopsound @s discoball_backpack`,
  `execute as @s unless entity @e[type=bf_bp:disco_ball_backpack,r=3] at @s run stopsound @s discoball_backpack`,
  `execute as @s if entity @e[family=backpack,rm=4,r=5] at @s run event entity @e[family=backpack,rm=4,r=5] out_range`,
];

// Function

function getAllArmorColors(tag, itemId) {
  const chestBackpackColors = [
    `bf_bp:${tag}_backpack_armor`,
    `bf_bp:red_${tag}_backpack_armor`,
    `bf_bp:yellow_${tag}_backpack_armor`,
    `bf_bp:green_${tag}_backpack_armor`,
    `bf_bp:blue_${tag}_backpack_armor`,
    `bf_bp:pink_${tag}_backpack_armor`,
    `bf_bp:purple_${tag}_backpack_armor`,
    `bf_bp:white_${tag}_backpack_armor`,
    `bf_bp:black_${tag}_backpack_armor`,
    `bf_bp:brown_${tag}_backpack_armor`,

    `bf_bp:gray_${tag}_backpack_armor`,
    `bf_bp:magenta_${tag}_backpack_armor`,
    `bf_bp:cyan_${tag}_backpack_armor`,
    `bf_bp:light_blue_${tag}_backpack_armor`,
    `bf_bp:rainbow_${tag}_backpack_armor`,
    `bf_bp:green_r_${tag}_backpack_armor`,
    `bf_bp:orange_${tag}_backpack_armor`,

    `bf_bp:gold_${tag}_backpack_armor`,

    `bf_bp:blackstone_${tag}_backpack_armor`,
    `bf_bp:exposed_${tag}_backpack_armor`,
    `bf_bp:oxidizied_${tag}_backpack_armor`,
    `bf_bp:rusty_${tag}_backpack_armor`,

    `bf_bp:lightt_${tag}_backpack_armor`,
    `bf_bp:scary_${tag}_backpack_armor`,
    `bf_bp:smile_${tag}_backpack_armor`,

    `bf_bp:enddragon_${tag}_backpack_armor`,

    `bf_bp:flower2_${tag}_backpack_armor`,
    `bf_bp:flower3_${tag}_backpack_armor`,
    `bf_bp:flower4_${tag}_backpack_armor`,
    `bf_bp:flower5_${tag}_backpack_armor`,
    `bf_bp:flower6_${tag}_backpack_armor`,
    `bf_bp:flower7_${tag}_backpack_armor`,
    `bf_bp:flower8_${tag}_backpack_armor`,
    `bf_bp:flower9_${tag}_backpack_armor`,
    `bf_bp:flower10_${tag}_backpack_armor`,
    `bf_bp:flower11_${tag}_backpack_armor`,
    `bf_bp:flower12_${tag}_backpack_armor`,
    `bf_bp:flower13_${tag}_backpack_armor`,
    `bf_bp:flower14_${tag}_backpack_armor`,
    `bf_bp:flower15_${tag}_backpack_armor`,
    `bf_bp:flower16_${tag}_backpack_armor`,
    `bf_bp:flower17_${tag}_backpack_armor`,
  ];
  return chestBackpackColors.includes(itemId);
}

function runCommands(player, commands) {
  commands.forEach((command) => player.runCommand(command));
}

function backpackSpecialsHabilities(player, backpack) {
  backpackSpecial(player);
  player.addTag("executeOne");
  player.addTag("executeTwo");

  const abilities = {
    axolotl: () => {
      runCommands(player, [
        `effect @s absorption 10 1 true`,
        `effect @a[r=10] regeneration 10 3 true`,
      ]);
      axolotlSound(player);
    },
    dragon_wings: () => {
      runCommands(player, [
        "playsound dragon_backpack_firebreath @a[r=10] ~~~ 0.5",
        `playsound random.explode @a[r=4]`,
        `particle bf_bp:breath2 ^^^1`,
        `particle bf_bp:breath2 ^^^1.5`,
        `particle bf_bp:breath2 ^^^2`,
        `setblock ^^2^2 fire`,
        `setblock ^^2^3 fire`,
        `setblock ^^2^4 fire`,
        `setblock ^^2^5 fire`,
        `setblock ^^2^6 fire`,
        `setblock ^^2^7 fire`,
        `setblock ^^2^8 fire`,
        `setblock ^^2^9 fire`,
        `setblock ^^2^10 fire`,
      ]);
      shootProjectile(player, "bf_bp:dragon_explode", 1);
    },
    warden: () => {
      runCommands(player, [`playsound mob.warden.sonic_boom @a[r=5]`]);
      shootProjectile(player, "bf_bp:sonic_explode", 1);
    },
    creeper: () => {
      runCommands(player, [
        `playsound random.explode @a[r=4]`,
        `particle bf_bp:boom`,
        `summon bf_bp:explode`,
        `fill ~-1~-1~-1~2~2~2 air replace grass_block`,
        `fill ~0~-1~0~1~1~1 air replace grass_block`,
        `fill ~-1~-1~-1~2~2~2 air replace dirt`,
        `fill ~0~-1~0~1~1~1 air replace dirt`,
        `fill ~-1~-1~-1~2~2~2 air replace stone`,
        `fill ~0~-1~0~1~1~1 air replace stone`,
        `fill ~-1~-1~-1~2~2~2 air replace sand`,
        `fill ~0~-1~0~1~1~1 air replace sand`,
        `execute at @s as @s unless block ~1~-2~ bedrock run setblock ~1~-2~ air`,
        `execute at @s as @s unless block ~~-2~ bedrock run setblock ~~-2~ air`,
        `execute at @s as @s unless block ~1~-2~1 bedrock run setblock ~1~-2~1 air`,
        `execute at @s as @s unless block ~~-2~1 bedrock run setblock ~~-2~1 air`,
        `fill ~-1~~-1~2~2~2 air replace grass_block`,
        `fill ~-1~1~-1~2~2~2 air replace grass_block`,
        `fill ~-1~~-1~2~2~2 air replace dirt`,
        `fill ~-1~1~-1~2~2~2 air replace dirt`,
        `fill ~-1~~-1~2~2~2 air replace stone`,
        `fill ~-1~1~-1~2~2~2 air replace stone`,
        `fill ~-1~~-1~2~2~2 air replace sand`,
        `fill ~-1~1~-1~2~2~2 air replace sand`,
        `execute at @s as @s unless block ~2~-1~ bedrock run setblock ~2~-1~ fire`,
        `execute at @s as @s unless block ~2~-1~2 bedrock run setblock ~2~-1~2 fire`,
        `execute at @s as @s unless block ~2~-1~ bedrock run setblock ~2~-1~ fire`,
        `execute at @s as @s unless block ~-2~-1~-2 bedrock run setblock ~-2~-1~-2 fire`,
        `execute at @s as @s unless block ~-2~-1~ bedrock run setblock ~-2~-1~ fire`,
        `execute at @s as @s unless block ~-2~-1~1 bedrock run setblock ~-2~-1~1 fire`,
        `execute at @s as @s unless block ~1~-1~ bedrock run setblock ~1~-1~ fire`,
        `execute at @s as @s unless block ~-1~1~ bedrock run setblock ~-1~1~ fire`,
        `execute at @s as @s unless block ~1~~2 bedrock run setblock ~1~~2 fire`,
        `damage @e[tag=!executeTwo,r=7,family=!backpack] 5`,
      ]);
    },
    enderman: () => {
      const loc = player.getBlockFromViewDirection()?.block.location;
      if (loc != undefined) {
        player?.teleport({
          x: loc.x,
          y: loc.y,
          z: loc.z,
        });
      }
      runCommands(player, [
        `playsound mob.shulker.teleport @a[r=4]`,
        `tag @e[type=bf_bp:enderman_backpack,c=1,r=4,tag=hasPicked] add teleport`,
        `tp @s ~~~`,
        `tp @e[type=bf_bp:enderman_backpack,c=1,tag=hasPicked,tag=teleport] @p[tag=teleport]`,
        `particle bf_bp:dust2`,
        `particle minecraft:end_chest ~~1~`,
        `particle minecraft:end_chest ~~1~`,
        `particle minecraft:end_chest ~~1~`,
        `particle minecraft:end_chest ~~1~`,
        `particle minecraft:end_chest ~~1~`,
        `playsound mob.shulker.teleport @a[r=4]`,
      ]);
      player.runCommand(`tp ~~1~`);
      cooldownTeleport(player);
      player.addTag("teleport");
    },
    wolf: () => {
      const wolves = player.dimension.getEntities({
        families: ["wolf"],
        closest: 4,
        maxDistance: 10,
        location: player.location,
      })
      let count = 0;
      let wolf;
      for (wolf of wolves) {
        count ++;
      }
      console.warn(count);
      if (count < 4) {
      for (let i = 0; i < 2; i++) {
        const wolf = player.dimension.spawnEntity(
          "minecraft:wolf",
          player.location
        );
        const tameable = wolf.getComponent("minecraft:tameable");
        tameable.tame(player);
      }
    } else {
      player.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"§cYou can't summon more wolves!"}]}`);
    }
    },
  };

  if (abilities[backpack]) {
    abilities[backpack]();
  }
}

// Code
world.beforeEvents.playerBreakBlock.subscribe((event) => {
  const { block, player } = event;
  const blockLocation = block.location;
  if (
    block.getItemStack().typeId === "minecraft:furnace" ||
    block.getItemStack().typeId === "minecraft:enchanting_table" ||
    block.getItemStack().typeId === "bf_bp:crafting_table" ||
    block.getItemStack().typeId === "minecraft:brewing_stand"||
    block.getItemStack().typeId === "minecraft:blast_furnace"
  ) {
    system.runTimeout(() => {
      const backpackE = block.dimension.getEntities({
        location: {
          x: blockLocation.x,
          y: blockLocation.y + 1,
          z: blockLocation.z,
        },
        families: ["backpack"],
        closest: 1,
        maxDistance: 2,
      });

      for (let backpack of backpackE) {
        const itemStack = new ItemStack(backpack.typeId, 1);
        if (backpack.typeId == "bf_bp:furnace_backpack") {
          backpack.dimension.spawnItem(itemStack, backpack.location);
          backpack.remove();
        }
        if (backpack.typeId == "bf_bp:enchant_backpack") {
          backpack.dimension.spawnItem(itemStack, backpack.location);
          backpack.remove();
        }
        if (backpack.typeId == "bf_bp:crafting_backpack") {
          backpack.dimension.spawnItem(itemStack, backpack.location);
          backpack.remove();
        }
        if (backpack.typeId == "bf_bp:alchemy_backpack") {
          backpack.dimension.spawnItem(itemStack, backpack.location);
          backpack.remove();
        }
        if (backpack.typeId == "bf_bp:steampunk_backpack") {
          backpack.dimension.spawnItem(itemStack, backpack.location);
          backpack.remove();
        }
      }
    });
  }
});

world.afterEvents.playerSpawn.subscribe((event) => {
  const { player, initialSpawn } = event;

  if (!player.hasTag("started")) {
    player.runCommand(`loot spawn ~ ~ ~ loot \"bf/bp/others/pick_up\"`);
    player.runCommand(`loot spawn ~ ~ ~ loot \"bf/bp/others/specials\"`);
    player.runCommand(`loot spawn ~ ~ ~ loot \"bf/bp/others/book\"`);
    player.runCommand(
      `tellraw @s {"rawtext":[{"text":"§b[!]§e Backpack Addon§f has been added."}]}`
    );
    player.runCommand(
      `tellraw @s {"rawtext":[{"translate":"action.text.bf_bp.text6"}]}`
    );

    player.addTag("started");
  }
});
world.beforeEvents.playerLeave.subscribe((event) => {
  const { player } = event;
  const inventory = player.getComponent("minecraft:inventory").container;
  //player.setDynamicProperty("backpack_state", false);
  /*
  system.runInterval(() => {
    player.runCommandAsync(`say assa${inventory}`)
  },0)
  */
});

system.runInterval(async () => {
  world.getAllPlayers().forEach((player) => {
    const MainhandItem = player
      .getComponent("equippable")
      .getEquipment("Mainhand")?.typeId;
    const itemId = player
      .getComponent("equippable")
      .getEquipment("Chest")?.typeId;

    if (player.getDynamicProperty("toggle_1") == undefined) {
      player.setDynamicProperty("toggle_1", 1);
    }
    if (player.getDynamicProperty("toggle_2") == undefined) {
      player.setDynamicProperty("toggle_2", 1);
    }
    if (player.getDynamicProperty("toggle_3") == undefined) {
      player.setDynamicProperty("toggle_3", 1);
    }
    if (player.getDynamicProperty("toggle_4") == undefined) {
      player.setDynamicProperty("toggle_4", 1);
    }
    if (player.getDynamicProperty("toggle_5") == undefined) {
      player.setDynamicProperty("toggle_5", 1);
    }
    if (player.getDynamicProperty("toggle_6") == undefined) {
      player.setDynamicProperty("toggle_6", 1);
    }

    if (player.getDynamicProperty("backpack_name") == undefined) {
      player.setDynamicProperty("backpack_name", "none");
    }
    if (player.getDynamicProperty("backpack_state") == undefined) {
      player.setDynamicProperty("backpack_state", false);
    }

    const { x: dx, y: dy, z: dz } = player.getViewDirection();
    if (player.isJumping) {
      if (
        AllBackpacksArmorWithSpecials.includes(itemId) &&
        itemId.includes("wings")
      ) {
        player.applyKnockback(dx, dz, 0.3, 0.25);
      } else if (itemId == "bf_bp:jetpack_backpack_armor") {
        player.applyKnockback(dx, dz, 0.0, 0.2);
      } else if (itemId == "bf_bp:elytra_backpack_armor") {
        player.applyKnockback(dx, dz, 0.7, 0.1);
      } else if (
        AllBackpacksBallons.includes(itemId) &&
        itemId.includes("ballons")
      ) {
        player.applyKnockback(dx, dz, 0.0, 0.1);
      } else if (itemId == "bf_bp:jetpack_backpack_armor") {
        player.runCommand("effect @s slow_falling 1 1 true");
        player.addTag("isFlyingJetpack");
      }
    }
    if (player.isJumping) {
      if (NewsBackpacksCanFly.includes(itemId)) {
        player.applyKnockback(dx, dz, 0.3, 0.25);
      }
    }
    if (player.isSneaking && !player.hasTag("bfsneaking")) {
      player.addTag("bfsneaking");
      player.runCommand(
        "event entity @e[r=1.5,type=bf_bp:speaker_backpack,c=1] musics_add"
      );
      player.runCommand(
        "event entity @e[r=1.5,type=bf_bp:disco_ball_backpack,c=1] musics_add"
      );
    }

    if (!player.isSneaking) {
      player.removeTag("bfsneaking");
    }

    if (
      MainhandItem?.includes("bf_bp:") &&
      MainhandItem?.includes("_backpack") &&
      !MainhandItem?.includes("_armor") &&
      !MainhandItem?.includes("_use")
    ) {
      player.addTag("backpack_item");
    } else {
      player.removeTag("backpack_item");
    }

    if (
      (AllBackpacksBallons.includes(itemId) && itemId.includes("ballons")) ||
      itemId == "bf_bp:elytra_backpack_armor"
    ) {
      player.runCommand("effect @s slow_falling 1 1 true");
    }
    if (NewsBackpacksCanFly.includes(itemId)) {
      player.runCommand("effect @s slow_falling 1 1 true");
    }
    if (NewsBackpacksLightSource.includes(itemId)) {
      player.runCommand("fill ~2~-3~2~-3~6~-3 air replace light_block");
      player.runCommand(
        `execute unless block ~~1~ end_portal unless block ~~1~ portal run setblock ~~1~ light_block["block_light_level"=10]`
      );
    }
    if (
      AllBackpacksArmorWithSpecials.includes(itemId) &&
      itemId.includes("wings")
    ) {
      player.runCommand("effect @s fire_resistance 1 1 true");
    }
    player.runCommand(
      `execute if block ~~~ portal at @s[tag=pickedBackpack] as @s[tag=pickedBackpack] run tag @s add portalMSG`
    );
    player.runCommand(
      `execute if block ~~~ end_portal at @s[tag=pickedBackpack] as @s[tag=pickedBackpack] run tag @s add portalMSG`
    );
    if (MainhandItem == "bf_bp:pick_up") {
      if (!player.hasTag("has_picked_item")) {
        player.onScreenDisplay.setActionBar({
          translate: "action.text.bf_bp.text4",
        });
      }
      player.addTag("has_picked_item");
    } else {
      player.removeTag("has_picked_item");
    }

    if (player.hasTag("portalMSG")) {
      player.onScreenDisplay.setActionBar({
        translate: "action.text.bf_bp.text3",
      });
      player.removeTag("portalMSG");
    }

    if (MainhandItem == "bf_bp:specials") {
      if (!player.hasTag("has_picked_item2")) {
        player.onScreenDisplay.setActionBar({
          translate: "action.text.bf_bp.text5",
        });
      }
      player.addTag("has_picked_item2");
    } else {
      player.removeTag("has_picked_item2");
    }

    if (
      AllBackpacksArmorWithSpecials.includes(itemId) &&
      player.isSneaking &&
      !player.hasTag("executeTwo")
    ) {
      if (
        AxolotlWithSpecials.includes(itemId) &&
        player.getDynamicProperty("toggle_1") == 1
      ) {
        player.special_timer++;
      }
      if (
        CreeperWithSpecials.includes(itemId) &&
        player.getDynamicProperty("toggle_2") == 1
      ) {
        player.special_timer++;
      }
      if (
        DragonWingsWithSpecials.includes(itemId) &&
        player.getDynamicProperty("toggle_3") == 1
      ) {
        player.special_timer++;
      }
      if (
        WardenWithSpecials.includes(itemId) &&
        player.getDynamicProperty("toggle_4") == 1
      ) {
        player.special_timer++;
      }
      if (
        WolfWithSpecials.includes(itemId) &&
        player.getDynamicProperty("toggle_5") == 1
      ) {
        player.special_timer++;
      }
      if (
        EndermanWithSpecials.includes(itemId) &&
        player.getDynamicProperty("toggle_6") == 1
      ) {
        player.special_timer++;
      }
      if (player.special_timer > 0 && player.special_timer <= 6) {
        player.runCommand(`title @s actionbar §0■ ■ ■ ■ ■ ■`);
      }
      if (player.special_timer >= 6 && player.special_timer <= 8) {
        player.runCommand(`title @s actionbar ■ §0■ ■ ■ ■ ■`);
      }
      if (player.special_timer >= 8 && player.special_timer <= 8) {
        player.runCommand(`title @s actionbar ■ ■ §0■ ■ ■ ■`);
      }
      if (player.special_timer >= 10 && player.special_timer <= 12) {
        player.runCommand(`title @s actionbar ■ ■ ■ §0■ ■ ■`);
      }
      if (player.special_timer >= 12 && player.special_timer <= 14) {
        player.runCommand(`title @s actionbar ■ ■ ■ ■ §0■ ■`);
      }
      if (player.special_timer >= 14 && player.special_timer <= 16) {
        player.runCommand(`title @s actionbar ■ ■ ■ ■ ■ §0■`);
      }
      if (player.special_timer >= 18) {
        player.runCommand(`title @s actionbar ■ ■ ■ ■ ■ ■`);
      }
      if (player.special_timer >= 19) {
        player.runCommand(`title @s actionbar §a■ ■ ■ ■ ■ ■`);
      }
    }
    if (!player.isSneaking) {
      player.special_timer = 0;
      player.removeTag("executeOne");
    }
    commandsRunInterval.forEach((command) => {
      player.runCommand(`${command}`);
    });

    if (itemId == undefined) {
      player.runCommand(`ride @s evict_riders`);
      if (player.hasTag("epout")) {
        player.runCommand(
          "execute as @s at @s[tag=pickedBackpack] run playsound drop_off_backpack @s ~~~ 0.3"
        );
      }
      player.removeTag("drop_sound");
      player.removeTag("epout");
    } else {
      player.addTag("epout");
    }

    if (
      itemId?.startsWith("bf_bp:") &&
      player.getDynamicProperty("backpack_state") == false
    ) {
      player.runCommand(
        `execute as @s unless entity @e[family=backpack,r=1.5] at @s run replaceitem entity @s slot.armor.chest 0 air 1 0`
      );
    }

    if (
      player.isSleeping &&
      player.getDynamicProperty("backpack_state") == true
    ) {
      player.runCommand(`replaceitem entity @s slot.armor.chest 0 air 1 0`);
    }

    const itemNames = player.dimension.getEntities({
      location: player.location,
      type: "minecraft:item",
    });

    for (let item of itemNames) {
      let itemName = item.getComponent("minecraft:item").itemStack.typeId;
      if (
        itemName?.includes("bf_bp:") &&
        itemName?.includes("_backpack") &&
        itemName?.includes("_armor")
      ) {
        item.remove();
      }
    }

    commandsRunInterval2.forEach((command) => {
      player.runCommand(`${command}`);
    });

    const inventory = player.getComponent("minecraft:inventory").container;
    const entity = player.dimension.getEntities({
      location: player.location,
      families: ["backpack"],
      tags: ["pickingBackpack"],
      excludeTags: ["pickedBackpack"],
      maxDistance: 8,
      closest: 1,
    })[0];
    const entity2 = player.getEntitiesFromViewDirection({ maxDistance: 8 })[0]
      ?.entity;

    if (itemId?.startsWith("bf_bp:") && itemId?.includes("backpack")) {
      const equipedBackpack = player.getDynamicProperty("backpackId");
      const rideEntity = player
        .getComponent("minecraft:rideable")
        .getRiders()[0];
      if (equipedBackpack == undefined) {
        if (rideEntity) {
          player.setDynamicProperty("backpackId", rideEntity.id);
        } else {
          player.setDynamicProperty("backpackId", undefined);
        }
      } else {
        player.setDynamicProperty("backpackId", equipedBackpack);
      }
    }

    for (let slot = 0; slot < inventory.size; slot++) {
      const item = inventory.getItem(slot);

      if (item?.typeId) {
        if (
          item.typeId?.includes("bf_bp:") &&
          item.typeId?.includes("_backpack") &&
          item.typeId?.includes("_armor") &&
          !item.typeId?.includes("_use")
        ) {
          inventory.setItem(slot);
        }
        switch (item.typeId) {
          case "bf_bp:crafting_pick_up_use":
            handleBackpackUse(
              player,
              inventory,
              slot,
              "crafting_backpack",
              "bf_bp:crafting_table"
            );
            break;
          case "bf_bp:furnace_pick_up_use":
            handleBackpackUse(
              player,
              inventory,
              slot,
              "furnace_backpack",
              "furnace"
            );
            break;
          case "bf_bp:enchant_pick_up_use":
            handleBackpackUse(
              player,
              inventory,
              slot,
              "enchant_backpack",
              "enchanting_table"
            );
            break;
          case "bf_bp:alchemy_pick_up_use":
            handleBackpackUse(
              player,
              inventory,
              slot,
              "alchemy_backpack",
              "brewing_stand"
            );
            case "bf_bp:steampunk_pick_up_use":
            handleBackpackUse(
              player,
              inventory,
              slot,
              "steampunk_backpack",
              "blast_furnace"
            );
            break;
          default:
            if (
              backpacksUseId.includes(item.typeId) &&
              !player.hasTag("clearTimer")
            ) {
              clearTimer(player);
              player.addTag("clearTimer");
            }
            break;
        }

        if (entity?.typeId && backpacksId.includes(entity.typeId)) {
          const backpackVariant =
            entity.getComponent("minecraft:variant").value;
          if (backpacksUseId.includes(item.typeId)) {
            const baseTypeId = item.typeId.replace("_armor_use", "");
            const backpackData = backpackNamesMap.get(baseTypeId);
            if (backpackData) {
              setArmorColor(
                player,
                entity,
                backpackData.type,
                backpackData.avaliableColors,
                item.typeId,
                backpackVariant
              );
            }
          }
        }
      }
    }

    function handleBackpackUse(
      player,
      inventory,
      slot,
      backpackType,
      replaceType
    ) {
      inventory.setItem(slot);
      player.runCommand(
        `execute as @e[type=bf_bp:${backpackType},c=1,r=8] at @s run fill ~-4~-4~-4~8~8~8 air replace ${replaceType}`
      );
      player.runCommand(
        `execute as @e[type=bf_bp:${backpackType},c=1,r=8] at @s run event entity @s despawn`
      );
    }

    //player.runCommand(`event entity @e[family=backpack] back_off2`);

    player.runCommand(`tag @e[family=backpack] add executeTwo`);

    if (player.hasTag("executeTwo")) {
      player.cooldown_timer++;
      if (player.cooldown_timer <= 26) {
        player.runCommand(`title @s actionbar §0■ ■ ■ ■ ■ ■`);
      }
      if (player.cooldown_timer >= 26 && player.cooldown_timer <= 52) {
        player.runCommand(`title @s actionbar ■ §0■ ■ ■ ■ ■`);
      }
      if (player.cooldown_timer >= 52 && player.cooldown_timer <= 78) {
        player.runCommand(`title @s actionbar ■ ■ §0■ ■ ■ ■`);
      }
      if (player.cooldown_timer >= 78 && player.cooldown_timer <= 104) {
        player.runCommand(`title @s actionbar ■ ■ ■ §0■ ■ ■`);
      }
      if (player.cooldown_timer >= 104 && player.cooldown_timer <= 130) {
        player.runCommand(`title @s actionbar ■ ■ ■ ■ §0■ ■`);
      }
      if (player.cooldown_timer >= 130 && player.cooldown_timer <= 156) {
        player.runCommand(`title @s actionbar ■ ■ ■ ■ ■ §0■`);
      }
      if (player.cooldown_timer >= 156 && player.cooldown_timer <= 160) {
        player.runCommand(`title @s actionbar ■ ■ ■ ■ ■ ■`);
      }
      if (player.cooldown_timer >= 160) {
        player.runCommand(`title @s actionbar ■ ■ ■ ■ ■ ■`);
        player.removeTag("executeTwo");
      }
    }
    if (!player.hasTag("executeTwo")) {
      player.cooldown_timer = 0;
    }

    player.runCommand(
      `execute at @e[type=bf_bp:sonic_explode] run particle minecraft:sonic_explosion`
    );
    player.runCommand(
      `execute at @e[type=bf_bp:dragon_explode] run particle bf_bp:breath2`
    );
    if (itemId == "bf_bp:turtleshell_backpack_armor") {
      player.runCommand("effect @s water_breathing 1 1 true");
    }
    if (
      AllBackpacksArmorWithSpecials.includes(itemId) &&
      (itemId.includes("ballons") ||
        itemId.includes("jetpack") ||
        itemId.includes("wings"))
    ) {
      player.runCommand("effect @s slow_falling 1 1 true");
    }
    if (itemId == "bf_bp:jetpack_backpack_armor" && player.isJumping) {
      player.runCommand("effect @s slow_falling 1 1 true");
      player.addTag("isFlyingJetpack");
    }

    if (player.isOnGround) {
      player.removeTag("isFlyingJetpack");
    }

    player.runCommand(`gamerule sendcommandfeedback false`);
    player.runCommand(`gamerule doimmediaterespawn false`);

    if (!player.hasTag("isFlyingJetpack")) {
      player.runCommand(`stopsound @s jetpack_sound`);
      player.removeTag("isFlyingJetpackOnce");
    }
    if (
      player.hasTag("isFlyingJetpack") &&
      !player.hasTag("isFlyingJetpackOnce")
    ) {
      player.addTag("isFlyingJetpackOnce");
      flyingJetpackParticle(player);
    }

    const iterator = AllBackpacksId.values();

    for (const value of iterator) {
      const idValues = value;
      if (
        getAllArmorColors(`${idValues}`, itemId) &&
        player.special_timer >= 20 &&
        player.isSneaking &&
        !player.hasTag("executeOne") &&
        !player.hasTag("executeTwo")
      ) {
        backpackSpecialsHabilities(player, `${idValues}`);
      }
    }
  });
}, 1);

const jetpackParticles = {};

system.runInterval(() => {
  Object.keys(jetpackParticles).forEach((key) => {
    const player = jetpackParticles[key];
    if (player.hasTag("isFlyingJetpack")) {
      // player.runCommand(`playsound jetpack_sound @s`);
      player.runCommand(`particle bf_bp:plasma2 ~~-1~`);
    } else {
      delete jetpackParticles[key];
    }
  });
}, 0.2 * 20);

function flyingJetpackParticle(player) {
  jetpackParticles[player.nameTag] = player;
}

const cooldownTeleports = {};

system.runInterval(() => {
  Object.keys(cooldownTeleports).forEach((key) => {
    const player = cooldownTeleports[key];
    if (player.isOnGround && player.hasTag("teleport")) {
      player.runCommand(`playsound mob.shulker.teleport @a[r=4]`);
      player.removeTag("teleport");
    } else {
      delete cooldownTeleports[key];
    }
  });
}, 0.5 * 20);

function cooldownTeleport(player) {
  cooldownTeleports[player.nameTag] = player;
}

function axolotlSound(player) {
  system.runTimeout(() => {
    player.runCommand("playsound backpack_heal_sound @a[r=10] ~~~ 0.15");
    player.dimension
      .getEntities({
        location: player.location,
        maxDistance: 10,
      })
      .forEach((entity) => {
        if (entity.typeId == "minecraft:player") {
          entity.dimension.spawnParticle("bf_bp:heal_emitter", entity.location);
          entity.dimension.spawnParticle("bf_bp:heal_fog", entity.location);
          entity.dimension.spawnParticle("bf_bp:heal_lines", entity.location);
          if (player.hasTag("executeTwo")) {
            axolotlSound(player);
          }
        }
      });
  }, 2 * 20);
}

function clearTimer(player) {
  system.runTimeout(() => {
    const inventory = player.getComponent("minecraft:inventory").container;
    for (let slot = 0; slot < inventory.size; slot++) {
      let item = inventory.getItem(slot);
      if (item?.typeId.endsWith("_armor_use")) {
        inventory.setItem(slot);
      }
    }
    player.removeTag("clearTimer");
  }, 1 * 20);
}

function backpackSpecial(player) {
  system.runTimeout(() => {
    if (player.hasTag("executeTwo")) {
      player.removeTag("executeTwo");
    }
  }, 8 * 20);
}

function shootProjectile(source, projectile, velocity) {
  const { x: pX, y: pY, z: pZ } = source.location;
  const { x: vX, y: vY, z: vZ } = source.getViewDirection();
  const { x: rX, y: rY } = source.getRotation();
  const bullet = source.dimension.spawnEntity(projectile, {
    x: pX + vX,
    y: pY + 1,
    z: pZ + vZ,
  });
  const bs = velocity;

  bullet.setRotation({
    x: rX,
    y: rY,
  });

  bullet.applyImpulse({
    x: vX * bs,
    y: vY * bs,
    z: vZ * bs,
  });
}
const backpackNamesMap = new Map();
for (let backpack of BackpackNames) {
  let { id } = backpack;
  backpackNamesMap.set(id, backpack);
}

function setArmorColor(player, entity, tag, avaliableColors, item, variant) {
  const color = avaliableColors[variant];
  const chestBackpackColor = [
    ``,
    `bf_bp:${tag}_backpack_armor`,
    `bf_bp:red_${tag}_backpack_armor`,
    `bf_bp:yellow_${tag}_backpack_armor`,
    `bf_bp:green_${tag}_backpack_armor`,
    `bf_bp:blue_${tag}_backpack_armor`,
    `bf_bp:pink_${tag}_backpack_armor`,
    `bf_bp:purple_${tag}_backpack_armor`,
    `bf_bp:white_${tag}_backpack_armor`,
    `bf_bp:black_${tag}_backpack_armor`,
    `bf_bp:brown_${tag}_backpack_armor`,

    `bf_bp:gray_${tag}_backpack_armor`,
    `bf_bp:magenta_${tag}_backpack_armor`,
    `bf_bp:cyan_${tag}_backpack_armor`,
    `bf_bp:light_blue_${tag}_backpack_armor`,
    `bf_bp:rainbow_${tag}_backpack_armor`,
    `bf_bp:green_r_${tag}_backpack_armor`,
    `bf_bp:orange_${tag}_backpack_armor`,

    `bf_bp:gold_${tag}_backpack_armor`,

    `bf_bp:blackstone_${tag}_backpack_armor`,
    `bf_bp:exposed_${tag}_backpack_armor`,
    `bf_bp:oxidizied_${tag}_backpack_armor`,
    `bf_bp:rusty_${tag}_backpack_armor`,

    `bf_bp:lightt_${tag}_backpack_armor`,
    `bf_bp:scary_${tag}_backpack_armor`,
    `bf_bp:smile_${tag}_backpack_armor`,

    `bf_bp:enddragon_${tag}_backpack_armor`,

    //flowers
    `bf_bp:flower2_${tag}_backpack_armor`,
    `bf_bp:flower3_${tag}_backpack_armor`,
    `bf_bp:flower4_${tag}_backpack_armor`,
    `bf_bp:flower5_${tag}_backpack_armor`,
    `bf_bp:flower6_${tag}_backpack_armor`,
    `bf_bp:flower7_${tag}_backpack_armor`,
    `bf_bp:flower8_${tag}_backpack_armor`,
    `bf_bp:flower9_${tag}_backpack_armor`,
    `bf_bp:flower10_${tag}_backpack_armor`,
    `bf_bp:flower11_${tag}_backpack_armor`,
    `bf_bp:flower12_${tag}_backpack_armor`,
    `bf_bp:flower13_${tag}_backpack_armor`,
    `bf_bp:flower14_${tag}_backpack_armor`,
    `bf_bp:flower15_${tag}_backpack_armor`,
    `bf_bp:flower16_${tag}_backpack_armor`,
    `bf_bp:flower17_${tag}_backpack_armor`,
  ];

  const backpackColorIndex = chestBackpackColor.findIndex((c) =>
    c.includes(color)
  );

  player.runCommand("playsound pick_up_backpack @s");
  player.onScreenDisplay.setActionBar({
    translate: "action.text.bf_bp.text2",
  });

  player.setDynamicProperty("backpack_state", true);
  player.setDynamicProperty("backpack_name", item.replace("_armor_use", ""));

  player.addTag("pickingBackpack");

  if (tag == "crafting") {
    player.runCommand(
      `execute as @e[type=bf_bp:crafting_backpack,c=1,r=7] at @s run fill ~~-1~~~2~ air replace bf_bp:crafting_table`
    );
  }
  if (tag == "enchant") {
    player.runCommand(
      `execute as @e[type=bf_bp:enchant_backpack,c=1,r=7] at @s run fill ~~-1~~~2~ air replace enchanting_table`
    );
  }
  if (tag == "furnace") {
    player.runCommand(
      `execute as @e[type=bf_bp:furnace_backpack,c=1,r=7] at @s run fill ~~-1~~~2~ air replace furnace`
    );
  }

  const Itemf = player
    .getComponent("minecraft:equippable")
    .getEquipment("Chest")
    ?.clone();
  if (Itemf) {
    player.dimension.spawnItem(Itemf, player.location);
  }

  const itemm = new ItemStack(chestBackpackColor[backpackColorIndex]);

  itemm.lockMode = "slot";

  const playerEquipment = player.getComponent("minecraft:equippable");

  entity.runCommand(
    "ride @s[tag=pickingBackpack,tag=!pickedBackpack] start_riding @p[tag=pickingBackpack]"
  );

  if (entity.typeId.includes("bf_bp:") && entity.typeId.includes("_backpack")) {
    playerEquipment.setEquipment("Chest", itemm);
  }

  const inventory = player.getComponent("minecraft:inventory").container;
  for (let slot = 0; slot < inventory.size; slot++) {
    let itemo = inventory.getItem(slot);

    if (itemo?.typeId == item) {
      inventory.setItem(slot);
    }
  }
}

const commandRack = [
  `tellraw @p[tag=pickedBackpack,tag=pickedBlockBackpack,c=1,r=7] {"rawtext":[{"text":"§cYou can't put that kind of backpack."}]}`,
  `tellraw @p[tag=pickedBackpack,c=1,r=7,rm=3] {"rawtext":[{"text":"§cGet at least 3 blocks away to place your backpack!"}]}`,
  "playsound drop_off_backpack @p[tag=pickedBackpack,tag=!pickedBlockBackpack,c=1,r=3] ~~~ 0.3",
  "execute at @p[tag=pickedBackpack,tag=!pickedBlockBackpack,c=1,r=3] as @s run tag @e[family=backpack,tag=pickedBackpack,c=1,r=3] add onRack",
  `replaceitem entity @p[tag=pickedBackpack,tag=!pickedBlockBackpack,c=1,r=3] slot.armor.chest 0 air 1 0`,
  "execute at @p[tag=pickedBackpack,tag=!pickedBlockBackpack,c=1,r=3] as @s run ride @e[family=backpack,tag=pickedBackpack,tag=!pickedBlockBackpack,tag=onRack,c=1,r=3] start_riding @s",
  "execute at @p[tag=pickedBackpack,tag=!pickedBlockBackpack,c=1,r=3] as @s run event entity @e[family=backpack,tag=pickedBackpack,tag=!pickedBlockBackpack,tag=onRack,c=1,r=3] back_off",
  "tag @p[tag=pickedBackpack,tag=!pickedBlockBackpack,c=1,r=3] remove pickedBackpack",
];

world.afterEvents.dataDrivenEntityTrigger.subscribe((data) => {
  const { eventId: event, entity } = data;
  if (entity.typeId == "bf_bp:tutorial_book") {
    if (event == "flip" || event == "flip_reverse") {
      entity.runCommand(`playsound swipe_book_page_sound @a[r=5]`);
    }
  }
  if (backpacksId.includes(entity.typeId)) {
    if (colorEvents.includes(event)) {
      entity.runCommand(`playsound brush @a[r=6] ~~~ 0.2`);
      entity.dimension.spawnParticle("bf_bp:paint", entity.location);
    }
    if (event == "picking") {
      if (
        entity.typeId == "bf_bp:lantern_backpack" ||
        entity.typeId == "bf_bp:medieval_backpack"
      ) {
        entity.runCommand("fill ~1~-3~1~-1~4~-1 air replace light_block");
      }
      if (entity.typeId == "bf_bp:crafting_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace bf_bp:crafting_table`
        );
      }
      if (entity.typeId == "bf_bp:furnace_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace furnace`
        );
      }
      if (entity.typeId == "bf_bp:enchant_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace enchanting_table`
        );
      }
      entity.runCommand("ride @s stop_riding");

      entity.runCommand("event entity @s back_on");

      entity.runCommand("ride @s start_riding @p[tag=pickingBackpack]");
      entity.runCommand("tag @s remove onRack");
      entity.runCommand("tag @s add picking2Backpack");
      entity.runCommand("tag @s add pickingBackpack");
    }
    if (event == "back_on") {
      entity.runCommand("tag @s add pickingBackpack");
      system.runTimeout(() => {
        if (
          entity.hasTag("pickedBackpack") &&
          entity.hasTag("pickingBackpack") &&
          !entity.hasTag("picking2Backpack")
        ) {
          entity.runCommand("ride @s stop_riding");
          entity.removeTag("picking2Backpack");
        }
      }, 0.35 * 20);
    }
    if (event == "remove") {
      const inventory = entity.getComponent("minecraft:inventory").container;

      for (let slot = 0; slot < inventory.size; slot++) {
        let Item = inventory.getItem(slot)?.clone();
        if (Item) {
          entity.dimension.spawnItem(Item, entity.location);
        }
      }
      if (
        entity.typeId == "bf_bp:lantern_backpack" ||
        entity.typeId == "bf_bp:medieval_backpack"
      ) {
        entity.runCommand("fill ~1~-3~1~-1~4~-1 air replace light_block");
      }
      const itemStack = new ItemStack(entity.typeId, 1);
      entity.dimension.spawnItem(itemStack, entity.location);
      if (entity.typeId == "bf_bp:crafting_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace bf_bp:crafting_table`
        );
      }
      if (entity.typeId == "bf_bp:furnace_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace furnace`
        );
      }
      if (entity.typeId == "bf_bp:enchant_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace enchanting_table`
        );
      }
      if (entity.typeId == "bf_bp:alchemy_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace brewing_stand`
        );
      }
      if (entity.typeId == "bf_bp:steampunk_backpack") {
        entity.runCommand(
          `execute as @s at @s run fill ~~-1~~~2~ air replace blast_furnace`
        );
      }
      entity.remove();
    }
    try {
      if (event == "back_off") {
        entity.runCommand("event entity @s ground");
        entity.runCommand("tag @s remove pickingBackpack");
        entity.runCommand("tag @s remove pickedBackpack");
        entity.runCommand("tag @s add ground");
      }
    } catch (error) {
      return;
    }
  }

  if (
    entity.typeId == "bf_bp:backpack_rack" ||
    entity.typeId == "bf_bp:backpack_rack2"
  ) {
    const player = entity.dimension.getEntities({
      type: "minecraft:player",
      location: entity.location,
      tags: ["hasInt"],
      closest: 1,
      maxDistance: 4,
    })[0];
    if (event == "on_stand") {
      if (!entity.hasTag("rotating")) {
        entity.addTag("rotate0");
        entity.runCommand(
          "execute as @s[tag=rotate0] at @s run tp @s ~~~ facing ~~~1"
        );
        entity.addTag("rotating");
      }
    }
    if (event == "on_stand0") {
      if (entity.hasTag("rotate0")) {
        entity.addTag("rotate1");
        entity.runCommand(
          "execute as @s[tag=rotate1] at @s run tp @s ~~~ facing ~1~~"
        );
        entity.removeTag("rotate0");
      }
    }
    if (event == "on_stand1") {
      if (entity.hasTag("rotate1")) {
        entity.addTag("rotate2");
        entity.runCommand(
          "execute as @s[tag=rotate2] at @s run tp @s ~~~ facing ~~~-1"
        );
        entity.removeTag("rotate1");
      }
    }
    if (event == "on_stand2") {
      if (entity.hasTag("rotate2")) {
        entity.addTag("rotate3");
        entity.runCommand(
          "execute as @s[tag=rotate3] at @s run tp @s ~~~ facing ~-1~~"
        );
        entity.removeTag("rotate2");
      }
    }
    if (event == "on_stand3") {
      if (entity.hasTag("rotate3")) {
        entity.addTag("rotate0");
        entity.runCommand(
          "execute as @s[tag=rotate3] at @s run tp @s ~ ~ ~ 0 ~"
        );
        entity.removeTag("rotate3");
      }
    }
    if (
      event == "on_shift" &&
      !entity.hasTag("haveInteracted") &&
      !player.hasTag("backpack_item")
    ) {
      commandRack.forEach((command) => {
        entity.runCommand(`${command}`);
      });
      player.removeTag("hasInt");
    }
    if (event == "on_shift") {
      player.removeTag("hasInt");
    }
  }
});

const backpacks = {
  "bf_bp:chest_backpack": {},
  "bf_bp:4_chests_backpack": {},
  "bf_bp:armadillo_backpack": {},
  "bf_bp:popcorn_backpack": {},
  "bf_bp:trashcan_backpack": {},
  "bf_bp:aquarium_backpack": {},
  "bf_bp:disco_ball_backpack": {},
  "bf_bp:unicorn_backpack": {},
  "bf_bp:potted_plant_backpack": {},
  "bf_bp:axolotl_backpack": {},
  "bf_bp:alchemy_backpack": {},
  "bf_bp:ballons_backpack": {},
  "bf_bp:barrel_backpack": {},
  "bf_bp:camo_backpack": {},
  "bf_bp:cat_backpack": {},
  "bf_bp:checkerboard_backpack": {},
  "bf_bp:creeper_backpack": {},
  "bf_bp:cute_backpack": {},
  "bf_bp:dark_backpack": {},
  "bf_bp:dragon_wings_backpack": {},
  "bf_bp:crafting_backpack": {},
  "bf_bp:furnace_backpack": {},
  "bf_bp:elytra_backpack": {},
  "bf_bp:chainmail_backpack": {},
  "bf_bp:diamond_backpack": {},
  "bf_bp:leather_backpack": {},
  "bf_bp:gold_backpack": {},
  "bf_bp:iron_backpack": {},
  "bf_bp:netherite_backpack": {},
  "bf_bp:enchant_backpack": {},
  "bf_bp:enderman_backpack": {},
  "bf_bp:speaker_backpack": {},
  "bf_bp:epic_chest_backpack": {},
  "bf_bp:jetpack_backpack": {},
  "bf_bp:magic_ribbon_backpack": {},
  "bf_bp:ninja_backpack": {},
  "bf_bp:rgb_backpack": {},
  "bf_bp:rich_backpack": {},
  "bf_bp:turtleshell_backpack": {},
  "bf_bp:warden_backpack": {},
  "bf_bp:wolf_backpack": {},

  "bf_bp:demon_backpack": {},
  "bf_bp:easter_backpack": {},
  "bf_bp:cauldron_backpack": {},
  "bf_bp:butterfly_backpack": {},
  "bf_bp:heart_backpack": {},
  "bf_bp:lantern_backpack": {},
  "bf_bp:medieval_backpack": {},
  "bf_bp:present_backpack": {},
  "bf_bp:satchel_backpack": {},
  "bf_bp:pumpkin_backpack": {},
  "bf_bp:sheep_backpack": {},
  "bf_bp:snail_backpack": {},
  "bf_bp:steampunk_backpack": {},
  "bf_bp:transport_backpack": {},
  "bf_bp:traveler_backpack": {},
  "bf_bp:wings_backpack": {},
};

world.afterEvents.itemUse.subscribe((data) => {
  let { source: player, itemStack: item } = data;
  const itemChestId = player
    .getComponent("equippable")
    .getEquipment("Chest")?.typeId;

  if (
    (itemChestId == undefined || !itemChestId.startsWith("bf_bp:")) &&
    backpacks[item.typeId]
  ) {
    equipBackpack(player, `${item.typeId}_armor`, `${item.typeId}`);
  }

  if (item.typeId == "bf_bp:specials") {
    MenuConfig(player);
  }

  const itemId = player
    .getComponent("equippable")
    .getEquipment("Chest")?.typeId;

  if (item.typeId == "bf_bp:pick_up") {
    if (itemId?.startsWith("bf_bp:")) {
      const playeer = player.dimension.getPlayers({
        location: player.location,
        maxDistance: 2.5,
        minDistance: 0.001,
      });

      if (playeer.length == 0) {
        if (!player.hasTag("drop_sound") && player.hasTag("pickedBackpack")) {
          player.playSound("drop_off_backpack", { volume: 0.3 });
        }
        player.onScreenDisplay.setActionBar({
          translate: "action.text.bf_bp.text1",
        });
        player.setDynamicProperty("backpack_state", false);
        player.setDynamicProperty("backpack_name", "none");
        player.addTag("drop_sound");
        player.runCommand(`replaceitem entity @s slot.armor.chest 0 air 1 0`);
        player.addTag("drop_sound");
        if (itemId == "bf_bp:crafting_backpack_armor") {
          checkBackpackAction(player, "crafting");
        }
        if (itemId == "bf_bp:enchant_backpack_armor") {
          checkBackpackAction(player, "enchant");
        }
        if (itemId == "bf_bp:furnace_backpack_armor") {
          checkBackpackAction(player, "furnace");
        }
        if (itemId == "bf_bp:alchemy_backpack_armor") {
          checkBackpackAction(player, "brewing_stand");
        }
        if (itemId == "bf_bp:steampunk_backpack_armor") {
          checkBackpackAction(player, "blast_furnace");
        }
        player.runCommand(`ride @s evict_riders`);
        player.runCommand(`ride @s evict_riders`);
        player.removeEffect("slow_falling");
        player.runCommand("tp ~~0.5~");
        player.removeTag("pickedBackpack");
        const entity = player.dimension.getEntities({
          location: player.location,
          families: ["backpack"],
          // tags: ["pickingBackpack", "picking2Backpack", "pickedBackpack"],
          maxDistance: 1.5,
          closest: 1,
        })[0];
        entity?.removeTag("picking2Backpack");
        const backpackLocation = entity?.location;
        let groundY = backpackLocation?.y;
        while (groundY > -64) {
          const blockBelow = player.dimension.getBlock({
            x: backpackLocation.x,
            y: groundY - 1,
            z: backpackLocation.z,
          });
          if (blockBelow && !blockBelow.isAir) {
            groundY = blockBelow.location.y + 1;
            break;
          }
          groundY--;
        }
        entity?.teleport({
          x: backpackLocation.x,
          y: groundY,
          z: backpackLocation.z,
        });
        // player.runCommand(`ride @s evict_riders`);
        // player.runCommand(`ride @s evict_riders`);
      }
    }
  }
  if (item.typeId == "bf_bp:book") {
    player.runCommand(
      `summon bf_bp:tutorial_book ^^0.5^2 facing @s spawn_anim`
    );
    player.runCommand(`playsound open_book_sound @a[r=3]`);
    player.runCommand(`clear @s bf_bp:book 0 1`);
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  const player = data.player;
  const block = data.block;
  const hasBackpack = player.hasTag("pickedBackpack");

  if (hasBackpack && block.typeId == "minecraft:bed") {
    data.cancel = true;

    system.run(() => {
      player.onScreenDisplay.setActionBar({
        translate: "action.text.bf_bp.text_bed_with_backpack",
      });
    });
  }
});

const commands = [
  "execute as @e[family=backpack,c=1,r=2,tag=pickedBackpack] run tp @s ~ ~ ~ 0 ~",
  "setblock ~~0~ air",
  "setblock ~~1~ air",
  "execute as @e[family=backpack,c=1,r=2,tag=pickedBackpack] run tp @e[family=backpack,c=1,r=2,tag=pickedBackpack] ~ ~-1 ~ 0 ~",
];

/**
 *
 * @param {Player} player
 * @param {string} block
 */
function checkBackpackAction(player, block) {
  commands.forEach((command) => {
    player.runCommand(`${command}`);
  });
  player.runCommand(
    `tp @e[family=backpack,c=1,r=2,tag=pickedBackpack] ${Math.round(
      player.location.x
      //Edit here
    )} ${Math.round(player.location.y)} ${Math.round(player.location.z)}`
  );
  player.addTag(`${block}_centerLocation2`);
  summonBlock(player);
}

/**
 *
 * @param {Player} player
 * @param {string} armor
 * @param {string} backpack
 */
function equipBackpack(player, armor, backpack) {
  const Itemf = player
    .getComponent("minecraft:equippable")
    .getEquipment("Chest")
    ?.clone();
  if (Itemf) {
    player.dimension.spawnItem(Itemf, player.location);
  }

  const item = new ItemStack(armor);

  item.lockMode = "slot";

  player.setDynamicProperty("backpack_state", true);
  player.setDynamicProperty("backpack_name", backpack);

  const playerEquipment = player.getComponent("minecraft:equippable");

  player.onScreenDisplay.setActionBar({
    translate: "action.text.bf_bp.text2",
  });

  playerEquipment.setEquipment("Chest", item);

  player.runCommand(`ride @s summon_rider ${backpack}`);
  player.runCommand(`tag @e[type=${backpack},c=1,r=2] add pickedBackpack`);
  player.runCommand(`tag @e[type=${backpack},c=1,r=2] add picking2Backpack`);
  player.addTag("pickedBackpack");
  player.playMusic("pick_up_backpack");
  player.runCommand(`event entity @e[type=${backpack},c=1,r=3] back_on`);
  player.runCommand(`clear @s ${backpack} 0 1`);
}

const filters = [
  {
    type: "bf_bp:crafting_backpack",
    tag: "crafting_centerLocation2",
    setblock: "bf_bp:crafting_table",
    tpYaw: 0,
  },
  {
    type: "bf_bp:furnace_backpack",
    tag: "furnace_centerLocation2",
    setblock: "furnace",
    tpYaw: 180,
  },
  {
    type: "bf_bp:enchant_backpack",
    tag: "enchant_centerLocation2",
    setblock: "enchanting_table",
    tpYaw: 0,
  },
  {
    type: "bf_bp:alchemy_backpack",
    tag: "brewing_stand_centerLocation2",
    setblock: "brewing_stand",
    tpYaw: 0,
  },
  {
    type: "bf_bp:steampunk_backpack",
    tag: "blast_furnace_centerLocation2",
    setblock: "blast_furnace",
    tpYaw: 180,
  },
];

/**
 * @param {Player} player
 * @param {Object} filter
 */
const processFilter = (player, filter) => {
  const entityFilter = {
    type: filter.type,
    location: player.location,
    closest: 1,
    maxDistance: 7,
  };

  world
    .getDimension(player.dimension.id)
    .getEntities(entityFilter)
    .forEach((loc) => {
      if (player.hasTag(filter.tag)) {
        loc.runCommand(`setblock ~~~ ${filter.setblock}`);
        //loc.runCommand(`setblock ~~-1~ grass`);
        player.runCommand("tp ~~~1.2");
        loc.runCommand(`tp ~~1~`);
        loc.runCommand(`execute as @s run tp @s ~ ~ ~ ${filter.tpYaw}`);
        player.removeTag(filter.tag);
      }
    });
};

function summonBlock() {
  system.runTimeout(() => {
    world.getAllPlayers().forEach((player) => {
      filters.forEach((filter) => processFilter(player, filter));
    });
  }, 0.25 * 20);
}

const fillBackpackBlock = {
  "bf_bp:crafting_backpack": {
    command: `fill ~-2~-2~-2~4~4~4 air replace bf_bp:crafting_table`,
  },
  "bf_bp:furnace_backpack": {
    command: `fill ~-2~-2~-2~4~4~4 air replace furnace`,
  },
  "bf_bp:enchant_backpack": {
    command: `fill ~-2~-2~-2~4~4~4 air replace enchanting_table`,
  },
  "bf_bp:alchemy_backpack": {
    command: `fill ~-2~-2~-2~4~4~4 air replace brewing_stand`,
  },
  "bf_bp:steampunk_backpack": {
    command: `fill ~-2~-2~-2~4~4~4 air replace blast_furnace`,
  },
};

world.afterEvents.entityDie.subscribe(
  ({ deadEntity, damageSource: { damagingEntity } }) => {
    const typeId = deadEntity.typeId;
    const Itemf = deadEntity
      .getComponent("minecraft:equippable")
      ?.getEquipment("Chest");
    const playerEquipment = deadEntity?.getComponent("minecraft:equippable");
    if (fillBackpackBlock[typeId]) {
      deadEntity.runCommandAsync(`${fillBackpackBlock[typeId].command}`);
    }
    if (
      deadEntity.typeId == "minecraft:player" &&
      deadEntity.getDynamicProperty("backpack_state") == true &&
      Itemf.typeId?.includes("bf_bp:") &&
      Itemf.typeId?.includes("_backpack") &&
      Itemf.typeId?.includes("_armor")
    ) {
      const entity = deadEntity.dimension.getEntities({
        location: deadEntity.location,
        families: ["backpack"],
        tags: ["pickingBackpack", "picking2Backpack", "pickedBackpack"],
        maxDistance: 1.5,
        closest: 1,
      })[0];
      if (world.gameRules.keepInventory == true) {
        entity.runCommand("tickingarea add ~~~~~~ died true");
        entity.addTag("died");
        deadEntity.setDynamicProperty("diedBackpack", `${entity.id}`);
        deadEntity.addTag("died");
      } else {
        entity.removeTag("picking2Backpack");
        deadEntity.setDynamicProperty("backpack_state", false);
        playerEquipment.setEquipment("Chest");
      }
    }
  }
);

world.afterEvents.playerSpawn.subscribe((event) => {
  const { player } = event;
  const Itemf = player
    .getComponent("minecraft:equippable")
    ?.getEquipment("Chest");
  const playerEquipment = player?.getComponent("minecraft:equippable");
  const equipedBackpack = player.getDynamicProperty("backpackId");
  const backpacks = player.dimension.getEntities({
    families: ["backpack"],
    tags: ["died"],
  });
  for (let backpack of backpacks) {
    if (backpack.id == equipedBackpack) {
      if (player.hasTag("died")) {
        backpack.runCommand(
          `execute as @s[family=backpack,tag=died,tag=!pickedBackpack,c=1] at @s run tickingarea remove ~~~`
        );
        backpack.runCommand(
          `ride @s[family=backpack,tag=died,tag=!pickedBackpack,c=1] start_riding @a[name="${player.name}",tag=died]`
        );
        backpack.removeTag("died");
        player.removeTag("died");
      }
    }
  }
});
