// ════════════════════════════════════════════════════════════════════════════
//  EDITOR PROPERTIES (editor_properties.js) – Auswahl, Handles & Eigenschaften
// ════════════════════════════════════════════════════════════════════════════

// ── UI-Injektion für Eigenschaften (Koordinaten, Spiegeln, Style) ──
(function injectPropertiesUI() {
    function inject() {
        const toolbar = document.getElementById('editor-toolbar');
        if (!toolbar) return;

        const s = document.createElement('style');
        s.innerHTML = `
            #ed-prop-panel { display: none; align-items: center; gap: 8px; margin-left: 15px; padding-left: 15px; border-left: 2px solid #34495e; }
            .ed-prop-label { color: #f1c40f; font-size: 11px; font-weight: bold; font-family: Arial; }
            .ed-prop-val { background: #1a252f; color: #2ecc71; border: 1px solid #7f8c8d; border-radius: 4px; padding: 2px 6px; font-size: 11px; width: 40px; text-align: center; }
            .ed-prop-btn { background: #34495e; color: white; border: 1px solid #7f8c8d; border-radius: 4px; padding: 2px 8px; font-size: 11px; cursor: pointer; }
            .ed-prop-btn:hover { background: #2c3e50; border-color: #bdc3c7; }
        `;
        document.head.appendChild(s);

        const propPanel = document.createElement('div');
        propPanel.id = 'ed-prop-panel';
        propPanel.innerHTML = `
            <span class="ed-prop-label">📍 X:</span> <input type="text" id="ed-prop-x" class="ed-prop-val" readonly>
            <span class="ed-prop-label">Y:</span> <input type="text" id="ed-prop-y" class="ed-prop-val" readonly>
            <button id="btn-prop-dash" class="ed-prop-btn">--- Linie</button>
            <button id="btn-prop-fill" class="ed-prop-btn">⬛ Füllen</button>
            <button id="btn-prop-flip" class="ed-prop-btn">↔️ Spiegeln</button>
        `;
        toolbar.appendChild(propPanel);

        // Events für die nachträgliche Bearbeitung
        document.getElementById('btn-prop-dash').addEventListener('click', () => {
            if (!window.selectedEditorElement) return;
            const el = window.selectedEditorElement;
            if (el.hasAttribute('stroke-dasharray')) {
                el.removeAttribute('stroke-dasharray');
            } else {
                el.setAttribute('stroke-dasharray', '4,4');
            }
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
        });

        document.getElementById('btn-prop-fill').addEventListener('click', () => {
            if (!window.selectedEditorElement) return;
            const el = window.selectedEditorElement;
            const currentFill = el.getAttribute('fill');
            if (currentFill === 'none' || !currentFill) {
                el.setAttribute('fill', 'black');
            } else {
                el.setAttribute('fill', 'none');
            }
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
        });

        document.getElementById('btn-prop-flip').addEventListener('click', () => {
            if (!window.selectedEditorElement) return;
            const el = window.selectedEditorElement;
            // Aktuelle Transformation auslesen und umkehren
            let currentTransform = el.getAttribute('transform') || '';
            if (currentTransform.includes('scale(-1, 1)')) {
                el.setAttribute('transform', currentTransform.replace('scale(-1, 1)', '').trim());
            } else {
                // Ermittle die Mitte des Elements für sauberes Spiegeln
                const bbox = el.getBBox();
                const cx = bbox.x + bbox.width / 2;
                el.setAttribute('transform', `translate(${cx * 2}, 0) scale(-1, 1) ${currentTransform}`);
            }
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', inject);
    } else {
        inject();
    }
})();

// Aktualisiert die Koordinaten-Anzeige oben im Menü
window.updateCoordinatesDisplay = function(x, y) {
    const px = document.getElementById('ed-prop-x');
    const py = document.getElementById('ed-prop-y');
    if (px && py) {
        px.value = Math.round(x);
        py.value = Math.round(y);
    }
};

// ── AUSWAHL LOGIK ──
window.deselectElement = function() {
    if (window.selectedEditorElement) {
        window.selectedEditorElement.removeAttribute('opacity');
    }
    window.selectedEditorElement = null;
    window.editorHandles.forEach(h => h.remove()); 
    window.editorHandles = [];
    
    const panel = document.getElementById('ed-prop-panel');
    if (panel) panel.style.display = 'none';
};

window.selectElement = function(el) {
    window.deselectElement(); 
    window.selectedEditorElement = el; 
    el.setAttribute('opacity', '0.4'); 
    
    const panel = document.getElementById('ed-prop-panel');
    if (panel) panel.style.display = 'flex';
    
    // Basis-Koordinaten für die Anzeige ermitteln
    const bbox = el.getBBox();
    window.updateCoordinatesDisplay(bbox.x, bbox.y);
    
    window.renderHandles();
};

const btnDeleteEl = document.getElementById('btn-delete-element');
if (btnDeleteEl) {
    btnDeleteEl.addEventListener('click', () => {
        if (window.selectedEditorElement) {
            window.selectedEditorElement.remove(); 
            window.deselectElement(); 
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
        }
    });
}

document.addEventListener('keydown', (e) => {
    if ((e.key === 'Delete' || e.key === 'Backspace') && 
        window.fullscreenEditor && !window.fullscreenEditor.classList.contains('hidden') && 
        window.selectedEditorElement && 
        e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA') {
        
        e.preventDefault(); 
        window.selectedEditorElement.remove(); 
        window.deselectElement(); 
        if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
    }
});

// ── HANDLES (Die roten Punkte zum Bearbeiten) ──
window.renderHandles = function() {
    window.editorHandles.forEach(h => h.remove()); 
    window.editorHandles = [];
    const el = window.selectedEditorElement; 
    if (!el) return;
    const tag = el.tagName.toLowerCase();

    if (tag === 'line') {
        window.createHandle(+el.getAttribute('x1'), +el.getAttribute('y1'), (nx, ny) => { 
            el.setAttribute('x1', nx); el.setAttribute('y1', ny); 
            window.updateCoordinatesDisplay(nx, ny);
            window.renderHandles(); 
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate(); 
        });
        window.createHandle(+el.getAttribute('x2'), +el.getAttribute('y2'), (nx, ny) => { 
            el.setAttribute('x2', nx); el.setAttribute('y2', ny); 
            window.updateCoordinatesDisplay(nx, ny);
            window.renderHandles(); 
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate(); 
        });
    } else if (tag === 'rect') {
        const x = parseFloat(el.getAttribute('x')) || 0;
        const y = parseFloat(el.getAttribute('y')) || 0;
        const w = parseFloat(el.getAttribute('width')) || 0;
        const h = parseFloat(el.getAttribute('height')) || 0;
        
        window.createHandle(x, y, (nx, ny) => { 
            el.setAttribute('x', nx); el.setAttribute('y', ny); 
            el.setAttribute('width', Math.max(1, w + (x - nx))); 
            el.setAttribute('height', Math.max(1, h + (y - ny))); 
            window.updateCoordinatesDisplay(nx, ny);
            window.renderHandles(); 
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate(); 
        });
        window.createHandle(x + w, y + h, (nx, ny) => { 
            el.setAttribute('width', Math.max(1, nx - x)); 
            el.setAttribute('height', Math.max(1, ny - y)); 
            window.updateCoordinatesDisplay(nx, ny);
            window.renderHandles(); 
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate(); 
        });
    } else if (tag === 'circle' && !el.classList.contains('port')) {
        const cx = parseFloat(el.getAttribute('cx')) || 0;
        const cy = parseFloat(el.getAttribute('cy')) || 0;
        const r = parseFloat(el.getAttribute('r')) || 0;
        
        window.createHandle(cx + r, cy, (nx) => { 
            el.setAttribute('r', Math.max(1, Math.abs(nx - cx))); 
            window.updateCoordinatesDisplay(nx, cy);
            window.renderHandles(); 
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate(); 
        });
    } else if (tag === 'polyline' || tag === 'polygon') {
        const ptsArr = (el.getAttribute('points') || '').trim().replace(/,/g, ' ').split(/\s+/).map(Number);
        for (let i = 0; i < ptsArr.length; i += 2) {
            const ptIdx = i;
            window.createHandle(ptsArr[i], ptsArr[i + 1], (nx, ny) => {
                const cur = (el.getAttribute('points') || '').trim().replace(/,/g, ' ').split(/\s+/).map(Number);
                cur[ptIdx] = nx; 
                cur[ptIdx + 1] = ny;
                const newPts = []; 
                for (let j = 0; j < cur.length; j += 2) newPts.push(`${cur[j]},${cur[j + 1]}`);
                el.setAttribute('points', newPts.join(' ')); 
                window.updateCoordinatesDisplay(nx, ny);
                window.renderHandles(); 
                if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
            });
        }
    }
};

window.createHandle = function(x, y, onDrag) {
    const h = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    h.setAttribute('cx', x); h.setAttribute('cy', y); h.setAttribute('r', '3.5');
    h.setAttribute('fill', '#e74c3c'); h.setAttribute('stroke', '#fff'); h.setAttribute('stroke-width', '1'); h.style.cursor = 'move';
    
    h.addEventListener('mousedown', (e) => { 
        e.stopPropagation(); 
        if (window.currentTool !== 'select') return; 
        window.activeDragHandle = onDrag; 
    });
    
    window.editorCanvas.appendChild(h); 
    window.editorHandles.push(h);
};

window.setupElementMove = function(el, startCoords) {
    const tag = el.tagName.toLowerCase();
    let initData = {};
    if (tag === 'line') initData = { x1: parseFloat(el.getAttribute('x1')) || 0, y1: parseFloat(el.getAttribute('y1')) || 0, x2: parseFloat(el.getAttribute('x2')) || 0, y2: parseFloat(el.getAttribute('y2')) || 0 };
    else if (tag === 'rect' || tag === 'text') initData = { x: parseFloat(el.getAttribute('x')) || 0, y: parseFloat(el.getAttribute('y')) || 0 };
    else if (tag === 'circle' || tag === 'ellipse') initData = { cx: parseFloat(el.getAttribute('cx')) || 0, cy: parseFloat(el.getAttribute('cy')) || 0 };
    else if (tag === 'polyline' || tag === 'polygon') initData = { pts: (el.getAttribute('points') || '').trim().replace(/,/g, ' ').split(/\s+/).map(Number) };
    
    window.activeDragHandle = (nx, ny) => {
        const dx = nx - startCoords.x;
        const dy = ny - startCoords.y;
        
        if (tag === 'line') { 
            el.setAttribute('x1', initData.x1 + dx); el.setAttribute('y1', initData.y1 + dy); 
            el.setAttribute('x2', initData.x2 + dx); el.setAttribute('y2', initData.y2 + dy); 
        }
        else if (tag === 'rect' || tag === 'text') { 
            el.setAttribute('x', initData.x + dx); el.setAttribute('y', initData.y + dy); 
        }
        else if (tag === 'circle' || tag === 'ellipse') { 
            el.setAttribute('cx', initData.cx + dx); el.setAttribute('cy', initData.cy + dy); 
        }
        else if (tag === 'polyline' || tag === 'polygon') {
            const newPts = []; 
            for (let i = 0; i < initData.pts.length; i += 2) {
                newPts.push(`${initData.pts[i] + dx},${initData.pts[i + 1] + dy}`);
            }
            el.setAttribute('points', newPts.join(' '));
        }
        
        window.updateCoordinatesDisplay(nx, ny);
        window.renderHandles();
    };
};