const world = server.world;
import * as server from "@minecraft/server";
import {
  ItemStack,
  EnchantmentType,
  ItemComponentTypes,
} from "@minecraft/server";
import { system } from "@minecraft/server";

let speed = 2;

function calculateForwardVector(yaw, pitch) {
  // Convert angles to radians
  const yawRad = yaw * (Math.PI / 180);
  const pitchRad = pitch * (Math.PI / 180);

  // Calculate movement vector
  const x = -Math.cos(pitchRad) * Math.sin(yawRad) * speed;
  const y = -Math.sin(pitchRad) * speed;
  const z = Math.cos(pitchRad) * Math.cos(yawRad) * speed;

  return { x, y, z };
}

const enchantments = [
  {
    level: 3,
    type: new EnchantmentType("luck_of_the_sea"),
  },
  {
    level: 3,
    type: new EnchantmentType("lure"),
  },
];

export function giveFishingRod(player) {
  const inv = player?.getComponent("minecraft:inventory").container;
  let luckyFishingRod = new ItemStack("fishing_rod");
  luckyFishingRod
    .getComponent("minecraft:enchantable")
    .addEnchantments(enchantments);
  inv.addItem(luckyFishingRod);
}
export function getFishingRodEnchantments(item) {
  return (
    item
      ?.getComponent("minecraft:enchantable")
      ?.hasEnchantment("luck_of_the_sea") ||
    item?.getComponent("minecraft:enchantable")?.hasEnchantment("lure")
  );
}
export function removeFishingRod(player) {
  const inventory = player?.getComponent("minecraft:inventory")?.container;
  for (let i = 0; i < inventory.size; i++) {
    const item = inventory.getItem(i);
    if (getFishingRodEnchantments(item)) {
      inventory.setItem(i, undefined);
    }
  }
}

function toRadians(degrees) {
  return degrees * (Math.PI / 180);
}
function getOffsetRelativeToEntityRotation(boat, offset) {
  const yawRadians = toRadians(boat?.getRotation().y);
  const pitchRadians = toRadians(boat?.getRotation().x);
  const sinYaw = Math.sin(yawRadians);
  const cosYaw = Math.cos(yawRadians);
  const sinPitch = Math.sin(pitchRadians);
  const cosPitch = Math.cos(pitchRadians);
  const deltaX = cosYaw * offset.x - sinYaw * offset.z;
  const deltaZ = sinYaw * offset.x + cosYaw * offset.z;
  const deltaY =
    cosPitch * offset.y +
    sinPitch * Math.sqrt(offset.x * offset.x + offset.z * offset.z);
  return {
    x: boat?.location.x + cosPitch * deltaX,
    y: boat?.location.y + deltaY,
    z: boat?.location.z + cosPitch * deltaZ,
  };
}

export let pirateAbility = false;
export let ghostAbility = false;

const iceBlocks = [
  "minecraft:ice",
  "minecraft:blue_ice",
  "minecraft:packed_ice",
  "minecraft:frosted_ice",
];

const ruinFinderBlocks = ["minecraft:chest"];

const coralBlocks = [
  // Live Coral Blocks
  "minecraft:tube_coral",
  "minecraft:brain_coral",
  "minecraft:bubble_coral",
  "minecraft:fire_coral",
  "minecraft:horn_coral",
  "minecraft:tube_coral_block", // Coral block version
  "minecraft:brain_coral_block", // Coral block version
  "minecraft:bubble_coral_block", // Coral block version
  "minecraft:fire_coral_block", // Coral block version
  "minecraft:horn_coral_block", // Coral block version

  "minecraft:seagrass",
  "minecraft:sea_pickle",
  "minecraft:kelp",

  // Dead Coral Blocks
  "minecraft:dead_tube_coral", // Dead variant
  "minecraft:dead_brain_coral", // Dead variant
  "minecraft:dead_bubble_coral", // Dead variant
  "minecraft:dead_fire_coral", // Dead variant
  "minecraft:dead_horn_coral", // Dead variant
  "minecraft:dead_tube_coral_block", // Dead block version
  "minecraft:dead_brain_coral_block", // Dead block version
  "minecraft:dead_bubble_coral_block", // Dead block version
  "minecraft:dead_fire_coral_block", // Dead block version
  "minecraft:dead_horn_coral_block", // Dead block version

  // Coral Fans
  "minecraft:tube_coral_fan", // Coral fan
  "minecraft:brain_coral_fan", // Coral fan
  "minecraft:bubble_coral_fan", // Coral fan
  "minecraft:fire_coral_fan", // Coral fan
  "minecraft:horn_coral_fan", // Coral fan

  // Coral Fans
  "minecraft:dead_tube_coral_fan", // Coral fan
  "minecraft:dead_brain_coral_fan", // Coral fan
  "minecraft:dead_bubble_coral_fan", // Coral fan
  "minecraft:dead_fire_coral_fan", // Coral fan
  "minecraft:dead_horn_coral_fan", // Coral fan
];

const projectile_list = [
  "minecraft:arrow",
  "minecraft:snowball",
  "minecraft:egg",
  "minecraft:trident",
  "minecraft:fire_charge",
];

