import { system } from "@minecraft/server";
import { ItemInventoryContents } from "../utilities.js";

const GROWABLE_CROPS = [
  "minecraft:wheat",
  "minecraft:carrots",
  "minecraft:potatoes",
  "minecraft:beetroot",
  "minecraft:nether_wart",
  "minecraft:melon_stem",
  "minecraft:pumpkin_stem",
  "minecraft:cocoa",
  "minecraft:bamboo",
];

export function wateringCan(player, item, event) {
  const contents =
    new ItemInventoryContents(item).getContainer()?.content ?? [];

  const hasReach = contents.some(
    (stack) => stack?.typeId === "pb_gat:orb_reach"
  );
  const hasSpeed = contents.some(
    (stack) => stack?.typeId === "pb_gat:orb_speed"
  );

  const dimension = player.dimension;
  const center = event.block.location;

  // 🎵 Play watering sound
  player.playSound("liquid.water", { pitch: 1, volume: 1.8 });
  player.playSound("ambient.weather.rain", { pitch: 1.3, volume: 1.8 });

  // ✨ Area particle
  dimension.spawnParticle("pb_gat:watering_can_splash", {
    x: center.x + 0.5,
    y: center.y + 0.8,
    z: center.z + 0.5,
  });

  const radius = hasReach ? 2 : 1;
  const targetLocations = [];

  // 🌾 Expand to include Y+1 and Y-1
  for (let dy = -1; dy <= 1; dy++) {
    for (let dx = -radius; dx <= radius; dx++) {
      for (let dz = -radius; dz <= radius; dz++) {
        targetLocations.push({
          x: center.x + dx,
          y: center.y + dy,
          z: center.z + dz,
        });
      }
    }
  }

  system.run(() => {
    for (const loc of targetLocations) {
      const block = dimension.getBlock(loc);
      if (!block) continue;

      if (!GROWABLE_CROPS.includes(block.typeId)) continue;

      const growthStage = block.permutation.getState("growth");
      if (growthStage === undefined) continue;

      const maxGrowth = getMaxGrowth(block.typeId);
      if (growthStage >= maxGrowth) continue;

      let newGrowth = growthStage;

      if (Math.random() < 0.33 && newGrowth < maxGrowth) {
        newGrowth++;
      }

      if (hasSpeed && Math.random() < 0.33 && newGrowth < maxGrowth) {
        newGrowth++;
      }

      newGrowth = Math.min(newGrowth, maxGrowth);

      if (newGrowth > growthStage) {
        // Use a timeout for particle and delayed growth
        system.runTimeout(() => {
          // Re-fetch block reference to avoid stale object issues
          const targetBlock = dimension.getBlock(loc);
          if (!targetBlock || targetBlock.typeId !== block.typeId) return;

          // Apply new growth stage
          const updatedGrowth = targetBlock.permutation.getState("growth");
          if (updatedGrowth !== undefined && updatedGrowth < maxGrowth) {
            // 🌱 Growth particles
            dimension.spawnParticle("minecraft:crop_growth_emitter", {
              x: loc.x + 0.5,
              y: loc.y + 0.2,
              z: loc.z + 0.5,
            });
            const newPermutation = targetBlock.permutation.withState(
              "growth",
              newGrowth
            );
            targetBlock.setPermutation(newPermutation);
          }
        }, 10);
      }
    }
  });
}

function getMaxGrowth(typeId) {
  switch (typeId) {
    case "minecraft:wheat":
    case "minecraft:carrots":
    case "minecraft:potatoes":
    case "minecraft:beetroots":
      return 7;
    case "minecraft:nether_wart":
      return 3;
    case "minecraft:melon_stem":
    case "minecraft:pumpkin_stem":
      return 7;
    case "minecraft:cocoa":
      return 2;
    case "minecraft:sweet_berry_bush":
      return 3;
    case "minecraft:bamboo":
      return 1;
    default:
      return 7;
  }
}
