// =======================================================================
// E-PAPER 4.2" (Waveshare Rev 2.2) BLOCKLY DEFINITIONEN & GENERATOREN
// =======================================================================

// --- 1. E-PAPER CUSTOM FIELD (POP-UP EDITOR FÜR BILDER) ---
class FieldCodeInputEINK extends Blockly.Field {
    constructor(code) {
        super(code || '');
        this.SERIALIZABLE = true;
        this.CURSOR = 'pointer';
    }

    static fromJson(options) {
        return new FieldCodeInputEINK(options['text'] || '');
    }

    initView() {
        this.borderRect_ = Blockly.utils.dom.createSvgElement('rect', {
            'rx': 4, 'ry': 4, 'x': 0, 'y': 0, 'height': 22,
            'fill': 'rgba(0,0,0,0.25)',
            'stroke': 'rgba(255,255,255,0.3)',
            'stroke-width': '1'
        }, this.fieldGroup_);

        this.textEl_ = Blockly.utils.dom.createSvgElement('text', {
            'class': 'blocklyText', 'x': 8, 'y': 15,
            'fill': '#fff', 'font-size': '11pt'
        }, this.fieldGroup_);

        this.updateSize_();
    }

    updateSize_() {
        const code  = this.getValue() || '';
        const lines = code.split('\n').filter(function(l) { return l.trim(); }).length;
        const preview = lines > 0
            ? ('✏️  ' + lines + ' Zeilen Code – klicken zum Bearbeiten')
            : '📋  Klicken zum Einfügen...';

        if (this.textEl_) this.textEl_.textContent = preview;

        const width = Math.max(220, preview.length * 7.5);
        if (this.borderRect_) this.borderRect_.setAttribute('width', width);
        this.size_ = { width: width, height: 22 };
    }

    doValueUpdate_(newValue) {
        super.doValueUpdate_(newValue);
        this.updateSize_();
    }

    showEditor_() {
        const overlay = document.createElement('div');
        overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.65);z-index:9999;display:flex;align-items:center;justify-content:center;font-family:sans-serif;';

        const modal = document.createElement('div');
        modal.style.cssText = 'background:#1e1e2e;border-radius:10px;padding:20px;width:620px;max-width:95vw;box-shadow:0 12px 40px rgba(0,0,0,0.6);border:1px solid #444;';

        const title = document.createElement('div');
        title.style.cssText = 'color:#cdd6f4;font-size:15px;font-weight:bold;margin-bottom:6px;';
        title.textContent = '📋 E-Paper Code aus Pixel-Designer einfügen';

        const hint = document.createElement('div');
        hint.style.cssText = 'color:#a6adc8;font-size:12px;margin-bottom:10px;';
        hint.textContent = 'Pixel-Designer → Code kopieren → hier einfügen (Strg+V) → Übernehmen';

        const textarea = document.createElement('textarea');
        textarea.value = this.getValue();
        textarea.placeholder = 'static const unsigned char PROGMEM eink_bild[] = { ... };\ndisplay.drawBitmap(0, 0, eink_bild, 100, 100, GxEPD_BLACK);';
        textarea.style.cssText = 'width:100%;height:280px;box-sizing:border-box;font-family:monospace;font-size:12px;background:#181825;color:#cdd6f4;border:1px solid #555;border-radius:6px;padding:10px;resize:vertical;outline:none;line-height:1.5;';

        const btnRow   = document.createElement('div');
        btnRow.style.cssText = 'display:flex;gap:10px;margin-top:14px;justify-content:flex-end;';

        const btnOk     = document.createElement('button');
        const btnClear  = document.createElement('button');
        const btnCancel = document.createElement('button');

        btnOk.textContent     = '✅ Übernehmen';
        btnClear.textContent  = '🗑️ Leeren';
        btnCancel.textContent = 'Abbrechen';

