// SECTION 1: CAPTURING THE MOB
ItemEvents.entityInteracted(event => {
    const { item, target, player, hand } = event
    if (item.id !== 'kubejs:capture_horn' || hand !== 'MAIN_HAND') return

    // Logic: Only capture if the horn is EMPTY
    if (!item.nbt || !item.nbt.StoredEntity) {
        
        // Safety: Don't capture players or non-living things
        if (!target.isLiving()) return

        // Ownership Check: Check if player's UUID is in the mob's NBT
        let isOwner = target.nbt.toString().contains(player.uuid.toString())
        let isTame = target.nbt.getInt('Tame') === 1 || target.nbt.getBoolean('Tame')

        if (isOwner || isTame) {
            // We MUST save the 'id' of the entity so we know what to spawn later
            let entityData = target.serializeNBT()
            entityData.id = target.type // Force the ID into the data

            item.nbt = {
                StoredEntity: entityData,
                EntityName: target.displayName.string
            }

            target.discard() // Remove from world
            player.swing()
            player.displayClientMessage(`§6Captured ${item.nbt.EntityName}!`, true)
            event.cancel() // Prevents the player from mounting the mob
        } else {
            player.displayClientMessage("§cThis mount doesn't belong to you!", true)
        }
    }
})

// SECTION 2: RELEASING THE MOB
ItemEvents.rightClicked(event => {
    const { item, player, level, hand } = event
    if (item.id !== 'kubejs:capture_horn' || hand !== 'MAIN_HAND') return

    // Logic: Only release if the horn is FULL
    if (item.nbt && item.nbt.StoredEntity) {
        let nbtData = item.nbt.StoredEntity
        
        // Find where player is looking (up to 5 blocks away)
        let ray = player.rayTrace(5)
        let spawnPos = ray.block ? ray.block.pos.relative(ray.facing) : player.blockPosition()

        // Create the entity from the stored ID
        let entity = level.createEntity(nbtData.id)
        if (entity) {
            entity.deserializeNBT(nbtData)
            entity.setPosition(spawnPos.x + 0.5, spawnPos.y, spawnPos.z + 0.5)
            entity.spawn()

            // Reset the item
            item.nbt = {}
            player.swing()
            player.displayClientMessage(`§aReleased ${item.nbt.EntityName || 'Mount'}!`, true)
        }
    }
})

// SECTION 3: EMERGENCY RESET (Left-click air to clear NBT if something breaks)
ItemEvents.firstLeftClicked(event => {
    const { item, player } = event
    if (item.id === 'kubejs:capture_horn' && player.isCrouching()) {
        item.nbt = {}
        player.displayClientMessage("§4Horn Cleared!", true)
    }
})