function cardinalDirection(boat) {
  const cardinals = ["north", "east", "south", "west"];
  const direction = Math.floor((boat?.getRotation().y + 225) / 90) % 4;
  return cardinals[direction];
}

function getRandomInteger() {
  // Randomly choose whether to return a positive or negative range
  const isPositive = Math.random() < 0.5;

  if (isPositive) {
    return Math.floor(Math.random() * 4) + 3; // Range from 6 to 9
  } else {
    return Math.floor(Math.random() * 4) - 7; // Range from -9 to -6
  }
}

//Boats
export const boats = {
  "pc:speedboat": {
    name: "Speed Boat",
    ability: "Nitro Jump",
    delay: 0, // in seconds
    cooldown: 20, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:speedboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let lookingAt = boat.getViewDirection();
        boat.applyKnockback(lookingAt.x, lookingAt.z, 15, 1);
      });
      world.sendMessage(`${this.ability} activated for Speed Boat!`);
    },
  },
  "pc:algaeboat": {
    name: "Algae Boat",
    ability: "Aqua Collector",
    delay: 3,
    cooldown: 20, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:algaeboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20; //ticks

        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            const riding = player?.getComponent("riding");
            const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
            if (!boatId) return;
            tickCount++;
            const { x, y, z } = boat?.location;
            for (let dy = 0; dy > -50; dy--) {
              for (let dz = -4; dz <= 4; dz++) {
                for (let dx = -4; dx <= 4; dx++) {
                  let blockPosition = {
                    x: x + dx,
                    y: y + dy,
                    z: z + dz,
                  };
                  // Check if the blockName is one of the coral blocks
                  try {
                    let block = dim.getBlock(blockPosition);
                    let blockName = block?.typeId;
                    if (coralBlocks.includes(blockName)) {
                      dim.setBlockType(blockPosition, "minecraft:air");
                      //world.sendMessage(`${blockName}`)
                      let droppeditem = new ItemStack(blockName, 1);
                      const inventory = player?.getComponent(
                        "minecraft:inventory"
                      ).container;
                      inventory.addItem(droppeditem);
                    }
                  } catch (error) {}
                }
              }
            }
            // Display remaining time
            const remainingTime = this.delay - Math.floor(tickCount / 20); // Calculate remaining seconds
            if (boatId === "pc:algaeboat") {
              player.onScreenDisplay.setActionBar(
                `Ability remaining: ${remainingTime} seconds.`
              );
            }

            // Clear the interval when the delay has elapsed
            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });
      world.sendMessage(`${this.ability} activated for Algae Boat!`);
    },
  },
  "pc:armoredboat": {
    name: "Armored Boat",
    delay: 20,
    ability: "Aegis Shield",
    cooldown: 15, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:armoredboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20; //ticks
        let boatPos = boat?.location;

        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            const riding = player?.getComponent("riding");
            const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
            if (!boatId) return;
            if (!boatId) return;
            tickCount++;

            const nearbyEntities = player?.dimension.getEntities({
              location: boatPos,
              maxDistance: 15,
            });

            // Filter for projectiles
            nearbyEntities.forEach((closeProjectile) => {
              if (projectile_list.includes(closeProjectile.typeId)) {
                closeProjectile.clearVelocity();
                closeProjectile.applyImpulse({ x: 0, y: -10, z: 0 }); // Apply downward force to remove projectile
              }
            });

            // Display remaining time
            const remainingTime = this.delay - Math.floor(tickCount / 20); // Calculate remaining seconds
            if (boatId === "pc:armoredboat") {
              player.onScreenDisplay.setActionBar(
                `Ability remaining: ${remainingTime} seconds.`
              );
            }

            // Clear the interval when the delay has elapsed
            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });
      world.sendMessage(`${this.ability} activated for Armored Boat!`);
    },
  },
  "pc:cargoboat": {
    name: "Cargo Boat",
    delay: 0,
    ability: "More Storage",
    cooldown: 0,
  },
  "pc:fireboat": {
    name: "Fire Boat",
    delay: 0,
    ability: "Inferno Blast",
    cooldown: 5, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:fireboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let boatLook = boat.getViewDirection();
        const boatDim = boat.dimension.id;
        let projectileSpawn = getOffsetRelativeToEntityRotation(boat, {
          x: 0,
          y: 2,
          z: 6,
        });
        boat?.playAnimation("animation.fireboat.fire_spread");
        let projectile = world
          .getDimension(boatDim)
          .spawnEntity("minecraft:fireball", projectileSpawn);
        projectile?.clearVelocity();
        projectile?.applyImpulse({
          x: boatLook.x * 2.5,
          y: boatLook.y,
          z: boatLook.z * 2.5,
        });
        let tickCount = 0;
        const abilityWithTimer = system.runInterval(() => {
          tickCount++;
          player?.runCommandAsync(
            `/execute as @e[type=fireball] at @s run fill ~-1 ~-1 ~1 ~1 ~2 ~-1 fire replace air`
          );
          if (tickCount === 7) {
            system.clearRun(abilityWithTimer);
          }
        });
      });
      world.sendMessage(`${this.ability} activated for Fire Boat!`);
    },
  },
