// ════════════════════════════════════════════════════════════════════════════
//  EDITOR EXPORT (editor_export.js) – Code Preview, Ports & Bauteil speichern
// ════════════════════════════════════════════════════════════════════════════

window.updatePortsSidebar = function() {
    const portsList = document.getElementById('ports-list');
    if (!portsList) return;
    
    portsList.innerHTML = '';
    const ports = window.editorCanvas.querySelectorAll('.port');
    
    if (ports.length === 0) {
        portsList.innerHTML = '<p style="color:#bdc3c7; font-size:12px; font-style:italic;">Keine Anschlüsse geladen.</p>';
        return;
    }
    
    ports.forEach((port, idx) => {
        const cx = parseFloat(port.getAttribute('cx') || port.getAttribute('x'));
        const cy = parseFloat(port.getAttribute('cy') || port.getAttribute('y'));
        let labelText = (idx + 1).toString(); 
        
        const texts = window.editorCanvas.querySelectorAll('text');
        texts.forEach(t => {
            const tx = parseFloat(t.getAttribute('x'));
            const ty = parseFloat(t.getAttribute('y'));
            if (Math.abs(tx - cx) < 15 && Math.abs(ty - cy) < 15) {
                labelText = t.textContent;
            }
        });

        const div = document.createElement('div');
        div.style.cssText = 'background: #2c3e50; padding: 8px; border-radius: 4px; display: flex; justify-content: space-between; align-items: center; gap: 8px; border-left: 4px solid #e74c3c;';
        div.innerHTML = `
            <span style="font-size:12px;">Knoten ${idx + 1}</span>
            <span style="background: #34495e; padding: 2px 6px; border-radius: 3px; font-size: 11px;">${labelText}</span>
        `;
        portsList.appendChild(div);
    });
};

window.getExportableChildren = function() {
    return Array.from(window.editorCanvas.children).filter(child => {
        if (child.tagName.toLowerCase() === 'defs') return false;
        if (window.editorHandles.includes(child)) return false;
        return true;
    });
};

window.getExportSVGContent = function() {
    if (window.selectedEditorElement) window.selectedEditorElement.removeAttribute('opacity');
    window.editorHandles.forEach(h => { h.style.display = 'none'; });

    let svgContent = window.getExportableChildren().map(el => el.outerHTML).join('');

    window.editorHandles.forEach(h => { h.style.display = ''; });
    if (window.selectedEditorElement) window.selectedEditorElement.setAttribute('opacity', '0.4');

    svgContent = svgContent.replace(/></g, '>\n  <');
    if (svgContent.length > 0) svgContent = '  ' + svgContent;
    return svgContent;
};

window.updateCodePreview = function() {
    if (window.codePanel && window.codePanel.classList.contains('hidden')) return;
    const svgContent = window.getExportSVGContent();
    if (window.codeOutput) {
        window.codeOutput.value = `<svg viewBox="${window.OUTPUT_VIEWBOX}" width="${window.OUTPUT_WIDTH}" height="${window.OUTPUT_HEIGHT}" class="symbol">\n${svgContent}\n</svg>`;
    }
    window.updatePortsSidebar();
};

window.schedulePreviewUpdate = function() {
    if (window._previewTimer) clearTimeout(window._previewTimer);
    window._previewTimer = setTimeout(window.updateCodePreview, 120);
};

const btnCopyCode = document.getElementById('btn-copy-code');
if (btnCopyCode) {
    btnCopyCode.addEventListener('click', async () => {
        try {
            await navigator.clipboard.writeText(window.codeOutput.value);
        } catch {
            window.codeOutput.select();
            document.execCommand('copy');
        }
        const origText = btnCopyCode.innerText;
        btnCopyCode.innerText = '✅ Kopiert!';
        setTimeout(() => { btnCopyCode.innerText = origText; }, 2000);
    });
}