        btnOk.style.cssText     = 'padding:9px 20px;background:#a6e3a1;color:#1e1e2e;border:none;border-radius:6px;cursor:pointer;font-weight:bold;font-size:13px;';
        btnClear.style.cssText  = 'padding:9px 16px;background:#f38ba8;color:#1e1e2e;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:bold;';
        btnCancel.style.cssText = 'padding:9px 16px;background:#45475a;color:#cdd6f4;border:none;border-radius:6px;cursor:pointer;font-size:13px;';

        const self = this;
        btnOk.onclick     = function() { self.setValue(textarea.value.trim()); document.body.removeChild(overlay); };
        btnClear.onclick  = function() { textarea.value = ''; textarea.focus(); };
        btnCancel.onclick = function() { document.body.removeChild(overlay); };
        overlay.onclick   = function(e) { if (e.target === overlay) document.body.removeChild(overlay); };

        btnRow.appendChild(btnCancel);
        btnRow.appendChild(btnClear);
        btnRow.appendChild(btnOk);
        modal.appendChild(title);
        modal.appendChild(hint);
        modal.appendChild(textarea);
        modal.appendChild(btnRow);
        document.body.appendChild(overlay);

        setTimeout(function() { textarea.focus(); textarea.select(); }, 60);
    }
}
Blockly.fieldRegistry.register('field_code_input_eink', FieldCodeInputEINK);


