import { world, system } from "@minecraft/server";

// Function to check if a block is a campfire and if it's lit
function isLitCampfire(block) {
    if (block.typeId === "minecraft:campfire") {
        const extinguishedState = block.permutation.getState("extinguished");
        return extinguishedState === false;
    }
    return false;
}

// Function to check if a block is above a campfire (lit or not)
function isAboveCampfire(block) {
    const blockBelow = block.dimension.getBlock({ x: block.location.x, y: block.location.y - 1, z: block.location.z });
    return blockBelow.typeId === "minecraft:campfire";
}

// Function to clamp a value between min and max
function clamp(value, min, max) {
    return Math.max(min, Math.min(max, value));
}

// Handle block placement
world.afterEvents.playerPlaceBlock.subscribe((event) => {
    const block = event.block;
    if (block.typeId === "block_swg:dss_mc_pot") {
        // Set initial state to false (not cooking)
        const currentPermutation = block.permutation;
        const newPermutation = currentPermutation.withState("dss_add:pot_cooking", false)
        .withState("dss_add:pot_can_cooking", false);
        block.setPermutation(newPermutation);
    }
});

// Main system that runs every tick
system.runInterval(() => {
    // Get all players
    const players = world.getAllPlayers();
    
    // For each player, check blocks around them
    for (const player of players) {
        const location = player.location;
        const dimension = player.dimension;
        
        // Check a 16x16x16 area around the player
        for (let x = -8; x <= 8; x++) {
            for (let y = -8; y <= 8; y++) {
                for (let z = -8; z <= 8; z++) {
                    // Clamp coordinates to world boundaries
                    const worldX = clamp(Math.floor(location.x) + x, -30000000, 30000000);
                    const worldY = clamp(Math.floor(location.y) + y, -64, 320);
                    const worldZ = clamp(Math.floor(location.z) + z, -30000000, 30000000);
                    
                    try {
                        const block = dimension.getBlock({ x: worldX, y: worldY, z: worldZ });
                        
                        if (block && block.typeId === "block_swg:dss_mc_pot") {
                            const isAboveFire = isAboveCampfire(block);
                            const isLit = isAboveFire && isLitCampfire(block.dimension.getBlock({ 
                                x: block.location.x, 
                                y: block.location.y - 1, 
                                z: block.location.z 
                            }));

                            const currentPermutation = block.permutation;
                            const currentCooking = currentPermutation.getState("dss_add:pot_cooking");
                            const currentCanCooking = currentPermutation.getState("dss_add:pot_can_cooking");

                            // Only trigger if state is changing to cooking
                            if (isLit && (!currentCooking || !currentCanCooking)) {
                                const x = block.location.x;
                                const y = block.location.y;
                                const z = block.location.z;
                                player.runCommandAsync(`particle minecraft:totem_particle ${x} ${y} ${z}`);
                                player.runCommandAsync(`playsound random.anvil_land @a ${x} ${y} ${z} 1 1`);
                            }

                            const newPermutation = currentPermutation.withState("dss_add:pot_cooking", isAboveFire)
                                .withState("dss_add:pot_can_cooking", isLit);

                            block.setPermutation(newPermutation);
                        }
                    } catch (error) {
                        // Silently ignore any out of bounds errors
                        continue;
                    }
                }
            }
        }
    }
}, 20); // Check every second 