// ════════════════════════════════════════════════════════════════════════════
//  EDITOR TOOLS (editor_tools.js) – Maus-Events, Snapping & Zeichen-Logik
// ════════════════════════════════════════════════════════════════════════════

// Hilfsfunktion: Strikte Rasterkoordinaten ermitteln
window.getMouseCoords = function(e) {
    if (!window.editorCanvas) return {x:0, y:0};
    const pt  = window.editorCanvas.createSVGPoint();
    pt.x = e.clientX; pt.y = e.clientY;
    const ctm = window.editorCanvas.getScreenCTM();
    if (!ctm) return { x: 0, y: 0 };
    const cursor = pt.matrixTransform(ctm.inverse());
    
    return {
        x: Math.round(cursor.x / window.gridSize) * window.gridSize,
        y: Math.round(cursor.y / window.gridSize) * window.gridSize
    };
};

// Hilfsfunktionen für "Punkt einfügen" Mathe
window.sqr = function(x) { return x * x; };
window.dist2 = function(v, w) { return window.sqr(v.x - w.x) + window.sqr(v.y - w.y); };
window.distToSegmentSquared = function(p, v, w) {
    const l2 = window.dist2(v, w);
    if (l2 === 0) return window.dist2(p, v);
    const t = Math.max(0, Math.min(1, ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2));
    return window.dist2(p, { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) });
};

// Event Delegation für Tool-Buttons
const toolbar = document.getElementById('editor-toolbar');
if (toolbar) {
    toolbar.addEventListener('click', (e) => {
        const btn = e.target.closest('.editor-btn[data-tool]');
        if (!btn) return;
        
        if(typeof window.updateToolBtns === 'function') window.updateToolBtns(); 
        if (window.toolBtns) {
            window.toolBtns.forEach(b => {
                b.classList.remove('active');
                b.style.backgroundColor = '';
                b.style.color = '';
            });
        }
        btn.classList.add('active');
        
        const tool = btn.dataset.tool;
        if (tool === 'select') {
            btn.style.backgroundColor = '#f1c40f';
            btn.style.color = 'black';
        } else if (tool === 'add-point') {
            btn.style.backgroundColor = '#2ecc71';
            btn.style.color = 'white';
        } else if (tool === 'port') {
            btn.style.backgroundColor = '#ff4757';
            btn.style.color = 'white';
        } else if (tool === 'text') {
            btn.style.backgroundColor = '#3498db';
            btn.style.color = 'white';
        } else if (tool === 'bezier') {
            btn.style.backgroundColor = '#9b59b6';
            btn.style.color = 'white';
        } else {
            btn.style.backgroundColor = '#34495e';
            btn.style.color = 'white';
        }
        window.currentTool = tool;
        if (typeof window.deselectElement === 'function') window.deselectElement();
    });
}

// "Neues Bauteil"-Button
const btnNewComp = document.getElementById('btn-new-comp');
if (btnNewComp) {
    btnNewComp.addEventListener('click', () => {
        window.editingComponent = null;
        window.editingInstance = null;
        
        if (document.getElementById('compId')) document.getElementById('compId').value = 'neues_bauteil_' + Date.now();
        if (document.getElementById('compTitle')) document.getElementById('compTitle').value = 'Neues Bauteil';
        if (document.getElementById('compFolder')) document.getElementById('compFolder').value = 'custom';
        
        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';
        
        if (typeof window.updateCodePreview === 'function') window.updateCodePreview();
        if (window.fullscreenEditor) window.fullscreenEditor.classList.remove('hidden');
        window.autoFitZoom();
    });
}

const btnClearCanvas = document.getElementById('btn-clear-canvas');
if (btnClearCanvas) {
    btnClearCanvas.addEventListener('click', () => {
        if (confirm('Zeichenfläche wirklich komplett leeren?')) {
            window.editorCanvas.innerHTML = '';
            if (typeof window.updateCodePreview === 'function') window.updateCodePreview();
        }
    });
}

const btnCloseEditor = document.getElementById('btn-close-editor');
if (btnCloseEditor) {
    btnCloseEditor.addEventListener('click', () => {
        if (typeof window.deselectElement === 'function') window.deselectElement();
        if (window.fullscreenEditor) window.fullscreenEditor.classList.add('hidden');
    });
}

