window.LogiLadder = window.LogiLadder || {};
window.LogiLadder.Variables = [];

document.addEventListener('DOMContentLoaded', () => {
    const container = document.getElementById('drawflow');
    const editor = new Drawflow(container);
    editor.start();

    // --- Accordion Menü Logik ---
    const accordions = document.querySelectorAll('.accordion');
    accordions.forEach(acc => {
        acc.addEventListener('click', function() {
            this.classList.toggle('active');
            const panel = this.nextElementSibling;
            if (panel.style.display === "flex") {
                panel.style.display = "none";
            } else {
                panel.style.display = "flex";
            }
        });
    });

    // Toolbar Buttons
    const buttons = document.querySelectorAll('.menu-btn[data-node]');
    buttons.forEach(btn => {
        btn.addEventListener('click', (e) => {
            const nodeType = e.target.getAttribute('data-node');
            const def = LogiLadder.Nodes[nodeType];
            if (def) {
                editor.addNode(nodeType, def.inputs, def.outputs, 250, 200, nodeType, def.data || {}, def.html);
            } else {
                console.warn("Baustein noch nicht definiert: " + nodeType);
            }
        });
    });

    // Copy Button
    document.getElementById('btn-copy-code').addEventListener('click', () => {
        const codeText = document.getElementById('arduino-code-output').innerText;
        navigator.clipboard.writeText(codeText).then(() => {
            const btn = document.getElementById('btn-copy-code');
            btn.innerText = "Kopiert!";
            setTimeout(() => btn.innerText = "Kopieren", 2000);
        });
    });

    // --- Speichern & Laden (.json) ---
    document.getElementById('btn-save').addEventListener('click', () => {
        const exportObj = { drawflow: editor.export(), variables: window.LogiLadder.Variables };
        const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj, null, 2));
        const dlAnchorElem = document.createElement('a');
        dlAnchorElem.setAttribute("href", dataStr);
        dlAnchorElem.setAttribute("download", "fupkiste_project.json");
        dlAnchorElem.click();
    });

    document.getElementById('btn-load').addEventListener('click', () => document.getElementById('file-load').click());
    document.getElementById('file-load').addEventListener('change', (e) => {
        const file = e.target.files[0];
        if(!file) return;
        const reader = new FileReader();
        reader.onload = function(evt) {
            try {
                const parsed = JSON.parse(evt.target.result);
                if(parsed.drawflow) editor.import(parsed.drawflow);
                if(parsed.variables) {
                    window.LogiLadder.Variables = parsed.variables;
                    renderVariableTable();
                }
                updateVariableDropdowns();
                updateCode();
            } catch(err) { alert("Fehler beim Laden der Datei!"); }
        };
        reader.readAsText(file);
        e.target.value = ''; 
    });

    // --- Simulation Start/Stop ---
    const btnSim = document.getElementById('btn-sim');
    if (btnSim) {
        btnSim.addEventListener('click', () => {
            if (LogiLadder.Simulator) {
                LogiLadder.Simulator.toggle(editor);
            } else {
                console.error("Simulator-Modul (fup_simulator.js) wurde nicht gefunden.");
            }
        });
    }

    // --- Analoge Linien einfärben ---
    function colorAnalogLines() {
        const data = editor.export();
        if (!data || !data.drawflow.Home.data) return;
        const nodes = data.drawflow.Home.data;
        
        for (const [id, node] of Object.entries(nodes)) {
            const def = LogiLadder.Nodes[node.name];
            if (def && def.outType === 'float') {
                const outConns = node.outputs.output_1?.connections;
                if(outConns) {
                    outConns.forEach(conn => {
                        const path = document.querySelector(`.connection.node_in_node-${conn.node}.node_out_node-${id} .main-path`);
                        if(path) path.classList.add('analog-line');
                    });
                }
            }
        }
    }

    // --- Live Code Update ---
    function updateCode() {
        try { 
            LogiLadder.CodeGen.generate(editor.export()); 
            colorAnalogLines(); // Färbt die Linien nach jeder Änderung
        } catch (error) { 
            console.error("Code-Gen Fehler:", error); 
        }
    }

    // --- Variable Dropdowns filtern und aktualisieren ---
    function updateVariableDropdowns() {
        const dropdowns = document.querySelectorAll('.var-dropdown');
        dropdowns.forEach(select => {
            const currentValue = select.value;
            const reqType = select.getAttribute('data-vartype'); 
            select.innerHTML = '';
            
            let filteredVars = [];
            if (reqType === 'internal') {
                filteredVars = LogiLadder.Variables.filter(v => ['int', 'float', 'bool'].includes(v.type));
            } else {
                filteredVars = LogiLadder.Variables.filter(v => v.type === reqType);
            }

            if (filteredVars.length === 0) {
                select.innerHTML = '<option value="">-- Leer --</option>';
            } else {
                filteredVars.forEach(v => {
                    const opt = document.createElement('option');
                    opt.value = v.name;
                    opt.innerText = v.name;
                    select.appendChild(opt);
                });
            }
            
            if (Array.from(select.options).some(opt => opt.value === currentValue)) {
                select.value = currentValue;
            }
        });
    }

    editor.on('nodeCreated', () => { updateVariableDropdowns(); updateCode(); });
    editor.on('nodeRemoved', updateCode);
    editor.on('connectionCreated', updateCode);
    editor.on('connectionRemoved', updateCode);
    
    // --- Eingaben in den Bausteinen speichern ---
    container.addEventListener('input', (e) => {
        if(e.target.classList.contains('fup-input-field') || e.target.classList.contains('fup-select-field') || e.target.hasAttribute('df-simval')) {
            const nodeId = e.target.closest('.drawflow-node').id.slice(5);
            const node = editor.getNodeFromId(nodeId);
            
            // Text- und Zahlenwerte
            if (e.target.hasAttribute('df-varname')) node.data.varname = e.target.value; 
            if (e.target.hasAttribute('df-name')) node.data.name = e.target.value;       
            if (e.target.hasAttribute('df-time')) node.data.time = e.target.value;
            if (e.target.hasAttribute('df-limit')) node.data.limit = e.target.value;
            if (e.target.hasAttribute('df-value')) node.data.value = e.target.value;
            if (e.target.hasAttribute('df-op')) node.data.op = e.target.value;
            if (e.target.hasAttribute('df-inmin')) node.data.inmin = e.target.value;
            if (e.target.hasAttribute('df-inmax')) node.data.inmax = e.target.value;
            if (e.target.hasAttribute('df-outmin')) node.data.outmin = e.target.value;
            if (e.target.hasAttribute('df-outmax')) node.data.outmax = e.target.value;
            if (e.target.hasAttribute('df-prio')) node.data.prio = e.target.value;
            if (e.target.hasAttribute('df-line1')) node.data.line1 = e.target.value;
            if (e.target.hasAttribute('df-line2')) node.data.line2 = e.target.value;
            if (e.target.hasAttribute('df-text')) node.data.text = e.target.value;
            
            // Simulationswerte (Checkbox oder Nummernfeld)
            if (e.target.hasAttribute('df-simval')) {
                if (e.target.type === 'checkbox') {
                    node.data.simval = e.target.checked;
                } else {
                    node.data.simval = e.target.value;
                }
            }
            
            updateCode();
        }
    });

    // --- Modal Logik für Symboltabelle ---
    const modalOverlay = document.getElementById('var-modal-overlay');
    const btnOpenModal = document.getElementById('btn-open-var-modal');
    const btnCloseModal = document.getElementById('btn-close-modal');
    const tbody = document.getElementById('var-table-body');
    const btnAddVar = document.getElementById('btn-add-var');

    function renderVariableTable() {
        tbody.innerHTML = '';
        LogiLadder.Variables.forEach((v, index) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <input type="text" class="var-input var-name" data-index="${index}" value="${v.name}" placeholder="Name">
                </td>
                <td>
                    <select class="var-input var-hw" data-index="${index}">
                        <option value="onboard" ${v.hw === 'onboard' ? 'selected' : ''}>Arduino Onboard</option>
                        <option value="shield1" ${v.hw === 'shield1' ? 'selected' : ''}>Shield 1 (I2C MCP)</option>
                        <option value="none" ${v.hw === 'none' ? 'selected' : ''}>- Keine (Intern) -</option>
                    </select>
                </td>
                <td>
                    <select class="var-input var-type" data-index="${index}">
                        <optgroup label="Hardware I/O">
                            <option value="din" ${v.type === 'din' ? 'selected' : ''}>Digital IN</option>
                            <option value="dout" ${v.type === 'dout' ? 'selected' : ''}>Digital OUT</option>
                            <option value="ain" ${v.type === 'ain' ? 'selected' : ''}>Analog IN</option>
                            <option value="pwm" ${v.type === 'pwm' ? 'selected' : ''}>PWM OUT</option>
                        </optgroup>
                        <optgroup label="Interne Variablen">
                            <option value="bool" ${v.type === 'bool' ? 'selected' : ''}>bool (Wahr/Falsch)</option>
                            <option value="int" ${v.type === 'int' ? 'selected' : ''}>int (Ganzzahl)</option>
                            <option value="float" ${v.type === 'float' ? 'selected' : ''}>float (Komma)</option>
                        </optgroup>
                    </select>
                </td>
                <td>
                    <input type="text" class="var-input var-pinval" data-index="${index}" value="${v.pinval}" placeholder="Pin oder Wert (z.B. 4, A0, 100)">
                </td>
                <td>
                    <button class="btn-delete-var" data-index="${index}">X</button>
                </td>
            `;
            tbody.appendChild(tr);
        });

        document.querySelectorAll('.var-input').forEach(input => {
            input.addEventListener('change', (e) => {
                const idx = e.target.getAttribute('data-index');
                if(e.target.classList.contains('var-name')) LogiLadder.Variables[idx].name = e.target.value;
                if(e.target.classList.contains('var-hw')) LogiLadder.Variables[idx].hw = e.target.value;
                if(e.target.classList.contains('var-type')) LogiLadder.Variables[idx].type = e.target.value;
                if(e.target.classList.contains('var-pinval')) LogiLadder.Variables[idx].pinval = e.target.value;
                updateVariableDropdowns();
                updateCode();
            });
        });

        document.querySelectorAll('.btn-delete-var').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const idx = e.target.getAttribute('data-index');
                LogiLadder.Variables.splice(idx, 1);
                renderVariableTable();
                updateVariableDropdowns();
                updateCode();
            });
        });
    }

    if (btnOpenModal && modalOverlay && btnCloseModal) {
        btnOpenModal.addEventListener('click', () => { modalOverlay.classList.remove('hidden'); });
        btnCloseModal.addEventListener('click', () => { modalOverlay.classList.add('hidden'); });
    }

    if (btnAddVar) {
        btnAddVar.addEventListener('click', () => {
            LogiLadder.Variables.push({ name: 'Neu_' + (LogiLadder.Variables.length + 1), hw: 'onboard', type: 'din', pinval: '2' });
            renderVariableTable();
            updateVariableDropdowns();
            updateCode();
        });
    }

    renderVariableTable();
    updateCode();
});