// client/signal_blocks.js

// Define Blockly blocks for user-created signals
export function defineSignalBlocks() {

    // Ensure Blockly.JSON is available
    if (!Blockly.JSON) {
        console.error('Blockly.JSON is not defined. Ensure json_generators.js is loaded before signal_blocks.js.');
        return;
    }

    // Get all user signals
    const signals = window.UI?.signals?.dataManager?.getAllSignals?.() || [];
    const toolboxCategory = document.querySelector('#toolbox_advanced category[name="Signals"]');

    if (!toolboxCategory) {
        console.error('Signals category not found in the toolbox.');
        return;
    }

    // Check if there are any signals to display
    if (signals.length === 0) {
        // Add helpful message when no signals exist
        const labelElement = document.createElement('label');
        labelElement.setAttribute('text', 'No signals configured yet.');
        toolboxCategory.appendChild(labelElement);

        const labelElement2 = document.createElement('label');
        labelElement2.setAttribute('text', 'Create signals from the Signals panel');
        toolboxCategory.appendChild(labelElement2);

        const labelElement3 = document.createElement('label');
        labelElement3.setAttribute('text', 'on the right side of the screen.');
        toolboxCategory.appendChild(labelElement3);

        console.log('No signals available - added help message to toolbox.');
        return;
    }

    for (const signal of signals) {
        const signalName = signal.name;

        // Create a unique block type by replacing spaces with underscores
        const sanitizedSignalName = signalName.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
        const blockType = 'signal_' + sanitizedSignalName;

        // Define the block for this signal
        Blockly.defineBlocksWithJsonArray([{
            "type": blockType,
            "message0": `Signal: ${signalName} %1`,
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "OUTPUT",
                    "options": [
                        ["is triggered", "triggered"],
                        ["value", "value"]
                    ]
                }
            ],
            "output": "dynamic_value",
            "colour": 160,
            "tooltip": `Check if the '${signalName}' signal is triggered or get its value`,
            "helpUrl": ""
        }]);

        // Define the JSON generator for this block
        Blockly.JSON[blockType] = function(block) {
            const selectedOutput = block.getFieldValue('OUTPUT');
            const json = {
                type: 'signal',
                fields: {
                    NAME: signalName,
                    OUTPUT: selectedOutput
                }
            };
            // Output as dynamic_value
            return {
                type: 'dynamic_value',
                values: [json]
            };
        };

        // Append the newly created block to the Signals category in the toolbox
        const blockElement = document.createElement('block');
        blockElement.setAttribute('type', blockType);
        toolboxCategory.appendChild(blockElement);
    }

    console.log(`Signal blocks defined: ${signals.length} signals added to toolbox.`);
}