// ── MAUS - AKTIONEN (Zeichnen & Snapping) ──
if (window.scaleWrapper) {
    window.scaleWrapper.addEventListener('mousedown', (e) => {
        if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA') e.preventDefault();

        const coords  = window.getMouseCoords(e);
        const tag = e.target.tagName.toLowerCase();
        const isShape = ['line', 'rect', 'circle', 'path', 'polygon', 'polyline', 'text', 'ellipse'].includes(tag);

        // FIX: Punkt Einfügen Logik wiederhergestellt!
        if (window.currentTool === 'add-point') {
            if (isShape && e.target !== window.editorCanvas) {
                if (tag === 'line') {
                    const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
                    poly.setAttribute('points', `${e.target.getAttribute('x1')},${e.target.getAttribute('y1')} ${coords.x},${coords.y} ${e.target.getAttribute('x2')},${e.target.getAttribute('y2')}`);
                    poly.setAttribute('stroke', e.target.getAttribute('stroke') || 'black');
                    poly.setAttribute('stroke-width', e.target.getAttribute('stroke-width') || '2');
                    poly.setAttribute('fill', e.target.getAttribute('fill') || 'none');
                    if (e.target.hasAttribute('stroke-dasharray')) poly.setAttribute('stroke-dasharray', e.target.getAttribute('stroke-dasharray'));
                    e.target.parentNode.replaceChild(poly, e.target);
                    document.querySelector('.editor-btn[data-tool="select"]').click();
                    if (typeof window.selectElement === 'function') window.selectElement(poly); 
                    if (typeof window.updateCodePreview === 'function') window.updateCodePreview();
                    return;
                } else if (tag === 'polyline' || tag === 'polygon') {
                    const ptsArr = (e.target.getAttribute('points') || '').trim().replace(/,/g, ' ').split(/\s+/).filter(Boolean).map(Number);
                    const pts = [];
                    for (let i = 0; i < ptsArr.length; i += 2) pts.push({ x: ptsArr[i], y: ptsArr[i + 1] });

                    let minDist = Infinity, insertIdx = 0;
                    const loop = tag === 'polygon' ? pts.length : pts.length - 1;
                    for (let i = 0; i < loop; i++) {
                        const d = window.distToSegmentSquared({ x: coords.x, y: coords.y }, pts[i], pts[(i + 1) % pts.length]);
                        if (d < minDist) { minDist = d; insertIdx = i + 1; }
                    }
                    pts.splice(insertIdx, 0, { x: coords.x, y: coords.y });
                    e.target.setAttribute('points', pts.map(p => `${p.x},${p.y}`).join(' '));
                    document.querySelector('.editor-btn[data-tool="select"]').click();
                    if (typeof window.selectElement === 'function') window.selectElement(e.target); 
                    if (typeof window.updateCodePreview === 'function') window.updateCodePreview();
                    return;
                }
            }
            return;
        }

        // Auswählen Werkzeug
        if (window.currentTool === 'select') {
            if (isShape && e.target !== window.editorCanvas && typeof window.selectElement === 'function') {
                window.selectElement(e.target);
                if (typeof window.setupElementMove === 'function') window.setupElementMove(e.target, coords);
            } else if (typeof window.deselectElement === 'function') {
                window.deselectElement();
            }
            return;
        }

        // Zeichen-Werkzeuge
        if (typeof window.deselectElement === 'function') window.deselectElement();
        window.isDrawing = true;
        window.startX = coords.x; 
        window.startY = coords.y;

        const chkFill = document.getElementById('tool-fill');
        const chkDash = document.getElementById('tool-dashed');
        const fillValue = (chkFill && chkFill.checked) ? 'black' : 'none';

        function applyDash(el) { if (chkDash && chkDash.checked) el.setAttribute('stroke-dasharray', '4,4'); }

        if (window.currentTool === 'line') {
            window.currentElement = document.createElementNS('http://www.w3.org/2000/svg', 'line');
            window.currentElement.setAttribute('x1', window.startX); window.currentElement.setAttribute('y1', window.startY);
            window.currentElement.setAttribute('x2', window.startX); window.currentElement.setAttribute('y2', window.startY);
            window.currentElement.setAttribute('stroke', 'black'); window.currentElement.setAttribute('stroke-width', '2');
            applyDash(window.currentElement);
        } else if (window.currentTool === 'rect') {
            window.currentElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
            window.currentElement.setAttribute('x', window.startX); window.currentElement.setAttribute('y', window.startY);
            window.currentElement.setAttribute('width', '0'); window.currentElement.setAttribute('height', '0');
            window.currentElement.setAttribute('fill', fillValue); window.currentElement.setAttribute('stroke', 'black'); window.currentElement.setAttribute('stroke-width', '2');
            applyDash(window.currentElement);
        } else if (window.currentTool === 'circle') {
            window.currentElement = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
            window.currentElement.setAttribute('cx', window.startX); window.currentElement.setAttribute('cy', window.startY);
            window.currentElement.setAttribute('r', '0');
            window.currentElement.setAttribute('fill', fillValue); window.currentElement.setAttribute('stroke', 'black'); window.currentElement.setAttribute('stroke-width', '2');
            applyDash(window.currentElement);
        } else if (window.currentTool === 'port') {
            const pCount = window.editorCanvas.querySelectorAll('.port').length + 1;
            const txt = prompt('Anschluss Bezeichnung:', pCount.toString());
            if (txt !== null) {
                const port = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
                port.setAttribute('cx', window.startX); port.setAttribute('cy', window.startY);
                port.setAttribute('r', '4'); port.setAttribute('fill', 'red'); port.setAttribute('class', 'port');
                window.editorCanvas.appendChild(port);
                
                const label = document.createElementNS('http://www.w3.org/2000/svg', 'text');
                label.setAttribute('x', window.startX + 6); label.setAttribute('y', window.startY + 3);
                label.setAttribute('font-size', '9'); label.setAttribute('font-family', 'Arial'); label.textContent = txt;
                label.style.pointerEvents = 'none';
                window.editorCanvas.appendChild(label);
            }
            window.isDrawing = false;
            if (typeof window.updateCodePreview === 'function') window.updateCodePreview();
            return;
        } else if (window.currentTool === 'text') {
            const txt = prompt('Text eingeben:', 'Text');
            if (txt !== null && txt.trim() !== '') {
                const textEl = document.createElementNS('http://www.w3.org/2000/svg', 'text');
                textEl.setAttribute('x', window.startX); 
                textEl.setAttribute('y', window.startY);
                textEl.setAttribute('font-size', window.currentFontSize || 10); 
                textEl.setAttribute('font-family', 'Arial'); 
                textEl.setAttribute('fill', fillValue === 'none' ? 'black' : fillValue);
                textEl.textContent = txt;
                window.editorCanvas.appendChild(textEl);
            }
            window.isDrawing = false;
            if (typeof window.updateCodePreview === 'function') window.updateCodePreview();
            return;
        } else if (window.currentTool === 'bezier') {
            window.currentElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            window.currentElement.setAttribute('d', `M ${window.startX} ${window.startY} C ${window.startX} ${window.startY}, ${window.startX} ${window.startY}, ${window.startX} ${window.startY}`);
            window.currentElement.setAttribute('fill', 'none');
            window.currentElement.setAttribute('stroke', 'black');
            window.currentElement.setAttribute('stroke-width', '2');
            applyDash(window.currentElement);
        }

        if (window.currentElement) window.editorCanvas.appendChild(window.currentElement);
    });
}