"pc:fishingboat": {
  name: "Fishing Boat",
  delay: 60,
  ability: "Fishing Time",
  cooldown: 25, // Cooldown in seconds
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:fishingboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return; // No entities found
    }
    boats.forEach((boat) => {
      let tickCount = 0;
      const delay = this.delay * 20; //ticks
      let boatPos = boat?.location;

      if (tickCount === 0) {
        const abilityWithTimer = system.runInterval(() => {
          const riding = player?.getComponent("riding");
          const boatId = riding?.entityRidingOn?.typeId;
          if (!boatId) return;
          tickCount++;

          if (boatId === "pc:fishingboat") {
            player?.addEffect("water_breathing", 5, {
              amplifier: 8,
              showParticles: false,
            });
            player?.addEffect("resistance", 5, {
              amplifier: 245,
              showParticles: false,
            });

            if (!player?.hasTag("fishingTime")) {
              player?.addTag("fishingTime");

              if (boatId === "pc:fishingboat" && boat && typeof boat.triggerEvent === "function") {
                boat.triggerEvent("pc:set_replacement");
              }

              giveFishingRod(player);
              player?.runCommandAsync(`/camera @s[tag=fishingTime] clear`);
            }
          }

          // Display remaining time
          const remainingTime = this.delay - Math.floor(tickCount / 20);
          if (boatId === "pc:fishingboat") {
            player.onScreenDisplay.setActionBar(
              `Ability remaining: ${remainingTime} seconds.`
            );
          }

          if (tickCount >= delay) {
            system.clearRun(abilityWithTimer);

            if (boatId === "pc:fishingboat" && boat && typeof boat.triggerEvent === "function") {
              boat.triggerEvent("pc:set_normal_boat");
            }

            try {
              player?.removeTag("fishingTime");
            } catch {}

            removeFishingRod(player);
            player?.runCommandAsync(
              `/event entity @e[type=pc:seat_replacement, c=1, r=15] pc:despawns`
            );
          }
        });
      }
    });
    world.sendMessage(`${this.ability} activated for Fishing Boat!`);
  },
},
"pc:flyingboat": {
  name: "Flying Boat",
  delay: 30,
  ability: "Phantom Wings",
  cooldown: 60, // Cooldown in seconds
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:flyingboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return; // No entities found
    }

    boats.forEach((boat) => {
      if (!boat) return;

      let tickCount = 0;
      const delay = this.delay * 20;

      const abilityWithTimer = system.runInterval(() => {
        const riding = player?.getComponent("riding");
        const boatId = riding?.entityRidingOn?.typeId;
        if (!boatId || boatId !== "pc:flyingboat") {
          system.clearRun(abilityWithTimer);
          return;
        }

        tickCount++;

        if (tickCount <= 600) {
          const yaw = player?.getRotation().y;
          const pitch = player?.getRotation().x;
          const movement = calculateForwardVector(yaw, pitch);

          if (boat && typeof boat.runCommandAsync === "function") {
            boat.runCommandAsync(
              `execute as @e[type=pc:flyingboat, c=1, tag=has_rider] rotated as @p if block ~ ~1 ~ air run tp @s ~${movement.x} ~${movement.y} ~${movement.z} ~ ~ true`
            );
          }
        }

        const remainingTime = this.delay - Math.floor(tickCount / 20);
        if (boatId === "pc:flyingboat") {
          player.onScreenDisplay.setActionBar(
            `Ability remaining: ${remainingTime} seconds.`
          );
        }

        if (tickCount >= delay) {
          system.clearRun(abilityWithTimer);
          tickCount = 0;

          if (boat && !boat.hasTag("descentActive")) {
            boat?.addTag("descentActive");
          }

          const descentFunction = system.runInterval(() => {
            const yaw = player?.getRotation().y;
            const pitch = player?.getRotation().x;
            const movement = calculateForwardVector(yaw, pitch);

            if (boat && typeof boat.runCommandAsync === "function") {
              boat.runCommandAsync(
                `execute as @e[type=pc:flyingboat, c=1, tag=descentActive, tag=has_rider] rotated as @p if block ~ ~-1 ~ air run tp @s ~${movement.x} ~-1 ~${movement.z} ~ ~ true`
              );

              boat.runCommandAsync(
                `execute as @e[type=pc:flyingboat, c=1, tag=descentActive, tag=has_rider] rotated as @p unless block ~ ~-1 ~ air run tag @s remove descentActive`
              );
            }

            boat?.addEffect("slow_falling", 20, {
              amplifier: 254,
              showParticles: false,
            });

            if (boat && !boat?.hasTag("descentActive")) {
              system.clearRun(descentFunction);
              boat?.removeEffect("slow_falling");
              boat?.removeTag("descentActive");
            }
          });
        }
      });
    });

    world.sendMessage(`${this.ability} activated for Flying Boat!`);
  },
},
  "pc:ghostboat": {
    name: "Ghost Boat",
    delay: 0,
    ability: "Ghost Barrage",
    cooldown: 10, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:ghostboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        ghostAbility = true;
        let boatPos = boat?.location;
        system.runTimeout(() => {
          player?.removeTag("ghostShoot");
          ghostAbility = false;
        }, 200);
        boat?.playAnimation("animation.ghostboat.right.plotun", {
          blendOutTime: 60,
        });
        world
          ?.getDimension(boat?.dimension?.id)
          ?.playSound("pc.cannon_shot_right", boatPos, {
            pitch: 1,
            volume: 100,
          });
        let yaw = boat?.getRotation().y;
        // Convert yaw to radians
        let yawRadians = yaw * (Math.PI / 180);
        // Calculate the impulse direction based on the boat's yaw (moving to the right)
        let impulseX = Math.cos(yawRadians) * -2;
        let impulseZ = Math.sin(yawRadians) * -2;
        let boatDim = boat.dimension.id;
        let fireballSpawn1 = getOffsetRelativeToEntityRotation(boat, {
          x: -7,
          y: 2,
          z: 1.2,
        });
        let projectile1 = world
          .getDimension(boatDim)
          .spawnEntity("pc:cannonball", fireballSpawn1);
        projectile1?.clearVelocity();
        projectile1?.applyImpulse({
          x: impulseX,
          y: 0,
          z: impulseZ,
        });
        let fireballSpawn2 = getOffsetRelativeToEntityRotation(boat, {
          x: -7,
          y: 2,
          z: -1,
        });
        let projectile2 = world
          .getDimension(boatDim)
          .spawnEntity("pc:cannonball", fireballSpawn2);
        projectile2?.clearVelocity();
        projectile2?.applyImpulse({
          x: impulseX,
          y: 0,
          z: impulseZ,
        });
        let fireballSpawn3 = getOffsetRelativeToEntityRotation(boat, {
          x: -7,
          y: 2,
          z: -3.5,
        });
        let projectile3 = world
          .getDimension(boatDim)
          .spawnEntity("pc:cannonball", fireballSpawn3);
        projectile3?.clearVelocity();
        projectile3?.applyImpulse({
          x: impulseX,
          y: 0,
          z: impulseZ,
        });
      });
      world.sendMessage(`${this.ability} activated for Ghost Boat!`);
    },
  },
