// ════════════════════════════════════════════════════════════════════════════
//  EDITOR IMPORT (editor_import.js) – QET & SVG Dateien einlesen und zentrieren
// ════════════════════════════════════════════════════════════════════════════
console.log('[editor_import.js] Zentrierungs-Fix geladen');

const fileImport = document.getElementById('qet-import-input');
if (fileImport) {
    fileImport.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = function (evt) {
            const text = evt.target.result;

            Array.from(window.editorCanvas.children).forEach(child => {
                if (child.tagName.toLowerCase() !== 'defs') {
                    child.remove();
                }
            });

            if (window.fullscreenEditor) window.fullscreenEditor.classList.remove('hidden');

            let defaultName = file.name.replace(/\.[^/.]+$/, '');

            try {
                if (text.includes('<definition') && text.includes('<description')) {
                    parseQETFile(text, defaultName);
                } else if (text.includes('<svg')) {
                    parseSVGFile(text, defaultName);
                } else {
                    alert('Fehler: Weder QET- noch SVG-Code in dieser Datei gefunden.');
                }
            } catch (err) {
                console.error('[Editor-Import] Fehler beim Parsen der Datei:', err);
                alert('Beim Einlesen der Datei ist ein Fehler aufgetreten (siehe Browser-Konsole für Details): ' + err.message);
            } 
            
            setTimeout(() => {
                try {
                    flattenAndCenterCoordinates();
                } catch (err) {
                    console.error('[Editor-Import] Fehler beim Zentrieren:', err);
                }
                if (typeof window.updateCodePreview === 'function') window.updateCodePreview();
                window.autoFitZoom();
            }, 10);
            
            e.target.value = '';

            window.toolBtns.forEach(b => b.classList.remove('active'));
            const selectBtn = document.querySelector('.editor-btn[data-tool="select"]');
            if (selectBtn) selectBtn.classList.add('active');
            window.currentTool = 'select';
        };
        reader.readAsText(file);
    });
}

function parseQETFile(xmlText, fallbackName) {
    const parser  = new DOMParser();
    const xmlDoc  = parser.parseFromString(xmlText, 'text/xml');
    const description = xmlDoc.querySelector('description');
    if (!description) { alert('Ungültige QET-Datei: Keine <description> gefunden.'); return; }

    const deName = xmlDoc.querySelector('names name[lang="de"]');
    const compName = deName ? deName.textContent.trim() : fallbackName;
    
    if (document.getElementById('compId')) document.getElementById('compId').value = compName.toLowerCase().replace(/[^a-z0-9_]/g, '_');
    if (document.getElementById('compTitle')) document.getElementById('compTitle').value = compName;

    function getQETStyle(el) {
        const s    = el.getAttribute('style') || '';
        let fill   = 'none';
        if (s.includes('filling:white')) fill = 'white';
        else if (s.includes('filling:black')) fill = 'black';
        const dash = s.includes('dash') ? ' stroke-dasharray="6 3"' : '';
        return `fill="${fill}" stroke="black" stroke-width="2"${dash}`;
    }

    let importedHTML = '';

    description.querySelectorAll('line').forEach(el => {
        const s    = el.getAttribute('style') || '';
        const dash = s.includes('dash') ? ' stroke-dasharray="6 3"' : '';
        importedHTML += `<line x1="${el.getAttribute('x1')}" y1="${el.getAttribute('y1')}" x2="${el.getAttribute('x2')}" y2="${el.getAttribute('y2')}" stroke="black" stroke-width="2"${dash}/>\n`;
    });

    description.querySelectorAll('rect').forEach(el => {
        importedHTML += `<rect x="${el.getAttribute('x')}" y="${el.getAttribute('y')}" width="${el.getAttribute('width')}" height="${el.getAttribute('height')}" rx="${el.getAttribute('rx') || 0}" ry="${el.getAttribute('ry') || 0}" ${getQETStyle(el)}/>\n`;
    });

    description.querySelectorAll('circle').forEach(el => {
        const r  = parseFloat(el.getAttribute('diameter')) / 2;
        const cx = parseFloat(el.getAttribute('x')) + r;
        const cy = parseFloat(el.getAttribute('y')) + r;
        importedHTML += `<circle cx="${cx}" cy="${cy}" r="${r}" ${getQETStyle(el)}/>\n`;
    });

    description.querySelectorAll('ellipse').forEach(el => {
        const rx = parseFloat(el.getAttribute('width'))  / 2;
        const ry = parseFloat(el.getAttribute('height')) / 2;
        const cx = parseFloat(el.getAttribute('x')) + rx;
        const cy = parseFloat(el.getAttribute('y')) + ry;
        importedHTML += `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" ${getQETStyle(el)}/>\n`;
    });

    description.querySelectorAll('polygon').forEach(el => {
        const closed = el.getAttribute('closed') !== 'false';
        const pts = [];
        let i = 1;
        while (el.getAttribute(`x${i}`) !== null) {
            pts.push(`${el.getAttribute(`x${i}`)},${el.getAttribute(`y${i}`)}`);
            i++;
        }
        const tag = closed ? 'polygon' : 'polyline';
        importedHTML += `<${tag} points="${pts.join(' ')}" ${getQETStyle(el)}/>\n`;
    });

    description.querySelectorAll('terminal').forEach((el, index) => {
        const x = parseFloat(el.getAttribute('x'));
        const y = parseFloat(el.getAttribute('y'));
        importedHTML += `<circle cx="${x}" cy="${y}" r="4" fill="red" class="port"/>\n`;
        importedHTML += `<text x="${x + 6}" y="${y + 3}" font-size="9" font-family="Arial" fill="#34495e" style="pointer-events:none; font-weight:bold;">${index + 1}</text>\n`;
    });

    window.editorCanvas.insertAdjacentHTML('beforeend', importedHTML);
}

