// client/formation_blocks.js

// Define Blockly blocks for user-created formations
export function defineFormationBlocks() {

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

    // Get all user formations for current scope
    const formations = window.UI?.formations?.dataManager?.getAllFormations?.() || [];
    const toolboxCategory = document.querySelector('#toolbox_advanced category[name="Formations"]');

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

    // Clear existing formation blocks (for refresh)
    const existingBlocks = toolboxCategory.querySelectorAll('block[type^="formation_"]');
    existingBlocks.forEach(block => block.remove());

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

            const labelElement2 = document.createElement('label');
            labelElement2.setAttribute('text', 'Draw formations on the chart');
            toolboxCategory.appendChild(labelElement2);

            const labelElement3 = document.createElement('label');
            labelElement3.setAttribute('text', 'using the Formations panel.');
            toolboxCategory.appendChild(labelElement3);
        }

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

    // Remove help labels if formations exist
    const labels = toolboxCategory.querySelectorAll('label');
    labels.forEach(label => label.remove());

    // Property options vary by formation type
    const propertyOptionsByType = {
        'support_resistance': [
            ['line value', 'line']
        ],
        'channel': [
            ['upper line', 'upper'],
            ['lower line', 'lower'],
            ['midline', 'midline']
        ]
    };

    // Default properties for unknown types
    const defaultProperties = [
        ['line value', 'line']
    ];

    for (const formation of formations) {
        const formationName = formation.name;
        const formationType = formation.formation_type;
        const tblKey = formation.tbl_key;

        // Create a unique block type using tbl_key (stable UUID)
        const sanitizedName = formationName.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
        const blockType = 'formation_' + sanitizedName + '_' + tblKey.substring(0, 8);

        // Get property options for this formation type
        const propertyOptions = propertyOptionsByType[formationType] || defaultProperties;

        // Define the block for this formation
        Blockly.defineBlocksWithJsonArray([{
            "type": blockType,
            "message0": `Formation: ${formationName} %1`,
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "PROPERTY",
                    "options": propertyOptions
                }
            ],
            "output": "dynamic_value",
            "colour": 290,  // Purple-ish color for formations
            "tooltip": `Get the price value of formation '${formationName}' (${formationType}) at current candle time`,
            "helpUrl": ""
        }]);

        // Define the JSON generator for this block
        Blockly.JSON[blockType] = function(block) {
            const selectedProperty = block.getFieldValue('PROPERTY');
            const json = {
                type: 'formation',
                fields: {
                    TBL_KEY: tblKey,
                    NAME: formationName,
                    PROPERTY: selectedProperty
                }
            };
            // Output as dynamic_value
            return {
                type: 'dynamic_value',
                values: [json]
            };
        };

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

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