// Priority: 1
/**
 * @file        non_recipe_stuffs.js
 * @description Miscellaneous server-side event fixes:
 *                - Opolis Utilities death stone → Tombstone grave key swap on respawn
 *                - Enigmatic Delicacy bush fruit fix on right-click
 *                - Lava bucket condenser (filling / emptying mode toggling)
 * @copyright   KnightDexx's Modded Minecraft World | ModernGamingWorld | GeekTechMedia
 * @author      @Cyn-SolveroftheAbsoluteGremlins on Discord
 */

// ---------------------------------------------------------------------------
// Opolis Utilities — Replace death stone with Tombstone grave key on respawn
// ---------------------------------------------------------------------------

PlayerEvents.respawned(event => {
  const stoneSlot = event.player.inventory.find(Item.of('opolisutilities:death_stone'))
  if (stoneSlot < 0) return

  const keySlot = event.player.inventory.find(Item.of('tombstone:grave_key'))
  const keyNbt   = event.player.getSlot(keySlot).get().nbt

  event.player.inventory.setStackInSlot(stoneSlot, Item.of('tombstone:grave_key', 1, keyNbt))
  event.player.getSlot(keySlot).get().shrink(1)
})

// ---------------------------------------------------------------------------
// Enigmatic Delicacy — Fix bush fruit drop on right-click at max age
// ---------------------------------------------------------------------------

BlockEvents.rightClicked('enigmaticdelicacy:enigmatic_bush', event => {
  if (event.block.getProperties().age.toString() !== '7') return

  event.block.set('enigmaticdelicacy:enigmatic_bush')

  const fruitColor  = Math.floor(Math.random() * 14) + 1
  const fruitAmount = Math.floor(Math.random() * 2) + 1

  if (fruitColor <= 7) {
    event.player.give(Item.of('enigmaticdelicacy:enigmatic_fruit', fruitAmount, `{AssignedColor:0.${fruitColor}f}`))
  }

  event.cancel()
})

// ---------------------------------------------------------------------------
// Lava Bucket Condenser — Right-click to enter fill/empty mode
// ---------------------------------------------------------------------------

BlockEvents.rightClicked(event => {
  if (event.hand !== 'MAIN_HAND') return

  const mainHand    = event.player.mainHandItem
  const mainHandID  = mainHand.id
  const mainHandNBT = mainHand.getNbt() || { stored: 1 }
  const offHandID   = event.player.offHandItem.id
  const perData     = event.player.persistentData

  // --- Condensed lava bucket (filling mode entry) ---
  const isCondensedBucket = mainHandID === 'minecraft:bucket' && mainHand.getNbtString().contains('Enchantments:[{}]')
  if (isCondensedBucket) {
    if (mainHandNBT.stored >= 64) {
      event.player.tell("You're in filling mode and your bucket's too full!")
      event.cancel()
      return
    }
    if (offHandID !== 'minecraft:bucket') {
      event.player.tell('You need a bucket in your off-hand!')
      event.cancel()
      return
    }

    // Notify at every 16-bucket milestone
    if (mainHandNBT.stored % 16 === 0) {
      event.player.tell(`Your bucket has ${mainHandNBT.stored} lava buckets in it!`)
    }

    perData.putInt('store', mainHandNBT.stored)
    perData.putBoolean('filling', true)
    return
  }

  // --- Condensed lava bucket (emptying mode entry) ---
  if (mainHandID === 'minecraft:lava_bucket' && mainHandNBT.stored > 1) {
    perData.putInt('store', mainHandNBT.stored)
    perData.putBoolean('emptying', true)
  }
})

// ---------------------------------------------------------------------------
// Lava Bucket Condenser — Left-click to toggle fill/empty mode
// ---------------------------------------------------------------------------

ItemEvents.firstLeftClicked(event => {
  const mainHand    = event.player.mainHandItem
  const mainHandID  = mainHand.id
  const mainHandNBT = mainHand.getNbt() || { stored: 1 }
  const perData     = event.player.persistentData

  const isCondensedBucket = mainHandID === 'minecraft:bucket' && mainHand.getNbtString().contains('Enchantments:[{}]')
  const isCondensedLava   = mainHandID === 'minecraft:lava_bucket'

  if (!isCondensedLava && !isCondensedBucket) return

  // Crouch + left-click = show current count
  if (event.player.isCrouching()) {
    const count = mainHandNBT.stored ?? 1
    event.player.tell(`You currently have ${count} lava bucket${count === 1 ? '' : 's'} condensed!`)
    event.cancel()
    return
  }

  // Left-click = toggle between filling and emptying mode
  const crouched = perData.getBoolean('crouched')
  if (crouched) {
    event.player.tell('Filling mode enabled — left-click to switch to emptying mode!')
    event.player.setMainHandItem(Item.of('minecraft:bucket',      1, { stored: mainHandNBT.stored, Enchantments: [{}] }))
  } else {
    event.player.tell('Emptying mode enabled — left-click to switch to filling mode!')
    event.player.setMainHandItem(Item.of('minecraft:lava_bucket', 1, { stored: mainHandNBT.stored, Enchantments: [{}] }))
  }
  perData.putBoolean('crouched', !crouched)
})

// ---------------------------------------------------------------------------
// Lava Bucket Condenser — Tick handler: apply the queued fill/empty action
// ---------------------------------------------------------------------------

PlayerEvents.tick(event => {
  const mainHand    = event.player.mainHandItem
  const mainHandID  = mainHand.id
  const offHand     = event.player.offHandItem
  const offHandID   = offHand.id
  const perData     = event.player.persistentData
  const stored      = perData.getInt('store')
  const storedEnch  = { stored: stored, Enchantments: [{}] }

  // --- Fill action: lava bucket placed → increment stored count ---
  if (perData.getBoolean('filling') && mainHandID === 'minecraft:lava_bucket') {
    storedEnch.stored++
    event.player.setMainHandItem(Item.of('minecraft:bucket', 1, storedEnch))
    offHand.shrink(1)
    perData.putBoolean('filling', false)
    return
  }

  // --- Empty action: condensed bucket used → decrement stored count ---
  if (perData.getBoolean('emptying') && mainHandID === 'minecraft:bucket') {
    storedEnch.stored--
    event.player.setMainHandItem(Item.of('minecraft:lava_bucket', 1, storedEnch))

    // Return the empty bucket to the player
    if (offHandID === 'minecraft:bucket' && offHand.count < 64) {
      event.player.setOffHandItem(`${offHand.count + 1}x minecraft:bucket`)
    } else if (offHandID === 'minecraft:air') {
      event.player.setOffHandItem('minecraft:bucket')
    } else {
      event.player.give('minecraft:bucket')
    }

    perData.putBoolean('emptying', false)
  }
})