// =======================================================================
// LOGIKKISTE - ANALOGE SPEZIAL-EINGÄNGE (GLÄTTER, TASTEN & JOYSTICK)
// =======================================================================

Blockly.defineBlocksWithJsonArray([

    // --- 1. BLOCKIERUNGSFREIER GLÄTTER ---
    {
        "type": "ard_analog_smooth_pro",
        "message0": "Lese geglätteten Wert von PIN %1 %2 %3 Messungen alle %4 ms",
        "args0": [
            {"type": "field_input", "name": "PIN", "text": "A0"},
            {"type": "input_dummy"},
            {"type": "field_number", "name": "SAMPLES", "value": 10, "min": 1, "max": 16},
            {"type": "field_number", "name": "INTERVAL", "value": 2, "min": 0}
        ],
        "output": "Number",
        "colour": 45,
        "tooltip": "Liest den analogen Pin blitzschnell im Hintergrund aus (kein Programm-Stopp durch delay!). Max 16 Messungen."
    },

    // --- 2. ANALOG-TASTENFELD (Resistor Ladder) ---
    {
        "type": "ard_analog_button_ladder",
        "message0": "Analog-Tastenfeld an PIN %1 erkennt Taste %2",
        "args0": [
            {"type": "field_input", "name": "PIN", "text": "A0"},
            {
                "type": "field_dropdown",
                "name": "BUTTON",
                "options": [
                    ["1 (z.B. Rechts)", "1"],
                    ["2 (z.B. Oben)", "2"],
                    ["3 (z.B. Unten)", "3"],
                    ["4 (z.B. Links)", "4"],
                    ["5 (z.B. Select)", "5"]
                ]
            }
        ],
        "output": "Boolean",
        "colour": 65,
        "tooltip": "Erkennt Tastendrücke über ein Widerstandsnetzwerk (Standardwerte passend für z.B. LCD Keypad Shields)."
    },

    // --- 3. OPTIONAL: EIGENE SCHWELLENWERTE (Tastenfeld) ---
    {
        "type": "ard_analog_button_setup",
        "message0": "⚠️ Setup Analog-Tastenfeld PIN %1 %2 Eigene Schwellenwerte (5 Stück): %3",
        "args0": [
            {"type": "field_input", "name": "PIN", "text": "A0"},
            {"type": "input_dummy"},
            {"type": "field_input", "name": "THRESHOLDS", "text": "50, 195, 380, 555, 790"}
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": 65,
        "tooltip": "Nur im SETUP verwenden! Überschreibt die Standardwerte, falls du eigene Widerstände verbaut hast."
    },

    // --- 4. UNIVERSAL JOYSTICK (Freie Pins & 8 Richtungen) ---
    {
        "type": "ard_joy_universal",
        "message0": "Joystick an PIN X %1 und PIN Y %2 bewegt sich nach %3",
        "args0": [
            {"type": "field_input", "name": "PIN_X", "text": "A0"},
            {"type": "field_input", "name": "PIN_Y", "text": "A1"},
            {
                "type": "field_dropdown",
                "name": "DIR",
                "options": [
                    ["Mitte (Losgelassen)", "0"],
                    ["⬆️ Oben", "1"],
                    ["⬇️ Unten", "2"],
                    ["⬅️ Links", "3"],
                    ["➡️ Rechts", "4"],
                    ["↖️ Oben-Links", "5"],
                    ["↗️ Oben-Rechts", "6"],
                    ["↙️ Unten-Links", "7"],
                    ["↘️ Unten-Rechts", "8"]
                ]
            }
        ],
        "output": "Boolean",
        "colour": 45,
        "tooltip": "Liest einen beliebigen analogen Joystick aus. (Standard: < 400 & > 600)"
    },

    // --- 5. OPTIONAL: JOYSTICK GRENZWERTE ÄNDERN ---
    {
        "type": "ard_joy_setup",
        "message0": "⚠️ Setup Joystick Grenzwerte %1 Links/Unten (kleiner als): %2 Rechts/Oben (größer als): %3",
        "args0": [
            {"type": "input_dummy"},
            {"type": "input_value", "name": "LOW_VAL", "check": "Number"},
            {"type": "input_value", "name": "HIGH_VAL", "check": "Number"}
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": 45,
        "tooltip": "Standard ist < 400 und > 600. Nutze diesen Block im Setup, um verschlissene Joysticks anzupassen."
    }
]);


// =======================================================================
// C++ CODE GENERATOREN
// =======================================================================

// 1. GENERATOR: GLÄTTER
ArduinoGenerator.forBlock['ard_analog_smooth_pro'] = function(block) {
    const pin = String(block.getFieldValue('PIN')).trim();
    const samples = block.getFieldValue('SAMPLES');
    const interval = block.getFieldValue('INTERVAL');
    const objName = `smooth_${pin}`;

    ArduinoGenerator.usedPinsAnalog.add(pin);
    ArduinoGenerator.globals_.add(`#include "KK_Analog.h"`);
    
    ArduinoGenerator.globals_.add(`KK_AnalogSmooth ${objName}(${pin}, ${samples}, ${interval});`);

    if (!ArduinoGenerator.autoSetup_.includes(`  ${objName}.begin();\n`)) {
        ArduinoGenerator.autoSetup_.push(`  ${objName}.begin();\n`);
    }
    if (!ArduinoGenerator.autoLoop_.includes(`  ${objName}.update();\n`)) {
        ArduinoGenerator.autoLoop_.push(`  ${objName}.update();\n`);
    }

    return [`${objName}.getValue()`, 0];
};


// 2. GENERATOR: TASTENFELD
ArduinoGenerator.forBlock['ard_analog_button_ladder'] = function(block) {
    const pin = String(block.getFieldValue('PIN')).trim();
    const btn = block.getFieldValue('BUTTON');
    const objName = `analogBtns_${pin}`;

    ArduinoGenerator.usedPinsAnalog.add(pin);
    ArduinoGenerator.globals_.add(`#include "KK_Analog.h"`);

    // Standard-Schwellenwerte anlegen
    ArduinoGenerator.globals_.add(`int kk_analog_thresh_${pin}[5] = {50, 195, 380, 555, 790};`);
    ArduinoGenerator.globals_.add(`KK_AnalogButtons ${objName}(pin${pin}, kk_analog_thresh_${pin}, 5, true);`);

    if (!ArduinoGenerator.autoLoop_.includes(`  ${objName}.update();\n`)) {
        ArduinoGenerator.autoLoop_.push(`  ${objName}.update();\n`);
    }

    return [`(${objName}.getButton() == ${btn})`, 0];
};


// 3. GENERATOR: TASTENFELD SETUP
ArduinoGenerator.forBlock['ard_analog_button_setup'] = function(block) {
    const pin = String(block.getFieldValue('PIN')).trim();
    const threshStr = block.getFieldValue('THRESHOLDS');
    
    let thresholds = threshStr.split(',').map(val => val.trim()).filter(val => val !== "");
    
    let code = `  // --- Eigene Schwellenwerte für Pin ${pin} ---\n`;
    for(let i = 0; i < thresholds.length; i++) {
        if (i < 5) {
            code += `  kk_analog_thresh_${pin}[${i}] = ${thresholds[i]};\n`;
        }
    }
    return code;
};


// 4. GENERATOR: UNIVERSAL JOYSTICK
ArduinoGenerator.forBlock['ard_joy_universal'] = function(block) {
    const pinX = String(block.getFieldValue('PIN_X')).trim();
    const pinY = String(block.getFieldValue('PIN_Y')).trim();
    const dir = block.getFieldValue('DIR');

    ArduinoGenerator.usedPinsAnalog.add(pinX);
    ArduinoGenerator.usedPinsAnalog.add(pinY);
    ArduinoGenerator.globals_.add(`#include "KK_Analog.h"`);

    ArduinoGenerator.globals_.add(`int kk_joy_low = 400;`);
    ArduinoGenerator.globals_.add(`int kk_joy_high = 600;`);

    // Greift direkt auf die neue statische C++ Funktion der Library zu
    return [`(KK_Joystick::getDirection(pin${pinX}, pin${pinY}, kk_joy_low, kk_joy_high) == ${dir})`, 0];
};


// 5. GENERATOR: JOYSTICK GRENZWERTE (SETUP)
ArduinoGenerator.forBlock['ard_joy_setup'] = function(block) {
    const lowVal = ArduinoGenerator.valueToCode(block, 'LOW_VAL', 0) || '400';
    const highVal = ArduinoGenerator.valueToCode(block, 'HIGH_VAL', 0) || '600';
    
    ArduinoGenerator.globals_.add(`int kk_joy_low = 400;`);
    ArduinoGenerator.globals_.add(`int kk_joy_high = 600;`);
    
    return `  kk_joy_low = ${lowVal};\n  kk_joy_high = ${highVal};\n`;
};