function parseSVGFile(text, fallbackName) {
    const parser = new DOMParser();
    const doc    = parser.parseFromString(text, 'image/svg+xml');
    const svgEl  = doc.querySelector('svg');
    if (!svgEl) { alert('Kein gültiges SVG-Element gefunden.'); return; }

    if (document.getElementById('compId')) document.getElementById('compId').value = fallbackName.toLowerCase().replace(/[^a-z0-9_]/g, '_');
    if (document.getElementById('compTitle')) document.getElementById('compTitle').value = fallbackName;

    svgEl.querySelectorAll('.port').forEach(el => el.remove());

    svgEl.querySelectorAll('line, rect, circle, path, polygon, polyline, ellipse').forEach(el => {
        if (!el.getAttribute('stroke')) el.setAttribute('stroke', 'black');
        if (!el.getAttribute('stroke-width') || parseFloat(el.getAttribute('stroke-width')) < 1.5)
            el.setAttribute('stroke-width', '2');
        if (!el.getAttribute('fill')) el.setAttribute('fill', 'none');
    });

    window.editorCanvas.insertAdjacentHTML('beforeend', svgEl.innerHTML);
}

function getAttributeBBox() {
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;

    Array.from(window.editorCanvas.children).forEach(el => {
        const tag = el.tagName.toLowerCase();
        if (tag === 'defs' || el.id === 'editor-grid-bg' || window.editorHandles.includes(el)) return;

        try {
            const b = el.getBBox();
            if (!b || (b.width === 0 && b.height === 0 && b.x === 0 && b.y === 0)) return;
            minX = Math.min(minX, b.x);
            minY = Math.min(minY, b.y);
            maxX = Math.max(maxX, b.x + b.width);
            maxY = Math.max(maxY, b.y + b.height);
        } catch (err) {
            console.warn('[getAttributeBBox] getBBox() fehlgeschlagen für <' + tag + '>:', err);
        }
    });

    if (!isFinite(minX)) {
        console.warn('[getAttributeBBox] Keine messbare Geometrie auf der Zeichenfläche gefunden.');
        return null;
    }
    return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
}