"pc:glassbottomboat": {
  name: "Glass-bottom Boat",
  delay: 60,
  ability: "Treasure Finder",
  cooldown: 5,
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:glassbottomboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return; // No entities found
    }

    boats.forEach((boat) => {
      if (!boat) return;
      let tickCount = 0;
      const delay = this.delay * 20; //ticks

      const thisBoat = boat;
      system.runTimeout(() => {
        if (thisBoat && typeof thisBoat.removeTag === "function") {
          try {
            thisBoat.removeTag("active");
          } catch {}
        }
      }, delay);

      if (tickCount === 0) {
        const abilityWithTimer = system.runInterval(() => {
          const riding = player?.getComponent("riding");
          const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
          if (!boatId || boatId !== "pc:glassbottomboat") {
            system.clearRun(abilityWithTimer);
            return;
          }

          tickCount++;
          const { x, y, z } = boat?.location;
          for (let dy = -1; dy > -20; dy--) {
            for (let dz = -5; dz <= 5; dz++) {
              for (let dx = -5; dx <= 5; dx++) {
                let blockPosition = {
                  x: x + dx,
                  y: y + dy,
                  z: z + dz,
                };
                try {
                  let block = dim.getBlock(blockPosition);
                  let blockName = block?.typeId;
                  if (ruinFinderBlocks.includes(blockName)) {
                    world
                      ?.getDimension(boat?.dimension?.id)
                      ?.spawnParticle("pc:ruin_finder", blockPosition);
                  }
                } catch (error) {}
              }
            }
          }

          // Display remaining time
          const remainingTime = this.delay - Math.floor(tickCount / 20);
          if (boatId === "pc:glassbottomboat") {
            player.onScreenDisplay.setActionBar(
              `Ability remaining: ${remainingTime} seconds.`
            );
          }

          if (tickCount >= delay) {
            system.clearRun(abilityWithTimer);
          }
        }, 1);
      }
    });

    world.sendMessage(`${this.ability} activated for Glassbottom Boat!`);
  },
},
  "pc:gravityboat": {
    name: "Gravity Boat",
    delay: 15,
    ability: "Gravity Shift",
    cooldown: 20, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:gravityboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }

      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20; //ticks
        let boatPos = boat?.location;

        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            const riding = player?.getComponent("riding");
            const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
            if (!boatId || boatId !== "pc:gravityboat") {
              system.clearRun(abilityWithTimer);
              return;
            }

            tickCount++;

            const nearbyEntities = player?.dimension.getEntities({
              location: boatPos,
              maxDistance: 25,
              excludeFamilies: ["pc:gravityboat", "player"],
            });

            nearbyEntities.forEach((closeEntity) => {
              closeEntity?.addEffect("levitation", 5, {
                amplifier: 5,
                showParticles: false,
              });
            });

            const remainingTime = this.delay - Math.floor(tickCount / 20);
            if (boatId === "pc:gravityboat") {
              player.onScreenDisplay.setActionBar(
                `Ability remaining: ${remainingTime} seconds.`
              );
            }

            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });

      world.sendMessage(`${this.ability} activated for Gravity Boat!`);
    }
  },
  "pc:harvesterboat": {
    name: "Harvester Boat",
    delay: 15,
    ability: "Harvest Surge",
    cooldown: 20, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:harvesterboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20; //ticks
        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            const riding = player?.getComponent("riding");
            const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
            if (!boatId) return;
            if (!boatId) return;
            tickCount++;
            boat?.runCommandAsync(
              `/execute as @s at @s run tp @e[type=item, r=50] ^^^0.001 facing @s`
            );
            // Display remaining time
            const remainingTime = this.delay - Math.floor(tickCount / 20); // Calculate remaining seconds
            if (boatId === "pc:harvesterboat") {
              player.onScreenDisplay.setActionBar(
                `Ability remaining: ${remainingTime} seconds.`
              );
            }

            // Clear the interval when the delay has elapsed
            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });
      world.sendMessage(`${this.ability} activated for Harvester Boat!`);
    },
  },
