// 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
 *                - 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)
})

// ---------------------------------------------------------------------------
// Bucket Condenser — Helper function
// ---------------------------------------------------------------------------
/**
 * @description Check if a string is acceptable for condensing
 * @param {string} test
 */
function allowed(test) {
    let whitelist = [
        'alexscaves:acid_bucket',
        'alexscaves:purple_soda_bucket',
    ]
    let blacklist = [
        'biomeswevegone:man_o_war_bucket',
        'botania:open_bucket',
        'endertanks:ender_bucket',
        'immersiveengineering:potion_bucket',
        'minecraft:axolotl_bucket',
        'minecraft:cod_bucket',
        'minecraft:salmon_bucket',
        'minecraft:tropical_fish_bucket',
        'minecraft:pufferfish_bucket',
        'minecraft:tadpole_bucket',
        'mynethersdelight:hot_wings_bucket',
        'tconstruct:potion_bucket',
        'aquaculture',
        'beachparty',
        'blue_skies',
        'cataclysm',
        'enviornmental',
        'fishofthieves',
        'forbidden_arcanus',
        'naturalist',
        'quark',
        'sushigocrafting',
        'upgrade_aquatic'
    ]
    if (whitelist.some(v => test.includes(v))) {
        return (test)
    }
    if (blacklist.some(v => test.includes(v))) {
        return (false)
    }
    if (test.includes('bucket')) {
        return (test)
    }
    return (false)
}

BlockEvents.rightClicked(event => {
    if (event.hand != 'MAIN_HAND') return
    // ---------------------------------------------------------------------------
    // Enigmatic Delicacy — Fix bush fruit drop on right-click at max age
    // ---------------------------------------------------------------------------
    if (event.block.id == 'enigmaticdelicacy:enigmatic_bush' && event.block.getProperties().age.toString() == '7') {
        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()
    }

    // ---------------------------------------------------------------------------
    // Bucket Condenser — Right-click to fill/empty
    // ---------------------------------------------------------------------------
    const mainHand = event.player.mainHandItem
    const mainHandID = mainHand.id
    const mainHandNBT = mainHand.getNbt()
    const offHandID = event.player.offHandItem.id
    const perData = event.player.persistentData

    // --- Condensed bucket (filling mode entry) ---
    if (mainHand.getNbtString().contains('Enchantments:[{}]')) {
        if (mainHandID == 'minecraft:bucket') {
            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} condensed buckets in it!`)
            }

            perData.putString('storedBuck', allowed(mainHandID))
            perData.putInt('store', mainHandNBT.stored)
            perData.putInt('switch', 1)
            return
        }
        event.player.tell(mainHandID)

        // --- Condensed bucket (emptying mode entry) ---
        if (allowed(mainHandID) == 'minecraft:lava_bucket' && mainHandNBT.stored > 1) {
            // Notify at every 16-bucket milestone
            if (mainHandNBT.stored % 16 == 0) {
                event.player.tell(`Your bucket has ${mainHandNBT.stored} condensed buckets in it!`)
            }

            perData.putString('storedBuck', allowed(mainHandID))
            perData.putInt('store', mainHandNBT.stored)
            perData.putInt('switch', 2)
            return
        }
    }
})

// ---------------------------------------------------------------------------
// Bucket Condenser — Right-click on entity to fill/empty
// ---------------------------------------------------------------------------
ItemEvents.entityInteracted(event => {
    const mainHand = event.player.mainHandItem
    const mainHandID = mainHand.id
    const mainHandNBT = mainHand.getNbt()
    const offHandID = event.player.offHandItem.id
    const perData = event.player.persistentData

    // --- Condensed bucket (filling mode entry) ---
    if (mainHand.getNbtString().contains('Enchantments:[{}]')) {
        if (mainHandID == 'minecraft:bucket') {
            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} condensed buckets in it!`)
            }

            perData.putString('storedBuck', allowed(mainHandID))
            perData.putInt('store', mainHandNBT.stored)
            perData.putInt('switch', 1)
            return
        }
        event.player.tell(mainHandID)

        // --- Condensed bucket (emptying mode entry) ---
        if (allowed(mainHandID) == 'minecraft:lava_bucket' && mainHandNBT.stored > 1) {
            // Notify at every 16-bucket milestone
            if (mainHandNBT.stored % 16 == 0) {
                event.player.tell(`Your bucket has ${mainHandNBT.stored} condensed buckets in it!`)
            }

            perData.putString('storedBuck', allowed(mainHandID))
            perData.putInt('store', mainHandNBT.stored)
            perData.putInt('switch', 2)
            return
        }
    }
})
// ---------------------------------------------------------------------------
// 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 }
    if (mainHandID == 'minecraft:lava_bucket' || (mainHandID == 'minecraft:bucket' && mainHand.getNbtString().contains('Enchantments:[{}]'))) {

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

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


// ---------------------------------------------------------------------------
// Bucket Condenser — Tick handler: apply the queued fill/empty action
// ---------------------------------------------------------------------------
PlayerEvents.tick(event => {
    const player = event.player
    const mainHand = player.mainHandItem
    const mainHandID = mainHand.id
    const offHand = player.offHandItem
    const offHandID = offHand.id
    const perData = player.persistentData
    const store = perData.getInt('store')
    const storedBuck = perData.getString('storedBuck')
    const storedEnch = { stored: store, Enchantments: [{}], storedBucket: storedBuck }

    if (perData.getInt('switch') > 0) {
        // --- Fill action: bucket placed → increment stored count ---
        if (perData.getInt('switch') == 1 && allowed(mainHandID) == 'minecraft:lava_bucket') {
            storedEnch.stored++
            player.setMainHandItem(Item.of('minecraft:bucket', 1, storedEnch))
            offHand.shrink(1)
        }

        // --- Empty action: condensed bucket used → decrement stored count ---
        if (perData.getInt('switch') == 2 && mainHandID == 'minecraft:bucket' && allowed(storedBuck) == 'minecraft:lava_bucket') {
            storedEnch.stored--
            player.setMainHandItem(Item.of(storedBuck, 1, storedEnch))

            // Return the empty bucket to the player
            if (offHandID == 'minecraft:bucket' && offHand.count < 64) {
                player.setOffHandItem(`${offHand.count + 1}x minecraft:bucket`)
            } else if (offHandID == 'minecraft:air') {
                player.setOffHandItem('minecraft:bucket')
            } else {
                player.give('minecraft:bucket')
            }
        }
        // Set all persistent data to placeholder values
        perData.putString('storedBuck', 'negative')
        perData.putInt('switch', 0)
        perData.putInt('store', 0)
    }
})