import { world, system, EntityComponentTypes } from "@minecraft/server";
import { playerSettings } from "./player_settings.js";
import { worldSettings } from "./world_settings.js";

// Visual Effects System inspired by Anime Jutsu
export class VisualEffectsManager {
  constructor() {
    this.activeEffects = new Map();
    this.setupEventListeners();
  }

  setupEventListeners() {
    // Listen to player setting changes
    playerSettings.addEventListener("weapon_glow_effects", ({ player, value }) => {
      this.toggleWeaponGlow(player, value);
    });

    playerSettings.addEventListener("soul_altar_particles", ({ player, value }) => {
      this.toggleAltarParticles(player, value);
    });

    playerSettings.addEventListener("companion_outline", ({ player, value }) => {
      this.toggleCompanionOutline(player, value);
    });

    // Listen to world setting changes
    worldSettings.addEventListener("soul_realm_effects", ({ value }) => {
      this.toggleSoulRealmEffects(value);
    });

    worldSettings.addEventListener("particle_density", ({ value }) => {
      this.updateParticleDensity(value);
    });
  }

  // Weapon glow effects
  toggleWeaponGlow(player, enabled) {
    try {
      if (enabled) {
        // Add glowing effect to Soul Hunters weapons
        const mainhand = player.getComponent(EntityComponentTypes.Equippable)?.getEquipment("Mainhand");
        if (mainhand && mainhand.typeId.startsWith("aft_soulhunters:")) {
          player.addTag("soul_weapon_glow");
        }
      } else {
        player.removeTag("soul_weapon_glow");
      }
    } catch (e) {
      // removed debug log
    }
  }

  // Soul altar particle effects
  toggleAltarParticles(player, enabled) {
    const playerId = player.id;
    
    if (enabled) {
      // Start altar particle monitoring
      this.activeEffects.set(`altar_particles_${playerId}`, true);
      this.startAltarParticleMonitoring(player);
    } else {
      // Stop altar particle monitoring
      this.activeEffects.delete(`altar_particles_${playerId}`);
    }
  }

  startAltarParticleMonitoring(player) {
    const playerId = player.id;
    
    const checkAltars = () => {
      if (!this.activeEffects.has(`altar_particles_${playerId}`)) return;
      
      try {
        // Find nearby altars
        const nearbyAltars = player.dimension.getEntities({
          location: player.location,
          maxDistance: 10,
          excludeTypes: ["minecraft:player"]
        }).filter(entity => 
          entity.typeId.includes("aft_soulhunters") && 
          entity.typeId.includes("altar")
        );
        // Schedule next check
        system.runTimeout(checkAltars, 20); // Check every second
      } catch (e) {
        // removed debug log
      }
    };

    checkAltars();
  }

  // Companion outline effects
  toggleCompanionOutline(player, enabled) {
    try {
      const nearbyCompanions = player.dimension.getEntities({
        location: player.location,
        maxDistance: 20,
        excludeTypes: ["minecraft:player"]
      }).filter(entity => 
        entity.typeId.includes("aft_soulhunters") && 
        entity.typeId.includes("companion")
      );

      nearbyCompanions.forEach(companion => {
        if (enabled) {
          companion.addTag("soul_companion_outline");
        } else {
          companion.removeTag("soul_companion_outline");
        }
      });
    } catch (e) {
      // removed debug log
    }
  }

  // Soul realm effects
  toggleSoulRealmEffects(enabled) {
    if (enabled) {
      this.startSoulRealmEffects();
    } else {
      this.stopSoulRealmEffects();
    }
  }

  startSoulRealmEffects() {
    if (this.activeEffects.has("soul_realm_effects")) return;
    
    this.activeEffects.set("soul_realm_effects", true);

    const realmEffects = () => {
      if (!this.activeEffects.has("soul_realm_effects")) return;

      try {
        // Add ambient soul effects around players
        world.getAllPlayers().forEach(player => {
          if (Math.random() < 0.1) { // 10% chance
            try {
            } catch (e) {
              // Particle spawn failed, ignore
            }
          }
        });

        // Schedule next effect cycle
        system.runTimeout(realmEffects, 40); // Every 2 seconds
      } catch (e) {
        // removed debug log
      }
    };

    realmEffects();
  }

  stopSoulRealmEffects() {
    this.activeEffects.delete("soul_realm_effects");
  }

  // Update particle density
  updateParticleDensity(density) {
    const multipliers = {
      "low": 0.5,
      "normal": 1.0,
      "high": 2.0
    };

    this.particleDensityMultiplier = multipliers[density] || 1.0;
  }

  // Camera shake effect (for weapon abilities)
  triggerCameraShake(player, intensity = "normal") {
    const playerIntensity = playerSettings.getPlayerSetting(player, "camera_shake_intensity");
    
    if (playerIntensity === "off") return;

    const shakeMultipliers = {
      "low": 0.5,
      "normal": 1.0,
      "high": 2.0
    };

    const finalIntensity = (shakeMultipliers[intensity] || 1.0) * (shakeMultipliers[playerIntensity] || 1.0);

    try {
      // Use camera shake command if available
      player.runCommand(`camerashake add @s ${finalIntensity} 0.5`);
    } catch (e) {
      // Camera shake not available, alternative effect used (debug removed)
    }
  }

  // Weapon trail effect
  createWeaponTrail(player, weaponType) {
    if (!playerSettings.getPlayerSetting(player, "weapon_glow_effects")) return;

    const trailParticles = {
      "fire_katana": "minecraft:lava_particle",
      "wind_naginata": "minecraft:wind_explosion_particle"
    };

    const particle = trailParticles[weaponType] || "minecraft:crit_particle";

    try {
      for (let i = 0; i < 5; i++) {
        system.runTimeout(() => {
          try {
            const offset = i * 0.2;
            player.dimension.spawnParticle(particle, {
              x: player.location.x + (Math.random() - 0.5) * 2,
              y: player.location.y + 1 + offset,
              z: player.location.z + (Math.random() - 0.5) * 2
            });
          } catch (e) {
            // Particle spawn failed
          }
        }, i * 2);
      }
    } catch (e) {
      // removed debug log
    }
  }
}

// Global instance
export const visualEffects = new VisualEffectsManager();

// Visual Effects System initialized
