let isDraggingWire = false;
let draggedWireTarget = null;

// Kabel manuell verschieben
document.addEventListener('mousemove', (e) => {
    if (isDraggingWire && draggedWireTarget) {
        const coords = window.getPointerCoords(e);
        if (draggedWireTarget.type === 'X1') draggedWireTarget.conn.customX1 = coords.x;
        if (draggedWireTarget.type === 'Y')  draggedWireTarget.conn.customY = coords.y;
        if (draggedWireTarget.type === 'X2') draggedWireTarget.conn.customX2 = coords.x;
        if (typeof window.updateCables === 'function') window.updateCables();
    }
});

document.addEventListener('mouseup', () => {
    if (isDraggingWire) {
        isDraggingWire = false;
        draggedWireTarget = null;
        if (typeof window.updateCables === 'function') window.updateCables(); 
        if (typeof addHistory === 'function') addHistory('Kabelverlauf angepasst');
    }
});

// Neue Verbindung zeichnen
window.addConnection = function(port1, port2, savedData = {}) {
    let inheritedColor = savedData.color || 'black';

    if (!savedData.color && typeof connections !== 'undefined') {
        for (const existingConn of connections) {
            if (existingConn.port1 === port1 || existingConn.port2 === port1 ||
                existingConn.port1 === port2 || existingConn.port2 === port2) {
                inheritedColor = existingConn.color;
                break;
            }
        }
    }

    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('stroke', inheritedColor);
    path.setAttribute('stroke-width', '2');
    path.setAttribute('fill', 'none');
    path.style.cursor = 'pointer';
    path.style.pointerEvents = 'stroke'; // WICHTIG: Erlaubt den Rechtsklick genau auf der Linie
    if (window.wiringLayer) window.wiringLayer.appendChild(path);

    const textElem = document.createElementNS('http://www.w3.org/2000/svg', 'text');
    textElem.setAttribute('font-family', 'Arial');
    textElem.setAttribute('font-size', '12');
    textElem.setAttribute('fill', 'black');
    textElem.setAttribute('text-anchor', 'middle');
    textElem.style.pointerEvents = 'none';
    if (window.wiringLayer) window.wiringLayer.appendChild(textElem);

    // Die drei blauen Greifpunkte
    const h1 = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    const h2 = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    const h3 = document.createElementNS('http://www.w3.org/2000/svg', 'circle');

    [h1, h2, h3].forEach(h => {
        h.setAttribute('class', 'wire-handle hidden');
        h.style.pointerEvents = 'all'; // WICHTIG: Erzwingt die Klickbarkeit
        if (window.wiringLayer) window.wiringLayer.appendChild(h);
    });

    const connObj = {
        pathElem: path, port1: port1, port2: port2, h1: h1, h2: h2, h3: h3,
        textElem: textElem, name: savedData.name || '', color: inheritedColor,
        showHandles: false, customX1: savedData.customX1, customY: savedData.customY, customX2: savedData.customX2
    };

    // Kontextmenü für Kabel öffnen
    path.addEventListener('dblclick', (e) => {
        e.preventDefault(); e.stopPropagation();
        if (typeof showWireContextMenu === 'function') showWireContextMenu(e.clientX, e.clientY, connObj);
    });

    path.addEventListener('contextmenu', (e) => {
        e.preventDefault(); e.stopPropagation();
        if (typeof showWireContextMenu === 'function') showWireContextMenu(e.clientX, e.clientY, connObj);
    });

    // Greifpunkte anklicken
    h1.addEventListener('mousedown', (e) => { e.preventDefault(); e.stopPropagation(); isDraggingWire = true; draggedWireTarget = {conn: connObj, type: 'X1'}; });
    h2.addEventListener('mousedown', (e) => { e.preventDefault(); e.stopPropagation(); isDraggingWire = true; draggedWireTarget = {conn: connObj, type: 'Y'}; });
    h3.addEventListener('mousedown', (e) => { e.preventDefault(); e.stopPropagation(); isDraggingWire = true; draggedWireTarget = {conn: connObj, type: 'X2'}; });

    if (typeof connections !== 'undefined') connections.push(connObj);
    if (typeof window.updateCables === 'function') window.updateCables();
};

function handlePortClick(e) {
    const port = e.target;
    if (!window.canvas) return;
    
    const rect = window.canvas.getBoundingClientRect();
    const portRect = port.getBoundingClientRect();
    const zoom = window.currentZoom || 1.0;

    const x = (portRect.left - rect.left + portRect.width / 2) / zoom;
    const y = (portRect.top - rect.top + portRect.height / 2) / zoom;

    if (typeof window.startPort === 'undefined' || !window.startPort) {
        window.startPort = { x, y, element: port };
        port.setAttribute('fill', 'blue');
        if (typeof addHistory === 'function') addHistory('Kabel gestartet');
    } else {
        if (window.startPort.element !== port) {
            window.addConnection(window.startPort.element, port, {});
            if (typeof addHistory === 'function') addHistory('Bauteile verbunden');
        }
        window.startPort.element.setAttribute('fill', 'red');
        window.startPort = null;
    }
}