document.addEventListener('mousemove', (e) => {
    if (window.fullscreenEditor && window.fullscreenEditor.classList.contains('hidden')) return;
    const coords = window.getMouseCoords(e); 

    if (window.activeDragHandle) { window.activeDragHandle(coords.x, coords.y); return; }
    if (!window.isDrawing || !window.currentElement) return;

    if (window.currentTool === 'line') {
        window.currentElement.setAttribute('x2', coords.x);
        window.currentElement.setAttribute('y2', coords.y);
    } else if (window.currentTool === 'rect') {
        const w = coords.x - window.startX; 
        const h = coords.y - window.startY;
        window.currentElement.setAttribute('x', w < 0 ? coords.x : window.startX); 
        window.currentElement.setAttribute('y', h < 0 ? coords.y : window.startY);
        window.currentElement.setAttribute('width',  Math.abs(w)); 
        window.currentElement.setAttribute('height', Math.abs(h));
    } else if (window.currentTool === 'circle') {
        window.currentElement.setAttribute('r', Math.hypot(coords.x - window.startX, coords.y - window.startY));
    } else if (window.currentTool === 'bezier') {
        const endX = coords.x;
        const endY = coords.y;
        const cp1X = Math.round(window.startX + (endX - window.startX) * 0.33);
        const cp1Y = Math.round(window.startY + (endY - window.startY) * 0.33);
        const cp2X = Math.round(window.startX + (endX - window.startX) * 0.66);
        const cp2Y = Math.round(window.startY + (endY - window.startY) * 0.66);
        
        window.currentElement.setAttribute('d', `M ${window.startX} ${window.startY} C ${cp1X} ${cp1Y}, ${cp2X} ${cp2Y}, ${endX} ${endY}`);
    }
});

document.addEventListener('mouseup', () => {
    if (window.isDrawing || window.activeDragHandle) {
        window.isDrawing = false; 
        window.currentElement = null; 
        window.activeDragHandle = null;
        if (typeof window.schedulePreviewUpdate === 'function') window.schedulePreviewUpdate();
    }
});