"pc:healingboat": {
    name: "Healing Boat",
    delay: 15,
    ability: "Vitality++",
    cooldown: 20, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:healingboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20; //ticks
        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            const riding = player?.getComponent("riding");
            const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
            if (!boatId) return;
            if (!boatId) return;
            tickCount++;
            if (boatId === "pc:healingboat") {
              player?.addEffect("regeneration", 5, {
                amplifier: 8,
                showParticles: false,
              });
            }
            // Display remaining time
            const remainingTime = this.delay - Math.floor(tickCount / 20); // Calculate remaining seconds
            if (boatId === "pc:healingboat") {
              player.onScreenDisplay.setActionBar(
                `Ability remaining: ${remainingTime} seconds.`
              );
            }

            // Clear the interval when the delay has elapsed
            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });
      world.sendMessage(`${this.ability} activated for Healing Boat!`);
    },
  },
"pc:iceboat": {
  name: "Ice Boat",
  delay: 30,
  ability: "Freeze Time",
  cooldown: 5,
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    if (!dim || !playerPos) return;

    const boats = dim.getEntities({
      type: "pc:iceboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) return;

    boats.forEach((boat) => {
      if (!boat || typeof boat.runCommandAsync !== "function") return;

      let tickCount = 0;
      const delay = this.delay * 20;

      const abilityWithTimer = system.runInterval(() => {
        const boatId =
          player?.getComponent("riding")?.entityRidingOn?.typeId;
        if (!boatId || boatId !== "pc:iceboat") {
          system.clearRun(abilityWithTimer);
          return;
        }

        tickCount++;

        try {
          boat.runCommandAsync(`/fill ^-2^^-10 ^2^^-12 ice replace water`);
        } catch {}

        const remainingTime = this.delay - Math.floor(tickCount / 20);
        player.onScreenDisplay.setActionBar(
          `Ability remaining: ${remainingTime} seconds.`
        );

        if (tickCount >= delay) {
          system.clearRun(abilityWithTimer);
        }
      });
    });

    world.sendMessage(`${this.ability} activated for Ice Boat!`);
  },
},
"pc:icebreakerboat": {
  name: "Ice Breaker Boat",
  delay: 15,
  ability: "Ice Breaker",
  cooldown: 20, // Cooldown in seconds
  activate: function (player) {
    try {
      const dim = player?.dimension;
      if (!dim) return;
      const playerPos = player?.location;
      if (!playerPos) return;

      const boats = dim.getEntities({
        type: "pc:icebreakerboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }

      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20;

        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            const riding = player?.getComponent("riding");
            const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
            if (!boatId || boatId !== "pc:icebreakerboat") {
              system.clearRun(abilityWithTimer);
              return;
            }

            tickCount++;

            if (tickCount % 5 !== 0) return; // Pretražuj samo svake 5 ticka!

            const dim = boat?.dimension;
            const { x, y, z } = boat?.location ?? {};
            if (!dim || x === undefined || y === undefined || z === undefined) return;

            for (let dy = -2; dy <= 2; dy++) {
              for (let dz = -12; dz <= 12; dz++) {
                for (let dx = -6; dx <= 6; dx++) {
                  const blockPosition = { x: x + dx, y: y + dy, z: z + dz };
                  try {
                    const block = dim.getBlock(blockPosition);
                    const blockName = block?.typeId;
                    if (iceBlocks.includes(blockName)) {
                      dim.setBlockType(blockPosition, "minecraft:air");
                      const droppeditem = new ItemStack(blockName, 1);
                      const inventory = player?.getComponent("minecraft:inventory")?.container;
                      inventory?.addItem(droppeditem);
                    }
                  } catch {}
                }
              }
            }

            const remainingTime = this.delay - Math.floor(tickCount / 20);
            if (boatId === "pc:icebreakerboat") {
              player.onScreenDisplay.setActionBar(
                `Ability remaining: ${remainingTime} seconds.`
              );
            }

            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });

      world.sendMessage(`${this.ability} activated for Ice Breaker Boat!`);
    } catch {}
  },
},
"pc:lighthouseboat": {
  name: "Lighthouse Boat",
  delay: 60,
  ability: "Guiding Light",
  cooldown: 5, // Cooldown in seconds
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:lighthouseboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return;
    }

    boats.forEach((boat) => {
      if (!boat) return;
      let tickCount = 0;
      const delay = this.delay * 20;

      const thisBoat = boat;
      system.runTimeout(() => {
        if (thisBoat && typeof thisBoat.removeTag === "function") {
          thisBoat.removeTag("active");
        }
      }, delay);

      if (tickCount === 0) {
        const abilityWithTimer = system.runInterval(() => {
          const riding = player?.getComponent("riding");
          const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
          if (!boatId || boatId !== "pc:lighthouseboat") {
            system.clearRun(abilityWithTimer);
            return;
          }

          tickCount++;

          if (boatId === "pc:lighthouseboat") {
            player?.runCommandAsync(`effect @s night_vision infinite 255 true`);
          }

          if (boat && typeof boat.getProperty === "function" && !boat.getProperty("pc:light")) {
            boat.setProperty("pc:light", true);
          }

          const remainingTime = this.delay - Math.floor(tickCount / 20);
          if (boatId === "pc:lighthouseboat") {
            player.onScreenDisplay.setActionBar(
              `Ability remaining: ${remainingTime} seconds.`
            );
          }

          if (tickCount >= delay) {
            system.clearRun(abilityWithTimer);
            if (boat && typeof boat.setProperty === "function") {
              boat.setProperty("pc:light", false);
            }
          }
        });
      }
    });

    world.sendMessage(`${this.ability} activated for Lighthouse Boat!`);
  },
},
  "pc:partyboat": {
    name: "Party Boat",
    delay: 0,
    ability: "Party Party",
    cooldown: 30, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:partyboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        const boatPos = boat?.location;
        const nearbyEntities = dim.getEntities({
          location: boatPos,
          maxDistance: 30,
        });
        world
          ?.getDimension(boat?.dimension?.id)
          ?.spawnParticle("pc:party_rgb_start", boatPos);
        let random = Math.random();
        if (random < 0.33) {
          world
            ?.getDimension(boat?.dimension?.id)
            ?.playSound("pc.track.1", boatPos, { pitch: 1, volume: 4 });
        } else if (random > 0.33 && random < 0.66) {
          world
            ?.getDimension(boat?.dimension?.id)
            ?.playSound("pc.track.2", boatPos, { pitch: 1, volume: 4 });
        } else if (random > 0.66) {
          world
            ?.getDimension(boat?.dimension?.id)
            ?.playSound("pc.track.3", boatPos, { pitch: 1, volume: 4 });
        }
        nearbyEntities.forEach((closeEntity) => {
          closeEntity?.addEffect("jump_boost", 420, {
            amplifier: 3,
            showParticles: false,
          });
        });
      });
      world.sendMessage(`${this.ability} activated for Party Boat!`);
    },
  },
  "pc:pirateboat": {
    name: "Pirate Boat",
    delay: 0,
    ability: "Cannonball Barrage",
    cooldown: 10, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:pirateboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let boatPos = boat?.location;
        pirateAbility = true;
        system.runTimeout(() => {
          player?.removeTag("pirateShoot");
          pirateAbility = false;
        }, 200);

        boat?.playAnimation("animation.pirateboat.right.plotun", {
          blendOutTime: 60,
        });
        let yaw = boat?.getRotation().y;
        world
          ?.getDimension(boat?.dimension?.id)
          ?.playSound("pc.cannon_shot_right", boatPos, {
            pitch: 1,
            volume: 100,
          });
        // Convert yaw to radians
        let yawRadians = yaw * (Math.PI / 180);
        // Calculate the impulse direction based on the boat's yaw (moving to the right)
        let impulseX = Math.cos(yawRadians) * -2;
        let impulseZ = Math.sin(yawRadians) * -2;
        let boatDim = boat.dimension.id;
        let fireballSpawn1 = getOffsetRelativeToEntityRotation(boat, {
          x: -7,
          y: 2,
          z: 1.2,
        });
        let projectile1 = world
          .getDimension(boatDim)
          .spawnEntity("pc:cannonball", fireballSpawn1);
        projectile1?.clearVelocity();
        projectile1?.applyImpulse({
          x: impulseX,
          y: 0,
          z: impulseZ,
        });
        let fireballSpawn2 = getOffsetRelativeToEntityRotation(boat, {
          x: -7,
          y: 2,
          z: -1,
        });
        let projectile2 = world
          .getDimension(boatDim)
          .spawnEntity("pc:cannonball", fireballSpawn2);
        projectile2?.clearVelocity();
        projectile2?.applyImpulse({
          x: impulseX,
          y: 0,
          z: impulseZ,
        });
        let fireballSpawn3 = getOffsetRelativeToEntityRotation(boat, {
          x: -7,
          y: 2,
          z: -3.5,
        });
        let projectile3 = world
          .getDimension(boatDim)
          .spawnEntity("pc:cannonball", fireballSpawn3);
        projectile3?.clearVelocity();
        projectile3?.applyImpulse({
          x: impulseX,
          y: 0,
          z: impulseZ,
        });
      });
      world.sendMessage(`${this.ability} activated for Pirate Boat!`);
    },
  },
  "pc:reinforcedboat": {
    name: "Reinforced Boat",
    delay: 20,
    ability: "Vengeful Detonation",
    cooldown: 25, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      if (!dim) return;
      const playerPos = player?.location;
      if (!playerPos) return;
      const boats = dim?.getEntities({
        type: "pc:reinforcedboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        try {
          if (!boat) return;
          let tickCount = 0;
          const delay = this.delay * 20; //ticks
          system.runTimeout(() => {
            if (!boat) return;
            try {
              boat?.removeTag("active");
            } catch {}
          }, delay);

          if (tickCount === 0) {
            const abilityWithTimer = system.runInterval(() => {
            const riding = player?.getComponent("riding");
            const boatId = riding?.entityRidingOn ? riding.entityRidingOn.typeId : null;
            if (!boatId) return;
              if (!boatId) return;
              tickCount++;
              if (!boat) {
                return;
              }
              if (boat.isValid) {
                if (!boat?.hasTag("active")) {
                  boat?.addTag("active");
                } else {
                  system.clearRun(abilityWithTimer);
                }
              }
              // Display remaining time
              const remainingTime = this.delay - Math.floor(tickCount / 20); // Calculate remaining seconds
              if (boatId === "pc:reinforcedboat") {
                player.onScreenDisplay.setActionBar(
                  `Ability remaining: ${remainingTime} seconds.`
                );
              }

              // Clear the interval when the delay has elapsed
              if (tickCount >= delay) {
                system.clearRun(abilityWithTimer);
              }
            });
          }
        } catch {}
      });
      world.sendMessage(`${this.ability} activated for Reinforced Boat!`);
    },
  },
  "pc:stealthboat": {
    name: "Stealth Boat",
    delay: 15,
    ability: "Silent Shade",
    cooldown: 20, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:stealthboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20; //ticks
        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            const boatId =
              player?.getComponent("riding")?.entityRidingOn?.typeId;
            if (!boatId) return;
            tickCount++;
            try {
              boat?.addEffect("invisibility", 1, {
                amplifier: 254,
                showParticles: false,
              });
            } catch {}
            if (boatId === "pc:stealthboat") {
              player?.addEffect("invisibility", 5, {
                amplifier: 254,
                showParticles: false,
              });
            }
            const remainingTime = this.delay - Math.floor(tickCount / 20); // Calculate remaining seconds
            if (boatId === "pc:stealthboat") {
              player.onScreenDisplay.setActionBar(
                `Ability remaining: ${remainingTime} seconds.`
              );
            }

            // Clear the interval when the delay has elapsed
            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });
      world.sendMessage(`${this.ability} activated for Stealth Boat!`);
    },
  },
