/**
 * DSS State System - Custom Component Handler
 * Handles the registration and events for the dss_block:state custom component
 */

import { world, system } from "@minecraft/server";
import { CUSTOM_COMPONENT } from "./dss_state_config.js";
import { debug } from "./dss_state_utils.js";
import { handleDssStateCustomComponent } from "./dss_state_main.js";

//========== CUSTOM COMPONENT REGISTRATION ==========//

/**
 * Register the DSS State custom component
 */
export function registerDssStateCustomComponent() {
    world.beforeEvents.worldInitialize.subscribe(eventData => {
        // Register the custom component
        eventData.blockComponentRegistry.registerCustomComponent(CUSTOM_COMPONENT, {
            onPlayerInteract: handlePlayerInteract,
            onPlace: handleBlockPlace
        });
        
        debug(`Registered custom component: ${CUSTOM_COMPONENT}`);
    });
}

//========== CUSTOM COMPONENT EVENT HANDLERS ==========//

/**
 * Handle player interaction with DSS state blocks
 * @param {object} event - The player interact event
 */
function handlePlayerInteract(event) {
    const { block, player } = event;
    
    if (!block || !player) {
        debug("Invalid player interact event data", "warn");
        return;
    }

    if (block.typeId.includes('dumpster') && block.permutation.getState('dss_block:state') === '2') {
        const playerInventory = player.getComponent('inventory');
        const selectedSlot = player.selectedSlotIndex;
        const itemInSlot = playerInventory.container.getItem(selectedSlot);
        
        if (itemInSlot) return;
    }
    
    debug(`Player ${player.name} interacted with DSS state block at ${block.location.x},${block.location.y},${block.location.z}`);
    
    // Handle the state interaction
    handleDssStateCustomComponent(event);
}

/**
 * Handle block placement (optional initialization)
 * @param {object} event - The block place event
 */
function handleBlockPlace(event) {
    const { block, player } = event;
    
    if (!block) {
        debug("Invalid block place event data", "warn");
        return;
    }
    
    debug(`DSS state block placed at ${block.location.x},${block.location.y},${block.location.z}`);
    
    // Initialize block state if needed
    initializeBlockState(block);
}



//========== HELPER FUNCTIONS ==========//

/**
 * Initialize a newly placed block's state
 * @param {object} block - The block to initialize
 */
function initializeBlockState(block) {
    if (!block || !block.permutation) return;
    
    // Get the current state
    const currentState = block.permutation.getState("dss_block:state");
    
    // If state is not set, initialize to state "1"
    if (!currentState) {
        const newPermutation = block.permutation.withState("dss_block:state", "1");
        block.setPermutation(newPermutation);
        debug(`Initialized block state to "1" at ${block.location.x},${block.location.y},${block.location.z}`);
    }
}

//========== COMPONENT VALIDATION ==========//

/**
 * Validate that a block has the correct custom component
 * @param {object} block - The block to validate
 * @returns {boolean} True if valid
 */
export function validateDssStateBlock(block) {
    if (!block || !block.typeId) return false;
    
    // Check if block has the required state
    const state = block.permutation.getState("dss_block:state");
    return state !== undefined;
}

//========== INITIALIZATION ==========//

/**
 * Initialize the custom component system
 */
export function initializeDssStateCustomComponents() {
    debug("Initializing DSS State custom components...");
    
    // Register the custom component
    registerDssStateCustomComponent();
    
    debug("DSS State custom components initialized successfully");
}

//========== EXPORT ==========//

// Auto-register when module is imported
initializeDssStateCustomComponents(); 