// Global variables to store positions
let pos1 = null;
let pos2 = null;
let debounce = false;

// Function to handle right-click event
BlockEvents.rightClicked(event => {
    const player = event.getPlayer();
    const heldItem = player.getMainHandItem();

    if (debounce) {
        return;
    }
    debounce = true;

    setTimeout(() => {
        debounce = false;
    }, 100); // Adjust the debounce time as needed

    console.log("Right-click detected with item: " + heldItem.getId());

    if (heldItem.getId() === 'minecraft:nether_star') {
        // Set the first position if holding a Nether Star
        pos1 = event.getBlock().getPos();
        player.tell("First position set at " + pos1);
        console.log("First position set at " + pos1);
    } else if (heldItem.getId() === 'minecraft:amethyst_shard') {
        // Set the second position if holding an Amethyst Shard
        pos2 = event.getBlock().getPos();
        player.tell("Second position set at " + pos2);
        console.log("Second position set at " + pos2);

        // Generate layout after both positions are set
        if (pos1 && pos2) {
            console.log("Generating layout...");
            generateLayout(event.getLevel(), pos1, pos2);
        }
    } else if (heldItem.getId() === 'minecraft:end_rod') {
        // Reset positions if holding an End Rod
        pos1 = null;
        pos2 = null;
        player.tell("Positions reset");
        console.log("Positions reset");
    }
});

// Function to generate layout
function generateLayout(level, pos1, pos2) {
    const yLevel = pos1.getY();  // Assuming same Y level for all blocks
    const minX = Math.min(pos1.getX(), pos2.getX());
    const maxX = Math.max(pos1.getX(), pos2.getX());
    const minZ = Math.min(pos1.getZ(), pos2.getZ());
    const maxZ = Math.max(pos1.getZ(), pos2.getZ());

    let layout = [];
    let keyMap = {};

    for (let z = minZ; z <= maxZ; z++) {
        let row = '';
        for (let x = minX; x <= maxX; x++) {
            let block = level.getBlock(x, yLevel, z); // Changed from const to let
            let blockId = block.getId(); // Changed from const to let

            if (blockId === 'minecraft:air' ||
                blockId === 'minecraft:yellow_glazed_terracotta' ||
                blockId === 'minecraft:lime_glazed_terracotta') {
                row += ' '; // Insert a space for air and blacklisted blocks
            } else {
                // Map block to a key
                if (!keyMap[blockId]) {
                    keyMap[blockId] = String.fromCharCode(65 + Object.keys(keyMap).length); // Assign a new key
                }
                row += keyMap[blockId];
            }
        }
        layout.push(row);
    }

    // Generate layer and keys
    let layerStr = layout.map(row => `        "${row}"`).join(",\n");
    let keyStr = Object.entries(keyMap).map(([blockId, key]) => `    key("${key}", { block: "${blockId}" })`).join("\n");

    // Output the generated script
    console.log(`
.layout(a => {
    a.layer([
${layerStr}
    ])
${keyStr}
})
    `);

    // Reset positions
    pos1 = null;
    pos2 = null;
}