"pc:rgbboat": {
  name: "Rgb Boat",
  delay: 60,
  ability: "Speed Boost Aura",
  cooldown: 5, // Cooldown in seconds
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:rgbboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return;
    }

    boats.forEach((boat) => {
      if (!boat) return;
      let tickCount = 0;
      const delay = this.delay * 20;

      const thisBoat = boat;
      system.runTimeout(() => {
        if (thisBoat && typeof thisBoat.removeTag === "function") {
          try {
            thisBoat.removeTag("active");
          } catch {}
        }
      }, delay);

      if (tickCount === 0) {
        const abilityWithTimer = system.runInterval(() => {
          const boatPos = boat?.location;
          if (!boatPos) return;

          dim
            .getEntities({
              location: boatPos,
              excludeFamilies: ["monster", "boats"],
              maxDistance: 30,
            })
            .forEach((entity) => {
              world
                ?.getDimension(entity?.dimension?.id)
                ?.spawnParticle("pc:entity_rgb", entity?.location);

              const hasEffect = entity?.getDynamicProperty("rgb_speed_effect");
              if (!hasEffect) {
                entity.setDynamicProperty("rgb_speed_effect", true);
                entity?.addEffect("speed", delay, {
                  amplifier: 2,
                  showParticles: false,
                });
              }
            });

          const riding = player?.getComponent("riding");
          const boatId = riding?.entityRidingOn?.typeId;
          if (!boatId || boatId !== "pc:rgbboat") {
            system.clearRun(abilityWithTimer);
            return;
          }

          tickCount++;

          const remainingTime = this.delay - Math.floor(tickCount / 20);
          if (boatId === "pc:rgbboat") {
            player.onScreenDisplay.setActionBar(
              `Ability remaining: ${remainingTime} seconds.`
            );
          }

          if (tickCount >= delay) {
            system.clearRun(abilityWithTimer);
          }
        });
      }
    });

    world.sendMessage(`${this.ability} activated for RGB Boat!`);
  },
},
"pc:submarineboat": {
  name: "Submarine Boat",
  delay: 120,
  ability: "Sea Explorer",
  cooldown: 30, // Cooldown in seconds
  activate: function (player) {
    player?.runCommandAsync(`/fog @s push pc:submarine_fog submarine`);
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:submarineboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return; // No entities found
    }

    boats.forEach((boat) => {
      if (!boat) return;
      let tickCount = 0;
      const delay = this.delay * 20; //ticks
      player?.addEffect("water_breathing", delay, {
        amplifier: 254,
        showParticles: false,
      });
      boat?.triggerEvent("pc:set_submarine_on");

      if (tickCount === 0) {
        const abilityWithTimer = system.runInterval(() => {
          const riding = player?.getComponent("riding");
          const boatId = riding?.entityRidingOn?.typeId;
          if (!boatId || boatId !== "pc:submarineboat") {
            system.clearRun(abilityWithTimer);
            return;
          }

          tickCount++;
          const remainingTime = this.delay - Math.floor(tickCount / 20);
          player.onScreenDisplay.setActionBar(
            `Ability remaining: ${remainingTime} seconds.`
          );

          if (tickCount >= delay) {
            system.clearRun(abilityWithTimer);
            try {
              boat?.triggerEvent("pc:set_submarine_off");
            } catch {}

            if (boat && typeof boat.setProperty === "function") {
              boat.setProperty("pc:underwater", false);
            }

            player?.runCommandAsync(`/fog @s remove submarine`);
          }
        });
      }
    });

    world.sendMessage(`${this.ability} activated for Submarine Boat!`);
  },
},
"pc:teleportationboat": {
  name: "Teleportation Boat",
  delay: 0,
  ability: "Phase Jump",
  cooldown: 10, // Cooldown in seconds
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:teleportationboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return; // No entities found
    }
    boats.forEach((boat) => {
      if (!boat) return;

      let teleportationLoc = getOffsetRelativeToEntityRotation(boat, {
        x: 0,
        y: 0,
        z: 40,
      });

      boat?.teleport(teleportationLoc, {
        checkForBlocks: true,
        keepVelocity: true,
      });

      world.sendMessage(
        `${this.ability} activated for Teleportation Boat!`
      );
    });
  },
},
  "pc:tntboat": {
    name: "Tnt Boat",
    delay: 1.5,
    ability: "TNT Strike",
    cooldown: 5, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:tntboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        let tickCount = 0;
        const delay = this.delay * 20; //ticks
        if (tickCount === 0) {
          const abilityWithTimer = system.runInterval(() => {
            tickCount++;
            if (tickCount % 10 === 0) {
              let boatLook = boat.getViewDirection();
              const boatDim = boat.dimension.id;
              let projectileSpawn = getOffsetRelativeToEntityRotation(boat, {
                x: 0,
                y: 3,
                z: 6,
              });
              boat?.playAnimation("animation.tntboat.fire", {
                blendOutTime: 60,
              });
              let projectile = world
                .getDimension(boatDim)
                .spawnEntity("pc:tnt", projectileSpawn);
              projectile?.clearVelocity();
              projectile?.applyImpulse({
                x: boatLook.x * 5,
                y: boatLook.y,
                z: boatLook.z * 5,
              });
            }
            // Clear the interval when the delay has elapsed
            if (tickCount >= delay) {
              system.clearRun(abilityWithTimer);
            }
          });
        }
      });
      world.sendMessage(`${this.ability} activated for TNT Boat!`);
    },
  },
