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

// Globale Variablen für die Punkt-Bearbeitung
window.activeHandleIndex = null;
window.activePointUpdater = null;

// ── 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: 45px; text-align: center; }
            .ed-prop-val:focus { border-color: #3498db; outline: none; background: #2c3e50; }
            .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="number" id="ed-prop-x" class="ed-prop-val">
            <span class="ed-prop-label">Y:</span> <input type="number" id="ed-prop-y" class="ed-prop-val">
            <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);

        // --- INTELLIGENTES KOORDINATEN UPDATE ---
        function handleManualCoordChange() {
            if (!window.selectedEditorElement) return;
            const newX = parseFloat(document.getElementById('ed-prop-x').value);
            const newY = parseFloat(document.getElementById('ed-prop-y').value);
            
            if (isNaN(newX) || isNaN(newY)) return;
            
            // Wenn ein einzelner Punkt aktiv ist, verschiebe NUR diesen Punkt!
            if (window.activeHandleIndex !== null && window.activePointUpdater) {
                window.activePointUpdater(newX, newY);
            } else {
                // Keinen Punkt gewählt? Dann verschiebe das ganze Bauteil
                const el = window.selectedEditorElement;
                const bbox = el.getBBox();
                const dx = newX - bbox.x;
                const dy = newY - bbox.y;
                
                if (dx === 0 && dy === 0) return;
                
                window.shiftElementManually(el, dx, dy);
                if (typeof window.renderHandles === 'function') window.renderHandles();
                if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
            }
        }

        const inputX = document.getElementById('ed-prop-x');
        const inputY = document.getElementById('ed-prop-y');
        inputX.addEventListener('change', handleManualCoordChange);
        inputY.addEventListener('change', handleManualCoordChange);
        // Bei Enter sofort das Tippen beenden und übernehmen
        inputX.addEventListener('keydown', (e) => { if (e.key === 'Enter') e.target.blur(); });
        inputY.addEventListener('keydown', (e) => { if (e.key === 'Enter') e.target.blur(); });
        // -------------------------------------------------------------

        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;
            let currentTransform = el.getAttribute('transform') || '';
            
            if (currentTransform.includes('scale(-1, 1)')) {
                const cleanTransform = currentTransform.replace(/translate\([^)]+\)\s*scale\(-1,\s*1\)/, '').trim();
                el.setAttribute('transform', cleanTransform);
            } else {
                const bbox = el.getBBox();
                const cx = bbox.x + bbox.width / 2;
                el.setAttribute('transform', `translate(${cx * 2}, 0) scale(-1, 1) ${currentTransform}`.trim());
            }
            if (typeof window.renderHandles === 'function') window.renderHandles();
            if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
        });
    }

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

// Aktualisiert die Anzeige (aber NICHT, wenn man gerade tippt)
window.updateCoordinatesDisplay = function(x, y) {
    const px = document.getElementById('ed-prop-x');
    const py = document.getElementById('ed-prop-y');
    if (px && py && document.activeElement !== px && document.activeElement !== py) {
        px.value = Math.round(x);
        py.value = Math.round(y);
    }
};

window.shiftElementManually = function(el, dx, dy) {
    const tag = el.tagName.toLowerCase();
    if (tag === 'line') { 
        el.setAttribute('x1', parseFloat(el.getAttribute('x1')) + dx); 
        el.setAttribute('y1', parseFloat(el.getAttribute('y1')) + dy); 
        el.setAttribute('x2', parseFloat(el.getAttribute('x2')) + dx); 
        el.setAttribute('y2', parseFloat(el.getAttribute('y2')) + dy); 
    }
    else if (tag === 'rect' || tag === 'text') { 
        el.setAttribute('x', parseFloat(el.getAttribute('x') || 0) + dx); 
        el.setAttribute('y', parseFloat(el.getAttribute('y') || 0) + dy); 
    }
    else if (tag === 'circle' || tag === 'ellipse') { 
        el.setAttribute('cx', parseFloat(el.getAttribute('cx') || 0) + dx); 
        el.setAttribute('cy', parseFloat(el.getAttribute('cy') || 0) + dy); 
    }
    else if (tag === 'polyline' || tag === 'polygon') {
        const pts = (el.getAttribute('points') || '').trim().replace(/,/g, ' ').split(/\s+/).map(Number);
        const newPts = []; 
        for (let i = 0; i < pts.length; i += 2) newPts.push(`${pts[i] + dx},${pts[i + 1] + dy}`);
        el.setAttribute('points', newPts.join(' '));
    }
    else if (tag === 'path') {
        const match = el.getAttribute('d').match(/M\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+C\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?),\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?),\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/);
        if (match) {
            const pts = match.slice(1).map(Number);
            const newPts = [];
            for (let i = 0; i < pts.length; i += 2) {
                newPts.push(pts[i] + dx); newPts.push(pts[i + 1] + dy);
            }
            el.setAttribute('d', `M ${newPts[0]} ${newPts[1]} C ${newPts[2]} ${newPts[3]}, ${newPts[4]} ${newPts[5]}, ${newPts[6]} ${newPts[7]}`);
        }
    }
};