function isPortAtTop(port, portRect) {
    const comp = port.closest('.dropped-component');
    if (!comp) return parseFloat(port.getAttribute('cy') || '50') < 50;
    const compRect = comp.getBoundingClientRect();
    const portCenterY = portRect.top + portRect.height / 2;
    return portCenterY < compRect.top + compRect.height / 2;
}
window.updateCables = function() {
    if (!window.canvas || !window.wiringLayer || typeof connections === 'undefined') return;
    
    const canvasRect = window.canvas.getBoundingClientRect();
    const zoom = window.currentZoom || 1.0;

    connections = connections.filter(conn => {
        if (!document.body.contains(conn.port1) || !document.body.contains(conn.port2)) {
            if (conn.pathElem) conn.pathElem.remove();
            if (conn.h1) conn.h1.remove(); 
            if (conn.h2) conn.h2.remove(); 
            if (conn.h3) conn.h3.remove();
            if (conn.textElem) conn.textElem.remove();
            return false;
        }
        return true;
    });

    connections.forEach(conn => {
        // Der aggressive Lösch-Block (delete conn.customX1) wurde hier restlos entfernt, 
        // damit die Leitungen immer ihre Form behalten!

        const rect1 = conn.port1.getBoundingClientRect();
        const rect2 = conn.port2.getBoundingClientRect();

        const x1 = (rect1.left - canvasRect.left + rect1.width / 2) / zoom;
        const y1 = (rect1.top - canvasRect.top + rect1.height / 2) / zoom;
        const x2 = (rect2.left - canvasRect.left + rect2.width / 2) / zoom;
        const y2 = (rect2.top - canvasRect.top + rect2.height / 2) / zoom;

        const isTop1 = isPortAtTop(conn.port1, rect1);
        const isTop2 = isPortAtTop(conn.port2, rect2);

        const y1_off = y1 + (isTop1 ? -20 : 20);
        const y2_off = y2 + (isTop2 ? -20 : 20);

        let defaultYMid;
        if (isTop1 && isTop2) defaultYMid = Math.min(y1, y2) - 40;
        else if (!isTop1 && !isTop2) defaultYMid = Math.max(y1, y2) + 40;
        else defaultYMid = y1_off + (y2_off - y1_off) / 2;

        const X1 = conn.customX1 !== undefined ? conn.customX1 : x1;
        const Y_mid = conn.customY !== undefined ? conn.customY : defaultYMid;
        const X2 = conn.customX2 !== undefined ? conn.customX2 : x2;

        const d = `M ${x1} ${y1} L ${x1} ${y1_off} L ${X1} ${y1_off} L ${X1} ${Y_mid} L ${X2} ${Y_mid} L ${X2} ${y2_off} L ${x2} ${y2_off} L ${x2} ${y2}`;
        conn.pathElem.setAttribute('d', d);
        conn.pathElem.setAttribute('stroke', conn.color || 'black');

        if (conn.textElem) {
            conn.textElem.textContent = conn.name || '';
            if (conn.name) {
                conn.textElem.setAttribute('x', X1 + (X2 - X1) / 2);
                conn.textElem.setAttribute('y', Y_mid - 8);
                conn.textElem.setAttribute('fill', conn.color || 'black');
            }
        }

        conn.points = [
            {x: x1, y: y1}, {x: x1, y: y1_off}, {x: X1, y: y1_off},
            {x: X1, y: Y_mid}, {x: X2, y: Y_mid}, {x: X2, y: y2_off},
            {x: x2, y: y2_off}, {x: x2, y: y2}
        ];

        // NEU: Absolute Sichtbarkeits-Steuerung der blauen Punkte
        if (conn.showHandles) {
            conn.h1.style.display = 'block';
            conn.h2.style.display = 'block';
            conn.h3.style.display = 'block';
            
            conn.h1.setAttribute('cx', X1); conn.h1.setAttribute('cy', y1_off + (Y_mid - y1_off) / 2);
            conn.h1.setAttribute('class', 'wire-handle v-handle');
            
            conn.h2.setAttribute('cx', X1 + (X2 - X1) / 2); conn.h2.setAttribute('cy', Y_mid);
            conn.h2.setAttribute('class', 'wire-handle h-handle');
            
            conn.h3.setAttribute('cx', X2); conn.h3.setAttribute('cy', Y_mid + (y2_off - Y_mid) / 2);
            conn.h3.setAttribute('class', 'wire-handle v-handle');
        } else {
            conn.h1.style.display = 'none';
            conn.h2.style.display = 'none';
            conn.h3.style.display = 'none';
        }
    });

    if (!isDraggingWire) {
        window.wiringLayer.querySelectorAll('.junction-dot').forEach(el => el.remove());

        const allPorts = Array.from(document.querySelectorAll('.port')).map(p => {
            const r = p.getBoundingClientRect();
            return {
                x: (r.left - canvasRect.left + r.width / 2) / zoom,
                y: (r.top - canvasRect.top + r.height / 2) / zoom
            };
        });

        function sharePort(c1, c2) {
            return c1.port1 === c2.port1 || c1.port1 === c2.port2 || c1.port2 === c2.port1 || c1.port2 === c2.port2;
        }

        const nets = [];
        const visitedConns = new Set();
        connections.forEach(c => {
            if (visitedConns.has(c)) return;
            const net = [];
            const queue = [c];
            visitedConns.add(c);
            while(queue.length > 0) {
                const curr = queue.shift();
                net.push(curr);
                connections.forEach(other => {
                    if (!visitedConns.has(other) && sharePort(curr, other)) {
                        visitedConns.add(other);
                        queue.push(other);
                    }
                });
            }
            nets.push(net);
        });

        const validJunctions = [];

        nets.forEach(net => {
            const segments = [];
            net.forEach(c => {
                for (let k = 0; k < c.points.length - 1; k++) {
                    segments.push({a: c.points[k], b: c.points[k+1]});
                }
            });

            const candidatePoints = [];
            const addCandidate = (x, y) => {
                if (!candidatePoints.some(p => Math.abs(p.x - x) < 1 && Math.abs(p.y - y) < 1)) {
                    candidatePoints.push({x, y});
                }
            };

            segments.forEach(seg => { addCandidate(seg.a.x, seg.a.y); addCandidate(seg.b.x, seg.b.y); });

            segments.forEach(seg1 => {
                segments.forEach(seg2 => {
                    const isHoriz1 = Math.abs(seg1.a.y - seg1.b.y) < 1;
                    const isHoriz2 = Math.abs(seg2.a.y - seg2.b.y) < 1;
                    if (isHoriz1 && !isHoriz2) {
                        const x = seg2.a.x; const y = seg1.a.y;
                        if (x >= Math.min(seg1.a.x, seg1.b.x) - 1 && x <= Math.max(seg1.a.x, seg1.b.x) + 1 &&
                            y >= Math.min(seg2.a.y, seg2.b.y) - 1 && y <= Math.max(seg2.a.y, seg2.b.y) + 1) {
                            addCandidate(x, y);
                        }
                    }
                });
            });

            candidatePoints.forEach(p => {
                let hasUp = false, hasDown = false, hasLeft = false, hasRight = false;
                const tol = 1;

                segments.forEach(seg => {
                    const isHoriz = Math.abs(seg.a.y - seg.b.y) < tol;
                    const isVert = Math.abs(seg.a.x - seg.b.x) < tol;

                    if (isHoriz && Math.abs(p.y - seg.a.y) < tol) {
                        const minX = Math.min(seg.a.x, seg.b.x); const maxX = Math.max(seg.a.x, seg.b.x);
                        if (p.x >= minX - tol && p.x <= maxX + tol) {
                            if (p.x > minX + tol) hasLeft = true;
                            if (p.x < maxX - tol) hasRight = true;
                        }
                    }
                    if (isVert && Math.abs(p.x - seg.a.x) < tol) {
                        const minY = Math.min(seg.a.y, seg.b.y); const maxY = Math.max(seg.a.y, seg.b.y);
                        if (p.y >= minY - tol && p.y <= maxY + tol) {
                            if (p.y > minY + tol) hasUp = true;
                            if (p.y < maxY - tol) hasDown = true;
                        }
                    }
                });

                const dirCount = (hasUp ? 1 : 0) + (hasDown ? 1 : 0) + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);

                if (dirCount >= 3) {
                    let isPort = allPorts.some(pt => Math.hypot(p.x - pt.x, p.y - pt.y) < 5);
                    if (!isPort) {
                        let exists = validJunctions.some(vj => Math.hypot(vj.x - p.x, vj.y - p.y) < 2);
                        if (!exists) validJunctions.push({x: p.x, y: p.y});
                    }
                }
            });
        });

        validJunctions.forEach(jp => {
            const dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
            dot.setAttribute('cx', jp.x); dot.setAttribute('cy', jp.y);
            dot.setAttribute('r', '4'); dot.setAttribute('fill', 'black');
            dot.setAttribute('class', 'junction-dot');
            dot.style.pointerEvents = 'none';
            if (window.wiringLayer) window.wiringLayer.appendChild(dot);
        });
    }

    if (typeof window.drawPotConnections === 'function') window.drawPotConnections();
};