// --- 2. BLOCK DEFINITIONEN ---
Blockly.defineBlocksWithJsonArray([
    // SETUP
    {
        "type": "eink_setup",
        "message0": "E-Paper 4.2 Setup | CS %1 DC %2 RST %3 BUSY %4",
        "args0": [
            {"type": "field_input", "name": "CS", "text": "10"},
            {"type": "field_input", "name": "DC", "text": "9"},
            {"type": "field_input", "name": "RST", "text": "8"},
            {"type": "field_input", "name": "BUSY", "text": "7"}
        ],
        "message1": "Rotation %1",
        "args1": [
            {"type": "field_dropdown", "name": "ROTATION", "options": [
                ["0° (Portrait)", "0"], ["90° (Querformat)", "1"], 
                ["180°", "2"], ["270°", "3"]
            ]}
        ],
        "colour": 120,
        "previousStatement": null,
        "nextStatement": null,
        "tooltip": "Initialisiert das 4.2-Zoll E-Paper (Rev 2.2). Gehört ins Setup!"
    },
    
    // STEUERUNG (Paged-Loop Wrapper)
    {
        "type": "eink_control",
        "message0": "E-Paper Aktualisieren (%1) %2 %3",
        "args0": [
            {"type": "field_dropdown", "name": "ACTION", "options": [
                ["Full Update", "update_full"],
                ["Fast Refresh", "update_partial"]
            ]},
            {"type": "input_dummy"},
            {"type": "input_statement", "name": "DRAW_COMMANDS"}
        ],
        "colour": 120,
        "previousStatement": null,
        "nextStatement": null,
        "tooltip": "Alle Zeichen- und Textblöcke MÜSSEN in diesen Block gelegt werden!"
    },
    
    // SCHRIFTART SETZEN
    {
        "type": "eink_set_font",
        "message0": "E-Paper Schriftart auf %1 setzen",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "FONT",
                "options": [
                    ["Standard (System)", "DEFAULT"],
                    ["Adafruit Mono Fett (9pt)", "FreeMonoBold9pt7b"],
                    ["Adafruit Sans (9pt)", "FreeSans9pt7b"],
                    ["Adafruit Serif (9pt)", "FreeSerif9pt7b"]
                ]
            }
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": 120
    },

    // TEXT SCHREIBEN MIT X/Y UND HINTERGRUND (Wie beim TFT)
    {
        "type": "eink_text_xy",
        "message0": "E-Paper schreibe an X: %1 Y: %2 Text/Zahl: %3",
        "args0": [
            {"type": "input_value", "name": "X", "check": "Number"},
            {"type": "input_value", "name": "Y", "check": "Number"},
            {"type": "input_value", "name": "TEXT"}
        ],
        "message1": "Größe %1 Farbe %2 BG %3",
        "args1": [
            {"type": "field_number", "name": "SIZE", "value": 2, "min": 1, "max": 10},
            {"type": "field_dropdown", "name": "COLOR", "options": [
                ["Schwarz", "GxEPD_BLACK"], ["Weiß", "GxEPD_WHITE"]
            ]},
            {"type": "field_dropdown", "name": "BG_COLOR", "options": [
                ["Transparent", "TRANS"], ["Weiß", "GxEPD_WHITE"], ["Schwarz", "GxEPD_BLACK"]
            ]}
        ],
        "colour": 120,
        "inputsInline": true,
        "previousStatement": null,
        "nextStatement": null
    },

    // TEXT SCHREIBEN (Fließtext ohne Koordinaten wie beim OLED)
    {
        "type": "eink_print",
        "message0": "E-Paper drucke Text/Zahl: %1 neue Zeile: %2",
        "args0": [
            {"type": "input_value", "name": "VAL"},
            {"type": "field_checkbox", "name": "NEW_LINE", "checked": true}
        ],
        "message1": "Größe %1 Farbe %2",
        "args1": [
            {"type": "field_number", "name": "SIZE", "value": 2, "min": 1, "max": 10},
            {"type": "field_dropdown", "name": "COLOR", "options": [
                ["Schwarz", "GxEPD_BLACK"], ["Weiß", "GxEPD_WHITE"]
            ]}
        ],
        "colour": 120,
        "inputsInline": true,
        "previousStatement": null,
        "nextStatement": null
    },
    
    // ERWEITERTE FORMEN (Wie beim TFT/OLED)
    {
        "type": "eink_shape",
        "message0": "E-Paper Form: %1 Farbe: %2",
        "args0": [
            {"type": "field_dropdown", "name": "SHAPE", "options": [
                ["Linie", "line"], 
                ["Rechteck (leer)", "rect"], ["Rechteck (gefüllt)", "fillRect"],
                ["Kreis (leer)", "circle"], ["Kreis (gefüllt)", "fillCircle"],
                ["Rundes Rechteck (leer)", "roundRect"], ["Rundes Rechteck (gefüllt)", "fillRoundRect"],
                ["Dreieck (leer)", "triangle"], ["Dreieck (gefüllt)", "fillTriangle"]
            ]},
            {"type": "field_dropdown", "name": "COLOR", "options": [
                ["Schwarz", "GxEPD_BLACK"], ["Weiß", "GxEPD_WHITE"]
            ]}
        ],
        "message1": "X: %1 Y: %2 B / X2 / Rad: %3 H / Y2: %4",
        "args1": [
            {"type": "input_value", "name": "X", "check": "Number"},
            {"type": "input_value", "name": "Y", "check": "Number"},
            {"type": "input_value", "name": "P3", "check": "Number"},
            {"type": "input_value", "name": "P4", "check": "Number"}
        ],
        "message2": "X3 / Rad (Rundes Rechteck): %1 Y3: %2",
        "args2": [
            {"type": "input_value", "name": "P5", "check": "Number"},
            {"type": "input_value", "name": "P6", "check": "Number"}
        ],
        "colour": 120,
        "inputsInline": true,
        "previousStatement": null,
        "nextStatement": null
    },
    
    // PIXEL SETZEN
    {
        "type": "eink_pixel",
        "message0": "E-Paper Pixel an X %1 Y %2 Farbe %3",
        "args0": [
            {"type": "input_value", "name": "X", "check": "Number"},
            {"type": "input_value", "name": "Y", "check": "Number"},
            {"type": "field_dropdown", "name": "COLOR", "options": [
                ["Schwarz", "GxEPD_BLACK"], ["Weiß", "GxEPD_WHITE"]
            ]}
        ],
        "colour": 120,
        "inputsInline": true,
        "previousStatement": null,
        "nextStatement": null
    },

    // BILD AUS DESIGNER
    {
        "type": "eink_draw_picture",
        "message0": "🖼️ E-Paper Bild einfügen %1",
        "args0": [
            {
                "type": "field_code_input_eink",
                "name": "PIXEL_CODE",
                "text": ""
            }
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": 120,
        "tooltip": "Klicke hier, um den Code aus dem E-Paper Pixel-Designer einzufügen."
    }
]);