const btnSaveComp = document.getElementById('btn-save-comp');
if (btnSaveComp) {
    btnSaveComp.addEventListener('click', () => {
        if (typeof window.deselectElement === 'function') window.deselectElement();
        
        const inputId = document.getElementById('compId');
        const inputFolder = document.getElementById('compFolder');
        const inputTitle = document.getElementById('compTitle');
        
        const id = inputId && inputId.value.trim() !== '' ? inputId.value.trim().replace(/\s+/g, '_') : 'custom_' + Date.now();
        const folder = inputFolder ? inputFolder.value : 'custom';
        const title = inputTitle && inputTitle.value.trim() !== '' ? inputTitle.value.trim() : 'Neues Bauteil';

        const svgContentForStorage = window.getExportableChildren().map(el => el.outerHTML).join('').trim();

        if (window.editingInstance) {
            const svg = window.editingInstance.querySelector('svg.symbol') || window.editingInstance.querySelector('svg');
            if (svg) {
                svg.classList.add('symbol');
                svg.setAttribute('viewBox', window.OUTPUT_VIEWBOX);
                svg.setAttribute('width', window.OUTPUT_WIDTH);
                svg.setAttribute('height', window.OUTPUT_HEIGHT);
                svg.innerHTML = svgContentForStorage;
            }
            if (typeof updateCables === 'function') updateCables();
            if (typeof addHistory === 'function') addHistory('Bauteil auf Plan geändert');
        } else {
            const componentConfig = {
                id: id,
                folder: folder,
                title: title,
                defaultData: {},
                svg: `<svg viewBox="${window.OUTPUT_VIEWBOX}" width="${window.OUTPUT_WIDTH}" height="${window.OUTPUT_HEIGHT}" class="symbol" xmlns="http://www.w3.org/2000/svg">\n${svgContentForStorage}\n</svg>`
            };

            if (window.ComponentRegistry) window.ComponentRegistry.register(id, componentConfig);

            let currentDB = [];
            try { currentDB = JSON.parse(localStorage.getItem('customComponents') || '[]'); } catch {}

            const idx = currentDB.findIndex(c => c.id === id);
            if (idx !== -1) currentDB[idx] = componentConfig;
            else currentDB.push(componentConfig);

            localStorage.setItem('customComponents', JSON.stringify(currentDB));
            
            if (window.ComponentRegistry) window.ComponentRegistry.buildSidebar(); 
            if (typeof addHistory === 'function') addHistory(`Bauteil "${title}" gesichert`);
        }

        if (window.fullscreenEditor) window.fullscreenEditor.classList.add('hidden');
    });
}

window.openEditorForComponent = function (compEl) {
    if (!window.fullscreenEditor || !window.editorCanvas) return;
    window.editingComponent = compEl; window.editingInstance = null;

    if (document.getElementById('compId')) document.getElementById('compId').value = compEl.dataset.type || '';
    if (document.getElementById('compTitle')) document.getElementById('compTitle').value = compEl.title || '';
    
    if (window.ComponentRegistry && window.ComponentRegistry.definitions[compEl.dataset.type]) {
        const folder = window.ComponentRegistry.definitions[compEl.dataset.type].folder;
        if (document.getElementById('compFolder')) document.getElementById('compFolder').value = folder || 'custom';
    }

    const svgEl = compEl.querySelector('svg.symbol');
    if (svgEl) {
        Array.from(window.editorCanvas.children).forEach(child => {
            if (child.tagName.toLowerCase() !== 'defs') child.remove();
        });
        window.editorCanvas.insertAdjacentHTML('beforeend', svgEl.innerHTML);
    }

    if (window.toolBtns) 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';

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

    setTimeout(() => {
        if (svgEl && typeof flattenAndCenterCoordinates === 'function') {
            flattenAndCenterCoordinates();
        }
        window.autoFitZoom();
        window.updateCodePreview();
    }, 10);
};

window.openEditorForInstance = function (el) {
    if (!window.fullscreenEditor || !window.editorCanvas) return;
    window.editingComponent = null; window.editingInstance = el;

    const svgEl = el.querySelector('svg.symbol');
    if (svgEl) {
        Array.from(window.editorCanvas.children).forEach(child => {
            if (child.tagName.toLowerCase() !== 'defs') child.remove();
        });
        window.editorCanvas.insertAdjacentHTML('beforeend', svgEl.innerHTML);
    }

    if (window.toolBtns) 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';

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

    setTimeout(() => {
        if (svgEl && typeof flattenAndCenterCoordinates === 'function') {
            flattenAndCenterCoordinates();
        }
        window.autoFitZoom();
        window.updateCodePreview();
    }, 10);
};

document.addEventListener('click', (e) => {
    const editBtn = e.target.closest('.edit-comp-btn');
    if (editBtn) {
        e.stopPropagation(); e.preventDefault();
        const compItem = editBtn.closest('.component-item');
        if (compItem) {
            window.openEditorForComponent(compItem);
            if (typeof addHistory === 'function') addHistory('Editor für Vorlage geöffnet');
        }
    }
}, true);