// ════════════════════════════════════════════════════════════════════════════
//  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());
    
    // Strikter Snap an das gewählte Raster (gridSize)
    return {
        x: Math.round(cursor.x / window.gridSize) * window.gridSize,
        y: Math.round(cursor.y / window.gridSize) * window.gridSize
    };
};

window.toolBtns.forEach(btn => {
    btn.addEventListener('click', (e) => {
        window.toolBtns.forEach(b => {
            b.classList.remove('active');
            b.style.backgroundColor = '';
            b.style.color = '';
        });
        e.currentTarget.classList.add('active');
        if (e.currentTarget.dataset.tool === 'select') {
            e.currentTarget.style.backgroundColor = '#f1c40f';
            e.currentTarget.style.color = 'black';
        } else if (e.currentTarget.dataset.tool === 'add-point') {
            e.currentTarget.style.backgroundColor = '#2ecc71';
            e.currentTarget.style.color = 'white';
        } else if (e.currentTarget.dataset.tool === 'port') {
            e.currentTarget.style.backgroundColor = '#ff4757';
            e.currentTarget.style.color = 'white';
        } else {
            e.currentTarget.style.backgroundColor = '#34495e';
            e.currentTarget.style.color = 'white';
        }
        window.currentTool = e.currentTarget.dataset.tool;
        if (typeof deselectElement === 'function') deselectElement();
    });
});

// "Neues Bauteil"-Button vom Haupt-Schaltplan (FIX: Löscht den Plan nicht mehr!)
const btnNewComp = document.getElementById('btn-new-comp');
if (btnNewComp) {
    btnNewComp.addEventListener('click', () => {
        window.editingComponent = null;
        window.editingInstance = null;
        
        // HIER WURDE DER LÖSCH-BEFEHL ENTFERNT! Der Plan bleibt nun erhalten.
        
        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';
        
        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 updateCodePreview === 'function') 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 updateCodePreview === 'function') updateCodePreview();
        }
    });
}

// ── 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 isShape = ['line', 'rect', 'circle', 'path', 'polygon', 'polyline', 'text', 'ellipse'].includes(e.target.tagName.toLowerCase());

        // (Der Teil für 'add-point' und 'select' kommt später in die Properties-Datei, 
        // für jetzt lassen wir das Zeichnen hier im Fokus)
        
        if (window.currentTool === 'select' || window.currentTool === 'add-point') {
            if (isShape && e.target !== window.editorCanvas && typeof selectElement === 'function') {
                selectElement(e.target);
                if (typeof setupElementMove === 'function') setupElementMove(e.target, coords);
            } else if (typeof deselectElement === 'function') {
                deselectElement();
            }
            return;
        }

        if (typeof deselectElement === 'function') 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 updateCodePreview === 'function') updateCodePreview();
            return;
        }

        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); // Erzwungene Raster-Koordinaten

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

    if (window.currentTool === 'line') {
        // FIX: Keine fliegenden Winkel mehr! Zieht direkte Linien zum harten Rasterpunkt.
        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));
    }
});

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