"pc:tradingboat": {
  name: "Trading Boat",
  delay: 60,
  ability: "Trading Master++",
  cooldown: 180, // Cooldown in seconds
  activate: function (player) {
    const dim = player?.dimension;
    const playerPos = player?.location;
    const boats = dim.getEntities({
      type: "pc:tradingboat",
      closest: 1,
      location: playerPos,
    });
    if (!boats || boats.length === 0) {
      return; // No entities found
    }

    boats.forEach((boat) => {
      if (!boat) return;
      let tickCount = 0;
      const delay = this.delay * 20; //ticks

      if (typeof boat.triggerEvent === "function") {
        boat.triggerEvent("pc:set_trading_better");
      }

      if (tickCount === 0) {
        const abilityWithTimer = system.runInterval(() => {
          const riding = player?.getComponent("riding");
          const boatId = riding?.entityRidingOn?.typeId;
          if (!boatId || boatId !== "pc:tradingboat") {
            system.clearRun(abilityWithTimer);
            return;
          }

          tickCount++;
          const remainingTime = this.delay - Math.floor(tickCount / 20);
          player.onScreenDisplay.setActionBar(
            `Ability remaining: ${remainingTime} seconds.`
          );

          if (tickCount >= delay) {
            system.clearRun(abilityWithTimer);
            if (boat && typeof boat.triggerEvent === "function") {
              boat.triggerEvent("pc:set_trading_normal");
            }
          }
        });
      }
    });

    world.sendMessage(`${this.ability} activated for Trading Boat!`);
    system.runTimeout(() => {
      world.sendMessage(
        `§o§7Interact with boat again to open Better Trade shop!`
      );
    }, 10);
  },
},
  "pc:turtleboat": {
    name: "Turtle Boat",
    delay: 0,
    ability: "TNT Barrels",
    cooldown: 10, // Cooldown in seconds
    activate: function (player) {
      const dim = player?.dimension;
      const playerPos = player?.location;
      const boats = dim.getEntities({
        type: "pc:turtleboat",
        closest: 1,
        location: playerPos,
      });
      if (!boats || boats.length === 0) {
        return; // No entities found
      }
      boats.forEach((boat) => {
        if (!boat) return;
        const boatDim = boat.dimension.id;
        let turtleSpawn1 = getOffsetRelativeToEntityRotation(boat, {
          x: 5,
          y: 0,
          z: 8,
        });
        world.getDimension(boatDim).spawnEntity("pc:turtle", turtleSpawn1);
        let turtleSpawn2 = getOffsetRelativeToEntityRotation(boat, {
          x: -5,
          y: 0,
          z: 8,
        });
        world.getDimension(boatDim).spawnEntity("pc:turtle", turtleSpawn2);
      });
      world.sendMessage(`${this.ability} activated for Turtle Boat!`);
    },
  },
};