function flattenAndCenterCoordinates() {
    const box = getAttributeBBox();
    if (!box) return;

    const safeWidth  = box.width  || 1;
    const safeHeight = box.height || 1;

    const maxW  = window.OUTPUT_WIDTH  - 24;
    const maxH  = window.OUTPUT_HEIGHT - 24;
    const scale = Math.min(maxW / safeWidth, maxH / safeHeight, 1.0); 
    
    const dx = (window.OUTPUT_WIDTH - (box.width * scale)) / 2 - (box.x * scale);
    const dy = (window.OUTPUT_HEIGHT - (box.height * scale)) / 2 - (box.y * scale);

    Array.from(window.editorCanvas.children).forEach(el => {
        const tag = el.tagName.toLowerCase();
        if (tag === 'defs' || el.id === 'editor-grid-bg') return;
        
        const snap = val => Math.round(val / (window.gridSize || 5)) * (window.gridSize || 5); 

        if (tag === 'line') {
            el.setAttribute('x1', snap(parseFloat(el.getAttribute('x1')) * scale + dx));
            el.setAttribute('y1', snap(parseFloat(el.getAttribute('y1')) * scale + dy));
            el.setAttribute('x2', snap(parseFloat(el.getAttribute('x2')) * scale + dx));
            el.setAttribute('y2', snap(parseFloat(el.getAttribute('y2')) * scale + dy));
        } else if (tag === 'rect') {
            el.setAttribute('x', snap(parseFloat(el.getAttribute('x')) * scale + dx));
            el.setAttribute('y', snap(parseFloat(el.getAttribute('y')) * scale + dy));
            el.setAttribute('width', snap(parseFloat(el.getAttribute('width')) * scale));
            el.setAttribute('height', snap(parseFloat(el.getAttribute('height')) * scale));
        } else if (tag === 'circle') {
            const cx = parseFloat(el.getAttribute('cx') ?? el.getAttribute('x') ?? 0);
            const cy = parseFloat(el.getAttribute('cy') ?? el.getAttribute('y') ?? 0);
            el.setAttribute('cx', snap(cx * scale + dx));
            el.setAttribute('cy', snap(cy * scale + dy));
            el.setAttribute('r',  snap(parseFloat(el.getAttribute('r') || 0) * scale));
        } else if (tag === 'ellipse') {
            el.setAttribute('cx', snap(parseFloat(el.getAttribute('cx')) * scale + dx));
            el.setAttribute('cy', snap(parseFloat(el.getAttribute('cy')) * scale + dy));
            el.setAttribute('rx', snap(parseFloat(el.getAttribute('rx')) * scale));
            el.setAttribute('ry', snap(parseFloat(el.getAttribute('ry')) * scale));
        } else if (tag === 'polygon' || tag === 'polyline') {
            const newPairs = (el.getAttribute('points') || '').trim().split(/\s+/).map(p => {
                const pts = p.split(',');
                return pts.length === 2 ? `${snap(parseFloat(pts[0]) * scale + dx)},${snap(parseFloat(pts[1]) * scale + dy)}` : p;
            });
            el.setAttribute('points', newPairs.join(' '));
        } else if (tag === 'text') {
            el.setAttribute('x', snap(parseFloat(el.getAttribute('x')) * scale + dx));
            el.setAttribute('y', snap(parseFloat(el.getAttribute('y')) * scale + dy));
        } else if (tag === 'path') {
            let isX = true;
            const newD = (el.getAttribute('d') || '').replace(/-?[\d.]+/g, (match) => {
                const val = parseFloat(match);
                let newVal;
                if (isX) newVal = snap(val * scale + dx);
                else     newVal = snap(val * scale + dy);
                isX = !isX;
                return newVal;
            });
            el.setAttribute('d', newD);
        } else {
            const existing = el.getAttribute('transform');
            const newTransform = `translate(${dx} ${dy}) scale(${scale})` + (existing ? ' ' + existing : '');
            el.setAttribute('transform', newTransform);
        }
    });
}