import { system, world } from "@minecraft/server";
import { combinedMobs } from "../variables";

export default function evilShieldAbility(player, currentTier) {
  try {
    let intervalId;

    const startShield = () => {
      player.addEffect("resistance", 200, { amplifier: 3, showParticles: false });

      let timer = 0;

      // Determine knockback intensity based on currentTier
      let knockbackIntensity;
      switch (currentTier) {
        case 1:
          knockbackIntensity = 0.3;
          break;
        case 2:
          knockbackIntensity = 0.5;
          break;
        case 3:
          knockbackIntensity = 0.7;
          break;
        default:
          knockbackIntensity = 0.3; // Default intensity if tier is not 1, 2, or 3
      }

      // Play sound
      player.playSound("float_ad.shield_ability_evil");
      // Fire particle immediately
      player.runCommandAsync(
        `particle float_ad:evil_bubble ${player.location.x} ${player.location.y + 1} ${player.location.z}`
      );

      intervalId = system.runInterval(() => {
        if (!player.isSneaking) {
          stopShield();
          return;
        }

        timer++;

        if (timer % 20 === 0) {
          // Fire particles once a second (20 ticks)
          player.runCommandAsync(
            `particle float_ad:evil_bubble ${player.location.x} ${player.location.y + 1} ${player.location.z}`
          );
        }

        const entities = world.getDimension(player.dimension.id).getEntities({
          location: player.location,
          radius: 3,
          excludeTypes: ["player"],
        });

        for (const entity of entities) {
          if (combinedMobs.includes(entity.typeId)) {
            const dx = entity.location.x - player.location.x;
            const dz = entity.location.z - player.location.z;
            const distanceSquared = dx * dx + dz * dz;

            if (distanceSquared <= 9) {
              const magnitude = Math.sqrt(distanceSquared);

              if (magnitude > 0) {
                const horizontalKnockback = knockbackIntensity;
                const verticalKnockback = 0.1;

                entity.applyKnockback(
                  (dx / magnitude) * horizontalKnockback,
                  verticalKnockback,
                  (dz / magnitude) * horizontalKnockback,
                  0.5
                );
              }
            }
          }
        }
      }, 1);
    };

    const stopShield = () => {
      player.removeEffect("resistance");
      if (intervalId) {
        system.clearRun(intervalId);
      }
    };

    if (currentTier > 0) {
      startShield();
    } else {
      stopShield();
    }
  } catch (error) {
    console.error(`Error in evilShieldAbility: ${error}`);
  }
}
