/**
 * Map of item IDs to their associated lore descriptions.
 * @type {Map<string, string[]>}
 * @param ["minecraft:apple", ["§2+3 Food", "Red", "Tastey"]]
 */
const loreMap = new Map([["hb_cb:hb_cb_backpack", ["§r§6Armor Evolve Add-On\n§rInteract to spawn the backpack!"]]]);

let previousInventoryState = new Map();

/**
 * Retrieves the current state of a player's inventory.
 *
 * @param {Object} playerContainer - The container representing the player's inventory.
 * @returns {Map<string, number>} A map of item type IDs to their quantities in the inventory.
 */
function getInventoryState(playerContainer) {
  let state = new Map();
  for (let i = 0; i < playerContainer.size; i++) {
    const item = playerContainer.getItem(i);
    if (item) {
      state.set(item.typeId, (state.get(item.typeId) || 0) + 1);
    }
  }
  return state;
}

/**
 * Checks if there has been a change in the player's inventory since the last check.
 *
 * @param {Object} playerContainer - The container representing the player's inventory.
 * @returns {boolean} True if the inventory has changed, false otherwise.
 */
function hasInventoryChanged(playerContainer) {
  const currentState = getInventoryState(playerContainer);
  if (currentState.size !== previousInventoryState.size) return true;

  for (let [id, count] of currentState) {
    if (!previousInventoryState.has(id) || previousInventoryState.get(id) !== count) {
      return true;
    }
  }
  return false;
}

/**
 * Assigns lore descriptions to items in a player's inventory.
 *
 * @param {Object} player - The player whose inventory is to be checked and updated.
 */
export function itemLore(player) {
  const playerContainer = player.getComponent("inventory").container;

  if (!hasInventoryChanged(playerContainer)) return;

  previousInventoryState = getInventoryState(playerContainer);

  for (let i = 0; i < playerContainer.size; i++) {
    const item = playerContainer.getItem(i);
    if (!item) continue;

    const lore = item.getLore();
    if (lore?.length !== 0) continue;

    const itemLore = loreMap.get(item.typeId);
    if (itemLore) {
      item.setLore(itemLore);
      playerContainer.setItem(i, item);
    }
  }
}
