import { EquipmentSlot, ItemStack, EntityComponentTypes, system, world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

export class dh_wa {
  static source = null;

  static armorDetails = [
    { name: "Fire Armor", description: "§d§lSpecial Attack§r§7\nSet monsters around you on fire and leave a fire trail.\n§d§lPassive Effects§r§7\nFire Resistance and Strength effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/fire_armor.png" },
    { name: "Earth Armor", description: "§d§lSpecial Attack§r§7\nCreate an earthquake that knocks back and damages mobs.\n§d§lPassive Effects§r§7\nStrength and Resistance effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/earth_armor.png" },
    { name: "Water Armor", description: "\n§d§lPassive Effects§r§7\nGain strong Regeneration and Strength effects while in water. \n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/water_armor.png" },
    { name: "Ice Armor", description: "§d§lSpecial Attack§r§7\nFreeze mobs in a radius, slowing them and damaging them.\n§d§lPassive Effects§r§7\nSpeed and Resistance effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/ice_armor.png" },
    { name: "Ender Armor", description: "§d§lSpecial Attack§r§7\nTeleport monsters into the sky, dealing fall damage.\n§d§lPassive Effects§r§7\nNight Vision effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/ender_armor.png" },
    { name: "Gravity Armor", description: "§d§lSpecial Attack§r§7\nWhile sneaking, levitate into the sky.\n§d§lPassive Effects§r§7\nSlow Falling and Jump Boost effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/gravity_armor.png" },
    { name: "Lightning Armor", description: "§d§lSpecial Attack§r§7\nSummon lightning strikes on monsters around you.\n§d§lPassive Effects§r§7\nSpeed and Haste effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/lightning_armor.png" },
    { name: "Poison Armor", description: "§d§lSpecial Attack§r§7\nPoison monsters around you and remove any poison effect from yourself.\n§d§lPassive Effects§r§7\nRegeneration and Absorption effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/poison_armor.png" },
    { name: "Void Armor", description: "§d§lSpecial Attack§r§7\nPull in mobs and damage them.\n§d§lPassive Effects§r§7\nNight Vision effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/void_armor.png" },
    { name: "Wind Armor", description: "§d§lSpecial Ability§r§7\nBoost yourself forward.\n§d§lPassive Effects§r§7\nHaste and Jump Boost effect. \n\n§o§cRequires full set to work!", icon: "textures/doghouse/weaponsarmors/items/wind_armor.png" }
  ];

  static weaponDetails = [
    { name: "Fire Sword", description: "§d§lSpecial Attack§r§7\nShoot a fireball projectile that explodes and burns enemies.", icon: "textures/doghouse/weaponsarmors/items/weapons/fire_sword.png" },
    { name: "Earth Sword", description: "§d§lSpecial Attack§r§7\nCreate a line of earth spikes that damage enemies.", icon: "textures/doghouse/weaponsarmors/items/weapons/earth_sword.png" },
    { name: "Water Sword", description: "§d§lSpecial Attack§r§7\nUnleash a wave that pushes and damages enemies.", icon: "textures/doghouse/weaponsarmors/items/weapons/water_sword.png" },
    { name: "Ice Sword", description: "§d§lSpecial Attack§r§7\nCreate a line of ice spikes that slow and damage enemies.", icon: "textures/doghouse/weaponsarmors/items/weapons/ice_sword.png" },
    { name: "Ender Sword", description: "§d§lSpecial Attack§r§7\nTeleport a short distance.", icon: "textures/doghouse/weaponsarmors/items/weapons/ender_sword.png" },
    { name: "Gravity Sword", description: "§d§lSpecial Attack§r§7\nShoot a projectile that levitates its targets.", icon: "textures/doghouse/weaponsarmors/items/weapons/gravity_sword.png" },
    { name: "Lightning Sword", description: "§d§lSpecial Attack§r§7\nSummon a lightning strike that damages enemies.", icon: "textures/doghouse/weaponsarmors/items/weapons/lightning_sword.png" },
    { name: "Poison Sword", description: "§d§lSpecial Attack§r§7\nInflict poison on nearby enemies, causing damage over time.", icon: "textures/doghouse/weaponsarmors/items/weapons/poison_sword.png" },
    { name: "Void Sword", description: "§d§lSpecial Attack§r§7\nCreate a black hole that pulls in and damages enemies.", icon: "textures/doghouse/weaponsarmors/items/weapons/void_sword.png" },
    { name: "Wind Sword", description: "§d§lSpecial Attack§r§7\nSummon a tornado.", icon: "textures/doghouse/weaponsarmors/items/weapons/wind_sword.png" }
  ];

  static armorEffects = {
    earth: [{ type: "resistance", amplifier: 2 }, { type: "strength", amplifier: 1 }],
    fire: [{ type: "fire_resistance", amplifier: 1 }, { type: "strength", amplifier: 2 }],
    water: [{ type: "water_breathing", amplifier: 1 }],
    ice: [{ type: "speed", amplifier: 0 }, { type: "resistance", amplifier: 1 }],
    ender: [{ type: "night_vision", amplifier: 1 }],
    gravity: [{ type: "slow_falling", amplifier: 2 }, { type: "jump_boost", amplifier: 0 }],
    lightning: [{ type: "speed", amplifier: 1 }, { type: "haste", amplifier: 1 }],
    poison: [{ type: "regeneration", amplifier: 0 }, { type: "absorption", amplifier: 1 }],
    void: [{ type: "night_vision", amplifier: 1 }],
    wind: [{ type: "haste", amplifier: 2 }, { type: "jump_boost", amplifier: 1 }]
  };

  static abilityCooldowns = {
    earth: 5000,
    fire: 6000,
    water: 7000,
    ice: 5000,
    ender: 8000,
    gravity: 6000,
    lightning: 5000,
    poison: 7000,
    void: 6000,
    wind: 5000
  };

  static playerArmorStatus = new Map();
  static cooldowns = new Map();
  static sneakState = new Map();

  static swordProperties = {
    "dh_wa:earth_sword": { projectile: "dh_wa:rock.projectile", impulse: 2.5 },
    "dh_wa:ender_sword": { projectile: "dh_wa:ender.projectile", impulse: 3 },
    "dh_wa:water_sword": { projectile: "dh_wa:sea_wave", impulse: 3 },
    "dh_wa:wind_sword": { projectile: "dh_wa:tornado", impulse: 3 },
    "dh_wa:fire_sword": { projectile: "dh_wa:fire_ball", impulse: 2 },
    "dh_wa:ice_sword": { projectile: "dh_wa:freeze.projectile", impulse: 2.5 },
    "dh_wa:poison_sword": { projectile: "dh_wa:poison_ball", impulse: 1.5 },
    "dh_wa:gravity_sword": { projectile: "dh_wa:gravity.projectile", impulse: 2 },
    "dh_wa:lightning_sword": { projectile: "dh_wa:lightning.projectile", impulse: 1.5 },
    "dh_wa:void_sword": { projectile: "dh_wa:void.projectile", impulse: 1 }
  };

  static run() {
    world.afterEvents.itemStartUse.subscribe((event) => {
      const { itemStack, source } = event;
      const swordProps = this.swordProperties[itemStack.typeId];
      if (swordProps) {
        this.projectileSpawn(source, swordProps.projectile, swordProps.impulse);
        this.playSwordEffects(source);
        this.source = source;
      } else if (itemStack?.typeId == "dh_wa:menu") {
        this.showMainMenu(source);
      }
    });

    world.afterEvents.playerSpawn.subscribe((e) => {
      const player = e.player
      if (e.initialSpawn === true && !player.hasTag('spawned')) {
        this.replaceItem(player, 'dh_wa:menu')
        player.addTag('spawned')
      }
    });

    world.afterEvents.entitySpawn.subscribe((event) => {
      const { entity } = event;
      const swordEntry = Object.entries(this.swordProperties).find(
        ([_, props]) => props.projectile === entity.typeId
      );
      if (swordEntry && this.source) {
        const impulse = swordEntry[1].impulse;
        this.applyImpulseToProjectile(entity, impulse);
      }
    });

    system.runInterval(this.applyGravityEffect.bind(this), 0);
    system.runInterval(this.applyPoisonEffect.bind(this), 0);
    system.runInterval(this.applyVoidEffect.bind(this), 0);

    system.runInterval(() => {
      for (const player of world.getPlayers()) {
        const armorSet = this.getArmorSet(player);
        if (armorSet && this.isFullArmorSet(player, armorSet)) {
          this.applyEffects(player, armorSet);
          if (this.playerArmorStatus.get(player.id) !== armorSet) {
            this.playerArmorStatus.set(player.id, armorSet);
          }
        } else if (this.playerArmorStatus.has(player.id)) {
          this.removeEffects(player, this.playerArmorStatus.get(player.id));
          this.playerArmorStatus.delete(player.id);
        }

        // Handle gravity armor sneaking behavior separately
        const wasSneaking = this.sneakState.get(player.id) || false;
        const isSneaking = player.isSneaking;
        if (armorSet === "gravity") {
          if (isSneaking) {
            this.handleGravitySneak(player);  // Start or continue levitation and follow entity
          } else if (wasSneaking && !isSneaking) {
            this.stopGravitySneak(player);    // Stop levitation and despawn entity
          } 
        } else if (armorSet && armorSet === "water" && this.isInWater(player)) {
          this.handleWaterArmorAbility(player);    // Water Ability
        } else if (!wasSneaking && isSneaking && armorSet && armorSet !== "water") {
          // Sneak actions for other armors (non-gravity)
          this.handleSneakAction(player, armorSet);
        }

        this.sneakState.set(player.id, isSneaking);
      }
    }, 1);
  }

  static replaceItem(source, itemToReplace) {
    const equipment = source.getComponent('equippable');
    const item = new ItemStack(itemToReplace);
    equipment.setEquipment(EquipmentSlot.Mainhand, item);
  }

  static handleGravitySneak(player) {
    const entityTag = player.id.slice(0, 5);

    // Check if the attachable entity is already following the player
    const existingEntities = player.dimension.getEntities({
      type: "dh_wa:attachable",
      tags: [entityTag]
    });

    // If no existing entity with this tag, summon a new one
    if (existingEntities.length === 0) {
      player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:gravity_armor`);
      player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${entityTag}"`);
    }

    // Continuously teleport the entity to the player's position while sneaking
    player.runCommandAsync(`tp @e[type=dh_wa:attachable,tag="${entityTag}",c=1] ${player.location.x} ${player.location.y} ${player.location.z}`);

    // Apply the levitation effect while sneaking
    player.runCommand(`effect @s levitation infinite 4 true`);
  }

  static stopGravitySneak(player) {
    const entityTag = player.id.slice(0, 5);

    // Remove the levitation effect when the player stops sneaking
    player.runCommand(`effect @s clear levitation`);

    // Stop following the player and optionally despawn the entity
    player.runCommand(`event entity @e[type=dh_wa:attachable,tag="${entityTag}",c=1] dh_wa:despawn`);
  }



  // Helper function to check if player is in water
  static isInWater(player) {
    const block = player.dimension.getBlock(player.location);
    return block && block.typeId === "minecraft:water";
  }
  // Apply particle effects and positive effects while in water for Water Armor
  static handleWaterArmorAbility(player) {
    const particleTag = player.id.slice(0, 5);

    // Check if the attachable with the particle effect already exists
    const existingEntities = player.dimension.getEntities({
      type: "dh_wa:attachable",
      tags: [particleTag]
    });

    // If no existing entity with this tag, spawn a new one
    if (existingEntities.length === 0) {
      player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:water_armor`);
      player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${particleTag}"`);
    }

    // Ensure the entity follows the player's position
    player.runCommandAsync(`tp @e[type=dh_wa:attachable,tag="${particleTag}",c=1] ${player.location.x} ${player.location.y} ${player.location.z}`);

    // Apply positive effects while the player is in water
    player.runCommand(`effect @s strength 1 2 true`);
    player.runCommand(`effect @s regeneration 1 2 true`);
  }


  static projectileSpawn(player, projectileType, speedMultiplier) {
    const coords = player.getHeadLocation();
    const viewDirection = player.getViewDirection();

    if (projectileType === "dh_wa:sea_wave") {
      // Summon the sea_wave projectile using a command with the facing option
      player.runCommand(`summon dh_wa:sea_wave ~~~ ~~`);

    } else {
      // Standard spawning behavior for other projectiles
      const arrow = player.dimension.spawnEntity(projectileType, {
        x: coords.x + viewDirection.x,
        y: coords.y + viewDirection.y,
        z: coords.z + viewDirection.z
      });

      const projectileComp = arrow.getComponent('minecraft:projectile');

      // Check if the projectile component exists before setting the owner and shooting direction
      if (projectileComp) {
        projectileComp.owner = player;
        projectileComp.shoot(viewDirection); // This sets the initial velocity in the player's view direction
      }

      // Apply impulse directly to control both the direction and speed of the projectile
      arrow.clearVelocity();
      arrow.applyImpulse({
        x: viewDirection.x * speedMultiplier,
        y: viewDirection.y * speedMultiplier,
        z: viewDirection.z * speedMultiplier
      });
    }
  }


  static playSwordEffects(player) {
    player.runCommand(`playsound mob.phantom.flap @s ~~~ 1 3`);
    player.runCommand(`camerashake add @s 0.05 0.2 rotational`);
    player.runCommand(`playanimation @s animation.dh_wa.sword.attack`);
  }

  static applyImpulseToProjectile(projectile, impulse) {
    if (!this.source) return;

    const direction = this.source.getViewDirection();
    if (typeof projectile.applyImpulse === "function") {
      try {
        projectile.applyImpulse({
          x: direction.x * impulse,
          y: direction.y * impulse,
          z: direction.z * impulse
        });
      } catch (error) {
      }
    } else {
    }
  }


  static applyGravityEffect() {
    this.applyEffectsToProjectiles("dh_wa:gravity.projectile", (projectile) => {
      projectile.runCommand(`effect @e[r=4,family=mob] levitation 1 10 false`);
    });
  }

  static applyPoisonEffect() {
    this.applyEffectsToProjectiles("dh_wa:poison_ball", (projectile) => {
      if (projectile.getComponent("minecraft:is_baby")) {
        projectile.runCommand(`effect @e[r=5,family=mob] fatal_poison 1 5 false`);
      }
    });
  }

  static applyVoidEffect() {
    this.applyEffectsToProjectiles("dh_wa:void.projectile", (projectile) => {
      if (!projectile.getComponent("minecraft:is_baby")) {
        projectile.runCommand(`tp @e[r=5,family=mob] @s`);
        projectile.runCommand(`damage @e[r=5,family=mob] 2 magic`);
      }
    });
  }

  static applyEffectsToProjectiles(typeId, effectFn) {
    const projectiles = world.getDimension("overworld").getEntities({ type: typeId });
    for (const projectile of projectiles) {
      effectFn(projectile);
    }
  }
  // Apply multiple effects based on armor set
  static applyEffects(player, armorType) {
    const effects = this.armorEffects[armorType];
    if (effects) {
      for (const effect of effects) {
        player.runCommand(`effect @s ${effect.type} 21 ${effect.amplifier} true`);
      }
    }
  }

  // Reusable function to teleport an entity to the player’s location for a specified duration and interval
  static teleportEntityToPlayer(player, totalTicks, tickRate) {
    let currentTick = 0;
    let entityTag = player.id.slice(1, 6);
    function teleportLoop() {
      if (currentTick < totalTicks) {
        // Teleport the entity with the specified tag to the player’s location
        player.runCommandAsync(`tp @e[type=dh_wa:attachable,tag="${entityTag}",c=1] ~~~`);

        // Increment the tick count
        currentTick++;

        // Schedule the next run at the specified interval
        system.runTimeout(teleportLoop, tickRate);
      } else {
        // After the duration, stop teleporting and optionally remove the entity
        player.runCommand(`event entity @e[type=dh_wa:attachable,tag="${entityTag}",c=1] dh_wa:despawn`);
      }
    }

    // Start the teleportation loop
    teleportLoop();
  }
  // Remove all effects associated with an armor set
  static removeEffects(player, armorType) {
    const effects = this.armorEffects[armorType];
    if (effects) {
      for (const effect of effects) {
        player.runCommand(`effect @s clear ${effect.type}`);
      }
    }
  }

  // Handle sneaking logic based on armor type
  static handleSneakAction(player, armorType) {
    const currentTime = Date.now();
    const lastUsedTime = this.cooldowns.get(player.id)?.[armorType] || 0;
    const cooldownDuration = this.abilityCooldowns[armorType];

    if (currentTime - lastUsedTime >= cooldownDuration) {
      switch (armorType) {
        case "earth":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§aEARTH ABILITY ACTIVATED!`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:earth_armor`);
          player.runCommand(`camerashake add @s 0.01 4 rotational`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 100, 1);
          break;
        case "ender":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§aENDER ABILITY ACTIVATED!`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:ender_armor`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 100, 1);
          break;
        case "ice":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§aICE ABILITY ACTIVATED!`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:ice_armor`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 100, 1);
          break;
        case "wind":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§aWIND ABILITY ACTIVATED!`);
          //SOUNDS !!!
          player.runCommand(`playsound wind_charge.burst @a ~~~ 1 0.75 0.001`);
          player.runCommand(`playsound wind_charge.burst @a ~~~ 0.75 0.25 0.001`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:wind_armor`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:wind_armor`);
          player.runCommand(`summon dh_wa:wind_armor_boost ^^-0.25^-0.5`);
          player.runCommand(`camerashake add @s 0.05 1 rotational`);
          player.runCommand(`effect @s slow_falling 3 1 true`);
          player.runCommand(`effect @s levitation 1 1 true`);
          player.runCommand(`effect @s slowness 1 1 true`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 100, 1);
          break;
        case "void":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§aVOID ABILITY ACTIVATED!`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:void_armor`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 100, 1);
          break;
        case "gravity":
          player.runCommand(`title @s actionbar §l§aGRAVITY ABILITY ACTIVATED!`);
          player.runCommand(`playsound wind_charge.burst @a ~~~ 1 0.75 0.001`);
          player.runCommand(`playsound wind_charge.burst @a ~~~ 0.75 0.25 0.001`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:gravity_armor`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 100, 1);
          break;
        case "fire":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§cFIRE ABILITY ACTIVATED!`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:fire_armor`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 120, 1);
          break;
        case "poison":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§cPOISON ABILITY ACTIVATED!`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:poison_armor`);
          player.removeEffect("minecraft:poison");
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 120, 1);
          break;
        case "lightning":
          player.runCommand(`playanimation @s animation.dh_wa.armor.special`);
          player.runCommand(`title @s actionbar §l§cLIGHTNING ABILITY ACTIVATED!`);
          player.runCommand(`execute at @e[family=monster,type=!player,r=8] run particle dh_wa:lightning_sword_1_small ~~~`);
          player.runCommand(`execute at @e[family=monster,type=!player,r=8] run particle dh_wa:lightning_sword_2_small ~~~`);
          player.runCommand(`execute at @e[family=monster,type=!player,r=8] run particle dh_wa:lightning_sword_3_small ~~~`);
          player.runCommand(`execute at @e[family=monster,type=!player,r=8] run particle dh_wa:lightning_sword_4_small ~~~`);
          player.runCommand(`execute at @e[family=monster,type=!player,r=8] run particle dh_wa:lightning_sword_6_small ~~~`);
          player.runCommand(`execute at @e[family=monster,type=!player,r=8] run particle dh_wa:lightning_sword_7_small ~~~`);
          player.runCommand(`execute at @e[family=monster,type=!player,r=8] run playsound ambient.weather.lightning.impact @a ~~~ 0.2 0.9 0.01`);
          player.runCommand(`damage @e[family=monster,type=!player,r=8] 7 lightning entity @s`);
          player.runCommand(`summon dh_wa:attachable ~ ~ ~ ~~ dh_wa:lightning_armor`);
          player.runCommand(`tag @e[type=dh_wa:attachable,c=1] add "${player.id.slice(1, 6)}"`);
          this.teleportEntityToPlayer(player, 120, 1);
          break;

        // Add additional cases for other armor types as needed

        default:
          break;
      }

      // Update the last-used time for the player's ability
      if (!this.cooldowns.has(player.id)) {
        this.cooldowns.set(player.id, {});
      }
      this.cooldowns.get(player.id)[armorType] = currentTime;
    } else {
      player.runCommand(`title @s actionbar §l§cABILITY ON COOLDOWN`);
    }
  }

  // Check if the player is wearing a full set of the specified armor type
  static isFullArmorSet(player, armorType) {
    const equipComponent = player.getComponent(EntityComponentTypes.Equippable);
    if (!equipComponent) return false;

    const helmet = equipComponent.getEquipment(EquipmentSlot.Head)?.typeId;
    const chestplate = equipComponent.getEquipment(EquipmentSlot.Chest)?.typeId;
    const leggings = equipComponent.getEquipment(EquipmentSlot.Legs)?.typeId;
    const boots = equipComponent.getEquipment(EquipmentSlot.Feet)?.typeId;

    return (
      helmet && helmet.includes(armorType) &&
      chestplate && chestplate.includes(armorType) &&
      leggings && leggings.includes(armorType) &&
      boots && boots.includes(armorType)
    );
  }

  // Determine the type of armor set the player is wearing
  static getArmorSet(player) {
    const equipComponent = player.getComponent(EntityComponentTypes.Equippable);
    if (!equipComponent) return null;

    const helmet = equipComponent.getEquipment(EquipmentSlot.Head)?.typeId;
    const chestplate = equipComponent.getEquipment(EquipmentSlot.Chest)?.typeId;
    const leggings = equipComponent.getEquipment(EquipmentSlot.Legs)?.typeId;
    const boots = equipComponent.getEquipment(EquipmentSlot.Feet)?.typeId;

    if (helmet && chestplate && leggings && boots) {
      for (const type in this.armorEffects) {
        if (
          helmet.includes(type) &&
          chestplate.includes(type) &&
          leggings.includes(type) &&
          boots.includes(type)
        ) {
          return type;
        }
      }
    }
    return null;
  }

  // Main Menu
  static showMainMenu(player) {
    const menuForm = new ActionFormData()
      .title("§lWEAPONS + ARMORS MENU")
      .body(
        "Inside the §c§lWeapons + Armors Menu§r, you can learn all about how to obtain, use, and craft the weapons and armors."
      )
      .button("How to Craft", "textures/doghouse/weaponsarmors/ui/craft.png")
      .button("Weapons", "textures/doghouse/weaponsarmors/ui/weapons.png")
      .button("Armors", "textures/doghouse/weaponsarmors/ui/armors.png");

    menuForm.show(player).then((response) => {
      if (response.canceled) return;

      switch (response.selection) {
        case 0:
          this.showHowToCraftMenu(player);
          break;
        case 1:
          this.showWeaponsMenu(player);
          break;
        case 2:
          this.showArmorsMenu(player);
          break;
      }
    });
  }

  // How to Craft Menu
  static showHowToCraftMenu(player) {
    const craftMenu = new ActionFormData()
      .title("§lHOW TO CRAFT")
      .body("§f§lCRAFTING:§r\n§7To find the crafting recipes for the weapons and armors, click on the recipe book inside the crafting table. Search for the specific sword or armor type to find all relevant recipes.\n\n§f§lCREATIVE:§r\n§7You can also obtain the items by using the creative menu and searching for your specific weapon or armor.")
      .button("Back to Main", "textures/doghouse/weaponsarmors/ui/back.png");

    craftMenu.show(player).then((response) => {
      if (!response.canceled && response.selection === 0) {
        this.showMainMenu(player);
      }
    });
  }

  // How to Use Weapons Menu
  static showHowToUseWeaponsMenu(player) {
    const useMenu = new ActionFormData()
      .title("§lHOW TO USE")
      .body("§d§lHow To Use§r§7\nTo use your special attack on the swords you just simply need to interact with the sword. Find out what special attacks each sword has in the swords menu.")
      .button("Back to Weapons", "textures/doghouse/weaponsarmors/ui/back.png");

    useMenu.show(player).then((response) => {
      if (!response.canceled && response.selection === 0) {
        this.showWeaponsMenu(player);
      }
    });
  }

  // Weapons Menu
  static showWeaponsMenu(player) {
    const weaponsMenu = new ActionFormData()
      .title("§lWEAPONS MENU")
      .button("How to Use", "textures/doghouse/weaponsarmors/ui/info.png")
      .button("Fire Sword", "textures/doghouse/weaponsarmors/items/weapons/fire_sword.png")
      .button("Earth Sword", "textures/doghouse/weaponsarmors/items/weapons/earth_sword.png")
      .button("Water Sword", "textures/doghouse/weaponsarmors/items/weapons/water_sword.png")
      .button("Ice Sword", "textures/doghouse/weaponsarmors/items/weapons/ice_sword.png")
      .button("Ender Sword", "textures/doghouse/weaponsarmors/items/weapons/ender_sword.png")
      .button("Gravity Sword", "textures/doghouse/weaponsarmors/items/weapons/gravity_sword.png")
      .button("Lightning Sword", "textures/doghouse/weaponsarmors/items/weapons/lightning_sword.png")
      .button("Poison Sword", "textures/doghouse/weaponsarmors/items/weapons/poison_sword.png")
      .button("Void Sword", "textures/doghouse/weaponsarmors/items/weapons/void_sword.png")
      .button("Wind Sword", "textures/doghouse/weaponsarmors/items/weapons/wind_sword.png")
      .button("Back to Main", "textures/doghouse/weaponsarmors/ui/back.png");

    weaponsMenu.show(player).then((response) => {
      if (response.canceled) return;

      if (response.selection === 0) {
        this.showHowToUseWeaponsMenu(player);
      } else if (response.selection === 11) { // Last button for "Back to Main"
        this.showMainMenu(player);
      } else if (response.selection - 1 < this.weaponDetails.length) {
        const selectedWeapon = this.weaponDetails[response.selection - 1];
        this.showWeaponDetail(player, selectedWeapon.name, selectedWeapon.description, selectedWeapon.icon);
      }
    });
  }

  // Armors Menu
  static showArmorsMenu(player) {
    const armorsMenu = new ActionFormData()
      .title("§lARMORS MENU")
      .button("How to Use", "textures/doghouse/weaponsarmors/ui/info.png")
      .button("Fire Armor", "textures/doghouse/weaponsarmors/items/fire_armor.png")
      .button("Earth Armor", "textures/doghouse/weaponsarmors/items/earth_armor.png")
      .button("Water Armor", "textures/doghouse/weaponsarmors/items/water_armor.png")
      .button("Ice Armor", "textures/doghouse/weaponsarmors/items/ice_armor.png")
      .button("Ender Armor", "textures/doghouse/weaponsarmors/items/ender_armor.png")
      .button("Gravity Armor", "textures/doghouse/weaponsarmors/items/gravity_armor.png")
      .button("Lightning Armor", "textures/doghouse/weaponsarmors/items/lightning_armor.png")
      .button("Poison Armor", "textures/doghouse/weaponsarmors/items/poison_armor.png")
      .button("Void Armor", "textures/doghouse/weaponsarmors/items/void_armor.png")
      .button("Wind Armor", "textures/doghouse/weaponsarmors/items/wind_armor.png")
      .button("Back to Main", "textures/doghouse/weaponsarmors/ui/back.png");

    armorsMenu.show(player).then((response) => {

      if (response.canceled) return;

      if (response.selection === 0) {
        this.showHowToUseArmorsMenu(player);
      } else if (response.selection === 11) { // Last button for "Back to Main"
        this.showMainMenu(player);
      } else if (response.selection - 1 < this.armorDetails.length) {
        const selectedArmor = this.armorDetails[response.selection - 1];
        this.showArmorDetail(player, selectedArmor.name, selectedArmor.description, selectedArmor.icon);
      }
    });
  }


  // How to Use Armors Menu
  static showHowToUseArmorsMenu(player) {
    const useMenu = new ActionFormData()
      .title("§lHOW TO USE")
      .body("§d§lHow To Use§r§7\nTo use your special attack on the armors, wear a full set of a specific armor type and sneak. Find out what special attacks and effects each armor has in the armors menu.")
      .button("Back to Armors", "textures/doghouse/weaponsarmors/ui/back.png");

    useMenu.show(player).then((response) => {
      if (!response.canceled && response.selection === 0) {
        this.showArmorsMenu(player);
      }
    });
  }

  // Define weapon and armor details
  static showWeaponDetail(player, weaponName, description, iconPath) {
    const detailMenu = new ActionFormData()
      .title(`§l${weaponName}`)
      .body(`§7${description}`)
      .button("Back to Weapons List", "textures/doghouse/weaponsarmors/ui/back.png");

    detailMenu.show(player).then((response) => {
      if (!response.canceled) {
        this.showWeaponsMenu(player);
      }
    });
  }

  static showArmorDetail(player, armorName, description, iconPath) {
    const detailMenu = new ActionFormData()
      .title(`§l${armorName}`)
      .body(`§7${description}`)
      .button("Back to Armors List", "textures/doghouse/weaponsarmors/ui/back.png");

    detailMenu.show(player).then((response) => {
      if (!response.canceled) {
        this.showArmorsMenu(player);
      }
    });
  }
}