// =======================================================================
// 3. GENERATOREN
// =======================================================================

// --- Scanner für Setup ---
ArduinoGenerator.hardwareScanners['eink_setup'] = function(block) {
    const cs = block.getFieldValue('CS');
    const dc = block.getFieldValue('DC');
    const rst = block.getFieldValue('RST');
    const busy = block.getFieldValue('BUSY');
    
    // WICHTIG: Hier .includes_ statt .globals_ verwenden,
    // damit sie im C++ Code über den Fonts stehen!
    ArduinoGenerator.includes_.add(`#include <Adafruit_GFX.h>`); 
    ArduinoGenerator.includes_.add(`#include <GxEPD2_BW.h>`);
    
    ArduinoGenerator.globals_.add(`const int EINK_CS = ${cs};`);
    ArduinoGenerator.globals_.add(`const int EINK_DC = ${dc};`);
    ArduinoGenerator.globals_.add(`const int EINK_RST = ${rst};`);
    ArduinoGenerator.globals_.add(`const int EINK_BUSY = ${busy};`);

    // Fest auf Rev 2.2 (GDEY042T81) und 32-Zeilen Paged-Mode gestellt
    ArduinoGenerator.globals_.add(`GxEPD2_BW<GxEPD2_420_GDEY042T81, 32> display(GxEPD2_420_GDEY042T81(EINK_CS, EINK_DC, EINK_RST, EINK_BUSY));`);
};

// --- Setup ---
ArduinoGenerator.forBlock['eink_setup'] = function(block) {
    const rot = block.getFieldValue('ROTATION');
    ArduinoGenerator.autoSetup_.push(`  display.init(115200, true, 2, false);\n`);
    ArduinoGenerator.autoSetup_.push(`  display.setRotation(${rot});\n`);
    ArduinoGenerator.autoSetup_.push(`  display.setTextColor(GxEPD_BLACK);\n`);
    return '';
};

// --- Steuerung (Paged Loop Wrapper) ---
ArduinoGenerator.forBlock['eink_control'] = function(block) {
    const action = block.getFieldValue('ACTION');
    const drawCode = ArduinoGenerator.statementToCode(block, 'DRAW_COMMANDS');
    const isPartial = (action === 'update_partial');
    
    return `  if (!${isPartial}) { display.setFullWindow(); } else { display.setPartialWindow(0, 0, display.width(), display.height()); }\n` +
           `  display.firstPage();\n` +
           `  do {\n` +
           `    display.fillScreen(GxEPD_WHITE);\n` +
           drawCode +
           `  } while (display.nextPage());\n`;
};

// --- Schriftart Setzen ---
ArduinoGenerator.forBlock['eink_set_font'] = function(block) {
    const font = block.getFieldValue('FONT');
    if (font === 'DEFAULT') {
        return `    display.setFont();\n`;
    } else {
        // Fügt das Include für die gewählte Schriftart ganz oben in den Code ein
        ArduinoGenerator.includes_.add(`#include <Fonts/${font}.h>`);
        return `    display.setFont(&${font});\n`;
    }
};

// --- Text mit X/Y und Hintergrund ---
ArduinoGenerator.forBlock['eink_text_xy'] = function(block) {
    const x = ArduinoGenerator.valueToCode(block, 'X', 0) || '0';
    const y = ArduinoGenerator.valueToCode(block, 'Y', 0) || '0';
    const text = ArduinoGenerator.valueToCode(block, 'TEXT', 0) || '""';
    const size = block.getFieldValue('SIZE');
    const color = block.getFieldValue('COLOR');
    const bg = block.getFieldValue('BG_COLOR');
    
    let code = `    display.setTextSize(${size});\n    display.setCursor(${x}, ${y});\n`;
    if (bg === 'TRANS') {
        code += `    display.setTextColor(${color});\n`;
    } else {
        code += `    display.setTextColor(${color}, ${bg});\n`;
    }
    code += `    display.print(${text});\n`;
    return code;
};

