import { world as dj2a, system as ddw2 } from "@minecraft/server";
import { j2d } from "./config";
import { dbgLg } from "./util";

// Cooldown tracking for players to prevent duplicate events
const playerCooldowns = new Map();

// Register the custom component for trash can blocks
function registerTrashCanComponent() {
    dj2a.beforeEvents.worldInitialize.subscribe(event => {
        event.blockComponentRegistry.registerCustomComponent("dss:trash_can", {
            onPlayerInteract: handleTrashCanInteract
        });
        
        dbgLg('i', 'Registered trash can custom component');
    });

    dj2a.beforeEvents.playerInteractWithBlock.subscribe(event => {
        const { block, player } = event;
        if (block.typeId.includes('_16') && player.isSneaking) {
            event.cancel = true;
            ddw2.run(() => {
                const inv = player.getComponent('inventory');
                const selectedSlot = player.selectedSlotIndex;
                const itemInSlot = inv.container.getItem(selectedSlot);
                
                if (itemInSlot) {
                    // clear item in slot
                    inv.container.setItem(selectedSlot, undefined);
                    player.playSound('block.sweet_berry_bush.break');
                }
            })   
        }     
    });
}

/**
 * Handle player interaction with trash can blocks
 * This fires BEFORE any item placement/consumption occurs
 */
function handleTrashCanInteract(event) {
    const { block, player } = event;

    dbgLg('i', `Player ${player.name} interacted with block ${block.typeId}`);
    
    // Check cooldown for this player
    const playerId = player.id;
    const currentTime = Date.now();
    const lastUseTime = playerCooldowns.get(playerId);
    
    // Skip if player is on cooldown (500ms debounce)
    if (lastUseTime && (currentTime - lastUseTime) < 500) {
        dbgLg('i', `Player ${player.name} on cooldown, skipping duplicate event`);
        return;
    }
    
    // Update cooldown
    playerCooldowns.set(playerId, currentTime);
    
    // Clean up old cooldowns periodically (every 30 seconds)
    if (playerCooldowns.size > 100) {
        const cutoffTime = currentTime - 30000;
        for (const [id, time] of playerCooldowns.entries()) {
            if (time < cutoffTime) {
                playerCooldowns.delete(id);
            }
        }
    }

    // Get player's inventory
    const inv = player.getComponent('inventory');
    if (!inv || !inv.container) {
        return;
    }
    
    // Get the item in the player's selected slot
    const selectedSlot = player.selectedSlotIndex;
    const container = inv.container;
    const itemInSlot = container.getItem(selectedSlot);
    
    if (itemInSlot && itemInSlot.amount > 0) {
        dbgLg('i', `Player is attempting to trash ${itemInSlot.typeId} (type: ${itemInSlot.typeId}, amount: ${itemInSlot.amount})`);
        
        // Remove one item from the stack
        const newAmount = itemInSlot.amount - 1;
        
        if (newAmount > 0 && player.isSneaking) {
            return;
        }
        else if (newAmount > 0) {
            // Update the item stack with one less item
            itemInSlot.amount = newAmount;
            container.setItem(selectedSlot, itemInSlot);
            dbgLg('i', `Successfully removed 1 ${itemInSlot.typeId}, ${newAmount} remaining`);
        } 
        else {
            // Remove the item entirely if it's the last one
            container.setItem(selectedSlot, undefined);
            dbgLg('i', `Successfully removed last ${itemInSlot.typeId} from slot ${selectedSlot}`);
        }
        player.playSound('block.sweet_berry_bush.place');
    } else {
        dbgLg('w', `No item detected in selected slot ${selectedSlot} or slot is empty`);
    }
    
    // Cancel the interaction to prevent any item placement
    event.cancel = true;
}

// Initialize the system
registerTrashCanComponent();