import { world, system } from "@minecraft/server";
import { GOLFBALL_ID, WATER_ID, WATER_FLOW_ID } from "./config.js";
import { BLOCK_IDS } from "./blocks.js";

// Block Effect Configuration for Golf Ball Velocity Modification
const BLOCK_EFFECTS = {
  [BLOCK_IDS.BUNKER]: {
    velocityMultiplier: 0.3, // Reduce velocity to 30% when on sand
    description: "Sand Bunker - Ball slowed down",
    particleEffect: "dss_gep:sand_bunker_particle",
    soundEffect: "brush_completed.suspicious_sand"
  },
  [BLOCK_IDS.BUNKER_SLAB]: {
    velocityMultiplier: 0.3, // Reduce velocity to 30% when on sand
    description: "Sand Bunker - Ball slowed down",
    particleEffect: "dss_gep:sand_bunker_particle",
    soundEffect: "brush_completed.suspicious_sand"
  },
  [WATER_ID]: {
    velocityMultiplier: 1, // Severely reduce velocity in water
    description: "Water Hazard - Ball heavily slowed",
    particleEffect: "dss_gep:water_splash_particle",
    soundEffect: "random.splash"
  },
  [WATER_FLOW_ID]: {
    velocityMultiplier: 1, // Severely reduce velocity in water
    description: "Water Hazard - Ball heavily slowed",
    particleEffect: "dss_gep:water_splash_particle",
    soundEffect: "random.splash"
  },
  [BLOCK_IDS.CHECKERED_GRASS]: {
    velocityMultiplier: 1,
    description: "Landed on Checkerboard Grass",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.CHECKERED_GRASS_SLAB]: {
    velocityMultiplier: 1,
    description: "Landed on Checkerboard Grass",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.ROUGH]: {
    velocityMultiplier: 1,
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.ROUGH_OUTLINED]: {
    velocityMultiplier: 1,
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.ROUGH_SLAB]: {
    velocityMultiplier: 1,
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.ROUGH_GRASS]: {
    velocityMultiplier: 1,
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.GREEN]: {
    velocityMultiplier: 1,
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.GREEN_SLAB]: {
    velocityMultiplier: 1,
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.FAIRWAY_LIGHT]: {
    velocityMultiplier: 1,
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.FAIRWAY_LIGHT_SLAB]: {
    velocityMultiplier: 1, // Increase velocity on ice (slippery)
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.FAIRWAY_MID]: {
    velocityMultiplier: 1, // Increase velocity on ice (slippery)
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  [BLOCK_IDS.FAIRWAY_MID_SLAB]: {
    velocityMultiplier: 1, // Increase velocity on ice (slippery)
    description: "Landed on Rough",
    particleEffect: "dss_gep:land_dust_particle"
  },
  // Add more block effects here as needed
  // "minecraft:water": {
  //   velocityMultiplier: 0.1, // Severely reduce velocity in water
  //   description: "Water Hazard - Ball heavily slowed",
  //   particleEffect: "minecraft:water_splash_particle"
  // },
  // "minecraft:ice": {
  //   velocityMultiplier: 1.2, // Increase velocity on ice (slippery)
  //   description: "Ice - Ball slides faster",
  //   particleEffect: "minecraft:snowflake_particle"
  // }
};

/**
 * Apply velocity-based block effects to golf balls
 */
function applyGolfBallBlockEffects() {
  // Get all golf balls in all dimensions
  for (const dimension of [world.getDimension("overworld"), world.getDimension("nether"), world.getDimension("the_end")]) {
    try {
      const golfballs = dimension.getEntities({ type: GOLFBALL_ID });
      
      for (const golfball of golfballs) {
        if (golfball.hasTag("dss_wedged")) {
            continue;
        }
        try {
          // Get the block directly below the golf ball
          const ballLocation = golfball.location;
          const blockBelow = dimension.getBlock({
            x: Math.floor(ballLocation.x),
            y: Math.floor(ballLocation.y - 0.25), // Check slightly below the ball
            z: Math.floor(ballLocation.z)
          });
          
          if (blockBelow) {
            const blockEffect = BLOCK_EFFECTS[blockBelow.typeId];
            
            if (blockEffect) {
              // Get current velocity
              const currentVelocity = golfball.getVelocity();
              const currentSpeed = Math.sqrt(
                currentVelocity.x * currentVelocity.x + 
                currentVelocity.y * currentVelocity.y + 
                currentVelocity.z * currentVelocity.z
              );
              
              // Only apply effect if ball is moving (avoid affecting stationary balls)
              if (currentSpeed > 0.1) {
                // Check if effect was recently applied to avoid over-application
                const lastEffectTime = golfball.getDynamicProperty("lastVelocityEffect") || 0;
                const currentTime = Date.now();
                
                if (currentTime - lastEffectTime > 100) { // 100ms cooldown
                  // Apply velocity reduction
                  const newVelocity = {
                    x: currentVelocity.x * blockEffect.velocityMultiplier,
                    y: currentVelocity.y * blockEffect.velocityMultiplier,
                    z: currentVelocity.z * blockEffect.velocityMultiplier
                  };
                  
                  // Apply the modified velocity
                  golfball.applyImpulse({
                    x: newVelocity.x - currentVelocity.x,
                    y: newVelocity.y - currentVelocity.y,
                    z: newVelocity.z - currentVelocity.z
                  });
                  
                  // Mark when effect was applied
                  golfball.setDynamicProperty("lastVelocityEffect", currentTime);
                  
                  // Spawn particle effect
                  if (blockEffect.particleEffect) {
                    try {
                      dimension.spawnParticle(blockEffect.particleEffect, {
                        x: ballLocation.x,
                        y: ballLocation.y + 0.1,
                        z: ballLocation.z
                      });
                    } catch (error) {
                      // Silently fail if particle spawn fails
                    }

                    // Play sound effect
                    if (blockEffect.soundEffect) {
                      try {
                        dimension.runCommand(`playsound ${blockEffect.soundEffect} @a ${ballLocation.x} ${ballLocation.y} ${ballLocation.z}`);
                      } catch (error) {
                        // Silently fail if sound play fails
                      }
                    }
                  }
                  
                  // Notify the owner about the effect
                  const owner = golfball.getDynamicProperty("owner");
                  if (owner) {
                    const ownerPlayer = world.getAllPlayers().find(p => p.name === owner);
                    if (ownerPlayer) {
                      // Only show message occasionally to avoid spam
                      const lastNotification = golfball.getDynamicProperty("lastEffectNotification") || 0;
                      
                      if (currentTime - lastNotification > 2000) { // 2 second cooldown for notifications
                        golfball.setDynamicProperty("lastEffectNotification", currentTime);
                      }
                    }
                  }
                }
              }
            }
          } else {
            // console.log("No block effect found for block " + blockBelow.typeId);
            dimension.spawnParticle("dss_gep:land_dust_particle", {
              x: ballLocation.x,
              y: ballLocation.y + 0.1,
              z: ballLocation.z
            });
          }
        } catch (error) {
          // Silently continue if there's an issue with a specific golf ball
          continue;
        }
      }
    } catch (error) {
      // Silently continue if there's an issue with a specific dimension
      continue;
    }
  }
}

// Run the golf ball effect system every tick for responsive velocity modification
system.runInterval(() => {
  applyGolfBallBlockEffects();
}, 1);