import { system, ItemStack, BlockPermutation } from "@minecraft/server";
import { toolDurability } from "tool_durability.js";

export const event = {
  sword: {
    async onHitEntity(event) {
      const { attackingEntity, hitEntity } = event;
      
      if (hitEntity.getComponent("minecraft:type_family").hasTypeFamily("inanimate")) return;

      const view = attackingEntity.getViewDirection();
      hitEntity.applyKnockback(-view.x, -view.z, 0.5, 0.8);
      await system.waitTicks(10);
      hitEntity.applyDamage(2);
    },
    onMineBlock(event) {
      const { source } = event;

      toolDurability(source, "Mainhand");
    }
  },
  pickaxe: {
    onMineBlock(event) {
      const { source, block } = event;
      const { x, y, z } = block.center();
      
      toolDurability(source, "Mainhand");

      for (let dx = -1; dx <= 1; dx++) {
        for (let dy = -1; dy <= 1; dy++) {
          for (let dz = -1; dz <= 1; dz++) {
            const pos = { x: x + dx, y: y + dy, z: z + dz };
            const minedBlock = block.dimension.getBlock(pos);
            if (minedBlock && minedBlock.typeId !== "minecraft:air" && minedBlock.typeId !== "minecraft:bedrock") {
              const mineCommand = `loot spawn ${x} ${y} ${z} mine ${minedBlock.location.x} ${minedBlock.location.y} ${minedBlock.location.z} mainhand`;
              try {
                source.runCommand(mineCommand);
              } catch (e) {}
              minedBlock.setType("minecraft:air");
            }
          }
        }
      }
    }
  },
  shovel: {
    // La pala rompe un área 3x3 en el plano horizontal (3 de ancho, 3 de largo, 1 de altura)
    onMineBlock(event) {
      const { source, block } = event;
      const { x, y, z } = block.center();

      toolDurability(source, "Mainhand");

      for (let dx = -1; dx <= 1; dx++) {
        for (let dz = -1; dz <= 1; dz++) {
          const pos = { x: x + dx, y: y, z: z + dz };
          const minedBlock = block.dimension.getBlock(pos);
          const validBlock = [
            "minecraft:dirt",
            "minecraft:grass_block",
            "minecraft:coarse_dirt",
            "minecraft:podzol",
            "minecraft:mycelium",
            "minecraft:rooted_dirt",
            "minecraft:snow",
            "minecraft:clay",
            "minecraft:sand",
            "minecraft:red_sand",
            "minecraft:gravel",
            "minecraft:mud",
            "minecraft:moss_block",
            "minecraft:farmland",
            "minecraft:grass_path",
            "minecraft:suspicious_gravel",
            "minecraft:suspicious_sand"
          ];
          if (validBlock.includes(minedBlock?.typeId)) {
            const mineCommand = `loot spawn ${x} ${y} ${z} mine ${minedBlock.location.x} ${minedBlock.location.y} ${minedBlock.location.z} mainhand`;
            try {
              source.runCommand(mineCommand);
            } catch (e) {}
            minedBlock.setType("minecraft:air");
          }
        }
      }
    }
  },
  axe: {
    // El hacha rompe la cadena vertical de troncos (hacia arriba y hacia abajo)
    onMineBlock(event) {
      const { source: player, block, minedBlockPermutation } = event;
      //const block = player.getBlockFromViewDirection({ maxDistance: 12 })?.block;
      if (!block) {
        return;
      }

      toolDurability(player, "Mainhand");

      const validWood = [
        "minecraft:oak_log",
        "minecraft:spruce_log",
        "minecraft:birch_log",
        "minecraft:jungle_log",
        "minecraft:acacia_log",
        "minecraft:dark_oak_log",
        "minecraft:mangrove_log",
        "minecraft:crimson_stem",
        "minecraft:warped_stem",
        "minecraft:cherry_log",
        "minecraft:pale_oak_log"
      ];
      if (!validWood.includes(minedBlockPermutation.type.id)) {
        return;
      }
      const { x, y, z } = block.center();
      const mineCommand = `loot spawn ${x} ${y} ${z} mine ${block.location.x} ${block.location.y} ${block.location.z} mainhand`;
      try {
        player.runCommand(mineCommand);
      } catch (e) {}
      //block.setType("minecraft:air");
      const baseX = block.location.x;
      const baseZ = block.location.z;
      const MAX_VERTICAL = 100;
      // Procesar troncos hacia arriba
      let currentYUp = block.location.y + 1;
      let countUp = 0;
      while (countUp < MAX_VERTICAL) {
        const posUp = { x: baseX, y: currentYUp, z: baseZ };
        const currentUp = block.dimension.getBlock(posUp);
        if (!currentUp || !validWood.includes(currentUp.typeId)) break;
        const centerUp = currentUp.center();
        const mineCommandUp = `loot spawn ${centerUp.x} ${centerUp.y} ${centerUp.z} mine ${currentUp.location.x} ${currentUp.location.y} ${currentUp.location.z} mainhand`;
        try {
          player.runCommand(mineCommandUp);
        } catch (e) {}
        currentUp.setType("minecraft:air");
        currentYUp++;
        countUp++;
      }
      // Procesar troncos hacia abajo
      let currentYDown = block.location.y - 1;
      let countDown = 0;
      while (countDown < MAX_VERTICAL) {
        const posDown = { x: baseX, y: currentYDown, z: baseZ };
        const currentDown = block.dimension.getBlock(posDown);
        if (!currentDown || !validWood.includes(currentDown.typeId)) break;
        const centerDown = currentDown.center();
        const mineCommandDown = `loot spawn ${centerDown.x} ${centerDown.y} ${centerDown.z} mine ${currentDown.location.x} ${currentDown.location.y} ${currentDown.location.z} mainhand`;
        try {
          player.runCommand(mineCommandDown);
        } catch (e) {}
        currentDown.setType("minecraft:air");
        currentYDown--;
        countDown++;
      }
    }
  },
  hoe: {
    onUseOn(event) {
      const player = event.source;
      const block = event.block;
      const hoeItem = event.itemStack;
      if (!player || !block || !hoeItem) return;
      if (hoeItem.typeId !== "sapphire_meteors:gravity_hoe") return;

      event.cancel = true; // Cancelamos la acción por defecto
      
      // Solo se planta si el bloque es farmland
      if (block.typeId !== "minecraft:farmland") {
        player.runCommandAsync("title @s actionbar §cPlant mode active! Only farmland can be planted.");
        return;
      }
      
      // Verifica que el bloque superior no esté ocupado (si se planta, se usa farmland y el cultivo se coloca en su parte superior)
      const above = block.above();
      if (!above || above.typeId !== "minecraft:air") {
        player.runCommandAsync("title @s actionbar §cCannot plant: crop space is occupied.");
        return;
      }
      
      const inventory = player.getComponent("minecraft:inventory")?.container;
      if (!inventory) return;
      
      // Lista de ítems que consideramos como semillas válidas.
      const seedCandidates = [
        "minecraft:wheat_seeds",
        "minecraft:potato",
        "minecraft:carrot",
        "minecraft:beetroot_seeds",
        "minecraft:melon_seeds",
        "minecraft:pumpkin_seeds"
      ];
      
      // Recorremos el inventario buscando alguna semilla.
      for (let i = 0; i < inventory.size; i++) {
        const seedItem = inventory.getItem(i);
        if (seedItem && seedCandidates.some(id => seedItem.typeId.includes(id))) {
          // Se decrementa la cantidad de la semilla.
          const slot = inventory.getSlot(i);
          if (seedItem.amount > 1) {
            slot.setItem(new ItemStack(seedItem.typeId, seedItem.amount - 1));
          } else {
            slot.setItem(undefined);
          }
          
          let cropBlock = "";
          const cropProps = { growth: 0 };

          if (seedItem.typeId.includes("wheat_seeds")) {
            cropBlock = "minecraft:wheat";
          } else if (seedItem.typeId === "minecraft:potato") {
            cropBlock = "minecraft:potatoes";
          } else if (seedItem.typeId === "minecraft:carrot") {
            cropBlock = "minecraft:carrots";
          } else if (seedItem.typeId.includes("beetroot_seeds")) {
            cropBlock = "minecraft:beetroots";
          } else if (seedItem.typeId.includes("melon_seeds")) {
            cropBlock = "minecraft:melon_stem";
          } else if (seedItem.typeId.includes("pumpkin_seeds")) {
            cropBlock = "minecraft:pumpkin_stem";
          } else {
            cropBlock = seedItem.typeId.replace("_seeds", "");
          }

          try {
            const permutation = BlockPermutation.resolve(cropBlock, cropProps);
            above.setPermutation(permutation);
            player.dimension.playSound("dig.grass", player.location);
            player.runCommandAsync(`title @s actionbar §a${cropBlock.toUpperCase()} planted!`);
          } catch (e) {
            console.error("[HOE] Error planting crop:", e);
          }
          return;
        }
      }
      player.sendMessage("You're out of seeds!");
    },
    onMineBlock(event) {
      const { source } = event;
      
      toolDurability(source, "Mainhand");
    }
  }
};