// ── AUSWAHL LOGIK ──
window.deselectElement = function() {
    if (window.selectedEditorElement) window.selectedEditorElement.removeAttribute('opacity');
    window.selectedEditorElement = null;
    window.activeHandleIndex = null;
    window.activePointUpdater = 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';
    
    window.activeHandleIndex = null;
    window.activePointUpdater = null;
    
    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 & blauen 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();
            });
        }
    } else if (tag === 'path') {
        const match = el.getAttribute('d').match(/M\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+C\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?),\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?),\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/);
        if (match) {
            const pts = match.slice(1).map(Number);
            const updatePath = () => {
                el.setAttribute('d', `M ${pts[0]} ${pts[1]} C ${pts[2]} ${pts[3]}, ${pts[4]} ${pts[5]}, ${pts[6]} ${pts[7]}`);
                window.renderHandles(); 
                if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
            };

            const line1 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
            line1.setAttribute('x1', pts[0]); line1.setAttribute('y1', pts[1]);
            line1.setAttribute('x2', pts[2]); line1.setAttribute('y2', pts[3]);
            line1.setAttribute('stroke', '#3498db'); line1.setAttribute('stroke-dasharray', '2,2');
            line1.style.pointerEvents = 'none'; window.editorCanvas.appendChild(line1); window.editorHandles.push(line1);

            const line2 = document.createElementNS('http://www.w3.org/2000/svg', 'line');
            line2.setAttribute('x1', pts[6]); line2.setAttribute('y1', pts[7]);
            line2.setAttribute('x2', pts[4]); line2.setAttribute('y2', pts[5]);
            line2.setAttribute('stroke', '#3498db'); line2.setAttribute('stroke-dasharray', '2,2');
            line2.style.pointerEvents = 'none'; window.editorCanvas.appendChild(line2); window.editorHandles.push(line2);

            window.createHandle(pts[2], pts[3], (nx, ny) => { pts[2] = nx; pts[3] = ny; window.updateCoordinatesDisplay(nx, ny); updatePath(); }, true);
            window.createHandle(pts[4], pts[5], (nx, ny) => { pts[4] = nx; pts[5] = ny; window.updateCoordinatesDisplay(nx, ny); updatePath(); }, true);
            window.createHandle(pts[0], pts[1], (nx, ny) => { pts[0] = nx; pts[1] = ny; window.updateCoordinatesDisplay(nx, ny); updatePath(); });
            window.createHandle(pts[6], pts[7], (nx, ny) => { pts[6] = nx; pts[7] = ny; window.updateCoordinatesDisplay(nx, ny); updatePath(); });
        }
    }
};

window.createHandle = function(x, y, onDrag, isBlue = false) {
    const hIndex = window.editorHandles.length;
    const h = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    h.setAttribute('cx', x); 
    h.setAttribute('cy', y); 
    h.setAttribute('r', '4');
    h.setAttribute('fill', isBlue ? '#3498db' : '#e74c3c');
    
    // Überprüft, ob dieser Punkt gerade aktiv ist (Gelber Rand)
    if (window.activeHandleIndex === hIndex) {
        h.setAttribute('stroke', '#f1c40f');
        h.setAttribute('stroke-width', '2.5');
        window.activePointUpdater = onDrag; 
    } else {
        h.setAttribute('stroke', '#fff');
        h.setAttribute('stroke-width', '1');
    }
    h.style.cursor = 'move';
    
    h.addEventListener('mousedown', (e) => { 
        e.stopPropagation(); 
        if (window.currentTool !== 'select') return; 
        
        // Entfernt den gelben Rand von allen anderen Punkten (außer den Hilfslinien)
        window.editorHandles.forEach(otherH => {
            if (otherH.tagName.toLowerCase() === 'circle') {
                otherH.setAttribute('stroke', '#fff');
                otherH.setAttribute('stroke-width', '1');
            }
        });
        // Macht diesen Punkt gelb
        h.setAttribute('stroke', '#f1c40f');
        h.setAttribute('stroke-width', '2.5');
        
        // Setzt den Fokus auf genau diesen Punkt!
        window.activeHandleIndex = hIndex;
        window.activePointUpdater = onDrag;
        window.updateCoordinatesDisplay(x, y);

        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) };
    else if (tag === 'path') {
        const match = el.getAttribute('d').match(/M\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+C\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?),\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?),\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/);
        if (match) initData = { isBezier: true, pts: match.slice(1).map(Number) };
    }
    
    window.activeDragHandle = (nx, ny) => {
        const dx = nx - startCoords.x;
        const dy = ny - startCoords.y;
        window.shiftElementManually(el, dx, dy);
        
        // BBox ändert sich beim Komplett-Verschieben
        const bbox = el.getBBox();
        window.updateCoordinatesDisplay(bbox.x, bbox.y);
        window.renderHandles();
    };
};