import { world, ItemStack, system } from "@minecraft/server";

export class ItemInventoryContents {
  constructor(itemStack) {
    this.itemStack = itemStack;
  }

  getContainer() {
    const dimension = world.getDimension("overworld");
    const location = world.getDynamicProperty("ItemInventoryContents");

    dimension.spawnItem(this.itemStack, location)?.applyDamage(5, {
      cause: "blockExplosion",
    });

    const entities = dimension.getEntities({
      location,
      type: "minecraft:item",
      maxDistance: 1,
    });

    const content = entities
      .map((e) => e.getComponent("item")?.itemStack)
      .filter(Boolean);
    entities.forEach((e) => e.remove());

    return { content };
  }
}

export function checkInventory(player, itemId) {
  const container = player.getComponent("inventory")?.container;

  // Check all slots from 0 to 35 (hotbar first because of numbering)
  for (let i = 0; i <= 35; i++) {
    const item = container.getItem(i);
    if (item?.typeId == itemId) {
      return { item: item, slot: i };
    }
  }
}

export function removeItem(player, itemStack) {
  const container = player.getComponent("minecraft:inventory")?.container;

  if (!container) return;

  for (let i = 0; i < container.size; i++) {
    const item = container.getItem(i);
    if (
      item &&
      item.typeId === itemStack.typeId &&
      item.nameTag === itemStack.nameTag
    ) {
      const newCount = item.amount - 1;

      if (newCount <= 0) {
        container.setItem(i, undefined); // remove entire stack
      } else {
        item.amount = newCount;
        container.setItem(i, item); // update stack count
      }
      break;
    }
  }
}

export function reduceDurability(player, item) {
  if (!player || !item) return;

  const equippable = player.getComponent("equippable");
  const durability = item.getComponent("durability");
  const enchantable = item.getComponent("enchantable");

  if (!equippable || !durability) return;

  const unbreakingLevel = enchantable?.getEnchantment("unbreaking")?.level ?? 0;

  // Vanilla Unbreaking formula
  const shouldTakeDamage = Math.random() < 1 / (unbreakingLevel + 1);
  if (!shouldTakeDamage) return;

  // Apply durability damage
  durability.damage += 1;

  const itemId = item.typeId;

  // If it's a gadget, check contents and show durability message
  if (itemId.startsWith("pb_gat:gadget_")) {
    const contents = new ItemInventoryContents(item).getContainer().content;
    if (contents.length > 0) {
      const current = durability.maxDurability - durability.damage;
      const max = durability.maxDurability;
      const gadgetName = formatGadgetName(itemId);
      player.sendMessage(`§7${gadgetName} Durability: §f${current} / ${max}`);
    }
  }

  // Handle break logic
  if (durability.damage >= durability.maxDurability) {
    player.playSound("random.break", {
      pitch: 1,
      location: player.location,
      volume: 1,
    });

    if (itemId.startsWith("pb_gat:gadget_")) {
      const contents = new ItemInventoryContents(item).getContainer().content;
      if (contents.length > 0) {
        equippable.setEquipment("Mainhand", contents[0]);
      } else {
        equippable.setEquipment("Mainhand", new ItemStack("minecraft:air"));
      }
    } else {
      equippable.setEquipment("Mainhand", new ItemStack("minecraft:air"));
    }
  } else {
    // Just update the item in the player's hand
    equippable.setEquipment("Mainhand", item);
  }
}
function formatGadgetName(itemId) {
  // Remove prefix
  let namePart = itemId.replace("pb_gat:gadget_", "");
  // Split by underscore
  let words = namePart.split("_");
  // Capitalize each word
  let capitalizedWords = words.map(
    (w) => w.charAt(0).toUpperCase() + w.slice(1)
  );
  // Join with spaces
  return capitalizedWords.join(" ");
}