// --- Fließtext (ohne Koordinaten) ---
ArduinoGenerator.forBlock['eink_print'] = function(block) {
    let value = ArduinoGenerator.valueToCode(block, 'VAL', 0) || '" "';
    const newLine = block.getFieldValue('NEW_LINE') === 'TRUE';
    const size = block.getFieldValue('SIZE');
    const color = block.getFieldValue('COLOR');
    const printFunction = newLine ? 'println' : 'print';
    
    return `    display.setTextSize(${size});\n    display.setTextColor(${color});\n    display.${printFunction}(${value});\n`;
};

// --- Formen ---
ArduinoGenerator.forBlock['eink_shape'] = function(block) {
    const shape = block.getFieldValue('SHAPE');
    const color = block.getFieldValue('COLOR');
    const x = ArduinoGenerator.valueToCode(block, 'X', 0) || '0';
    const y = ArduinoGenerator.valueToCode(block, 'Y', 0) || '0';
    const p3 = ArduinoGenerator.valueToCode(block, 'P3', 0) || '0'; // Breite, X2 oder Radius
    const p4 = ArduinoGenerator.valueToCode(block, 'P4', 0) || '0'; // Höhe oder Y2
    const p5 = ArduinoGenerator.valueToCode(block, 'P5', 0) || '0'; // X3 oder Radius (bei RoundRect)
    const p6 = ArduinoGenerator.valueToCode(block, 'P6', 0) || '0'; // Y3
    
    let code = '';
    if (shape === 'line') {
        code = `    display.drawLine(${x}, ${y}, ${p3}, ${p4}, ${color});\n`;
    } else if (shape === 'rect') {
        code = `    display.drawRect(${x}, ${y}, ${p3}, ${p4}, ${color});\n`;
    } else if (shape === 'fillRect') {
        code = `    display.fillRect(${x}, ${y}, ${p3}, ${p4}, ${color});\n`;
    } else if (shape === 'circle') {
        code = `    display.drawCircle(${x}, ${y}, ${p3}, ${color});\n`;
    } else if (shape === 'fillCircle') {
        code = `    display.fillCircle(${x}, ${y}, ${p3}, ${color});\n`;
    } else if (shape === 'roundRect') {
        code = `    display.drawRoundRect(${x}, ${y}, ${p3}, ${p4}, ${p5}, ${color});\n`;
    } else if (shape === 'fillRoundRect') {
        code = `    display.fillRoundRect(${x}, ${y}, ${p3}, ${p4}, ${p5}, ${color});\n`;
    } else if (shape === 'triangle') {
        code = `    display.drawTriangle(${x}, ${y}, ${p3}, ${p4}, ${p5}, ${p6}, ${color});\n`;
    } else if (shape === 'fillTriangle') {
        code = `    display.fillTriangle(${x}, ${y}, ${p3}, ${p4}, ${p5}, ${p6}, ${color});\n`;
    }
    return code;
};

// --- Pixel Setzen ---
ArduinoGenerator.forBlock['eink_pixel'] = function(block) {
    const x = ArduinoGenerator.valueToCode(block, 'X', 0) || '0';
    const y = ArduinoGenerator.valueToCode(block, 'Y', 0) || '0';
    const color = block.getFieldValue('COLOR');
    return `    display.drawPixel(${x}, ${y}, ${color});\n`;
};

// --- Bild Einfügen ---
ArduinoGenerator.forBlock['eink_draw_picture'] = function(block) {
    const raw = block.getFieldValue('PIXEL_CODE') || '';
    if (!raw.trim()) return '    // (Kein Code eingefügt)\n';

    // Einrückung für den Code aus dem Designer anpassen
    const lines = raw.split('\n').map(function(line) {
        const t = line.trimStart();
        return t.length > 0 ? '    ' + t : '';
    }).join('\n');

    return '    // --- E-Paper Bild ---\n' + lines + '\n';
};