// kubejs/server_scripts/unbreakable_armor.js

const UNBREAKABLE_ARMOR = new Set([
  'ancient_elements:aeonite_helmet',
  'ancient_elements:aeonite_chestplate',
  'ancient_elements:aeonite_leggings',
  'ancient_elements:aeonite_boots',

  'ancient_elements:galactrium_helmet',
  'ancient_elements:galactrium_chestplate',
  'ancient_elements:galactrium_leggings',
  'ancient_elements:galactrium_boots',

  'armageddon_mod:helionite_armor_helmet',
  'armageddon_mod:helionite_armor_chestplate',
  'armageddon_mod:helionite_armor_leggings',
  'armageddon_mod:helionite_armor_boots',

  'lethality:hf_battle_maid_helmet',
  'lethality:hf_battle_maid_chestplate',
  'lethality:hf_battle_maid_leggings',
  'lethality:hf_battle_maid_boots',

  'armageddon_mod:bloody_armor_helmet',
  'armageddon_mod:bloody_armor_chestplate',
  'armageddon_mod:bloody_armor_leggings',
  'armageddon_mod:bloody_armor_boots'
])

const FIXED_MARKER = 'AeoniteUnbreakableFixed'

function makeUnbreakable(item) {
  if (!item || item.isEmpty()) return false

  const id = String(item.id)
  if (!UNBREAKABLE_ARMOR.has(id)) return false

  const nbt = item.nbt || {}

  if (nbt.Unbreakable === 1 || nbt.Unbreakable === true) {
    if (item.damageValue > 0) item.setDamageValue(0)
    return false
  }

  nbt.Unbreakable = 1
  nbt[FIXED_MARKER] = 1

  item.nbt = nbt
  item.setDamageValue(0)
  return true
}

function scanInventory(player) {
  player.inventory.allItems.forEach(item => {
    makeUnbreakable(item)
  })
}

PlayerEvents.loggedIn(event => {
  scanInventory(event.player)
})

ItemEvents.crafted(event => {
  makeUnbreakable(event.item)
})

ItemEvents.pickedUp(event => {
  makeUnbreakable(event.item)
})

// statt inventoryChanged: nur alle 5 Sekunden pro Spieler
PlayerEvents.tick(event => {
  const player = event.player
  if (player.age % 100 !== 0) return

  scanInventory(player)
})