import { system, EquipmentSlot, EntityComponentTypes } from "@minecraft/server";

export default function evilJump(player, currentTier) {
  try {
    // Get the item in the player's chest slot
    const equipment = player.getComponent(EntityComponentTypes.Equippable);
    const chestSlotItem = equipment.getEquipment(EquipmentSlot.Chest);

    // Determine the current tier based on the item in the chest slot
    let parsedTier;
    if (chestSlotItem && chestSlotItem.typeId && chestSlotItem.typeId.startsWith("float_ad:evil_")) {
      parsedTier = parseInt(chestSlotItem.typeId.split("_")[2]);
    } else {
      console.error("Player is not wearing a valid chestplate.");
      return;
    }

    // Determine knockback intensity based on parsedTier
    let knockbackIntensity;
    let soundToPlay;
    if (parsedTier > currentTier) {
      knockbackIntensity = 0.5; // Default intensity if parsedTier is less than currentTier
      soundToPlay = "float_ad.chestplate_ability_tier1_evil";
    } else {
      switch (parsedTier) {
        case 1:
          knockbackIntensity = 0.5;
          soundToPlay = "float_ad.chestplate_ability_tier1_evil";
          break;
        case 2:
          knockbackIntensity = 0.7;
          soundToPlay = "float_ad.chestplate_ability_tier2_evil";
          break;
        case 3:
          knockbackIntensity = 1;
          soundToPlay = "float_ad.chestplate_ability_tier3_evil";
          break;
        default:
          knockbackIntensity = 0.5; // Default intensity if tier is not 1, 2, or 3
          soundToPlay = "float_ad.chestplate_ability_tier1_evil";
      }
    }

    // Apply an upward impulse to the player
    player.applyKnockback(0, 0, 0, knockbackIntensity);
    // Play the sound to the player
    player.playSound(soundToPlay);

    // Add the slow falling effect
    player.addEffect("slow_falling", 9999, { amplifier: 1, showParticles: false }); // Use a long duration to ensure effect lasts

    // Monitor when the player lands back on the ground
    const intervalId = system.runInterval(() => {
      const velocity = player.getVelocity();
      if (velocity.y === 0) {
        // Player is on the ground; remove the slow falling effect
        player.removeEffect("slow_falling");
        system.clearRun(intervalId); // Stop checking once the player lands
      }
    }, 1); // Check every tick (20 times per second)

    // Trigger a particle effect for visual feedback
    player.runCommandAsync(
      `particle float_ad:evil_jump ${player.location.x} ${player.location.y + 1} ${player.location.z}`
    );

    // Notify the player
  } catch (error) {
    console.error(`Error in evilJump: ${error}`);
  }
}
