const pageTabsContainer = document.getElementById('page-tabs');

function initPages() { 
    if (typeof currentPageId === 'undefined' || !currentPageId) {
        currentPageId = 1; 
    }
    renderTabs(); 
    setTimeout(() => switchPage(currentPageId), 50); 
}

function renderTabs() {
    pageTabsContainer.innerHTML = '';
    
    const tabD = document.createElement('div');
    tabD.className = `page-tab ${currentPageId === 'D' ? 'active' : ''}`;
    tabD.textContent = 'D';
    tabD.style.fontWeight = 'bold';
    tabD.onclick = () => switchPage('D');
    pageTabsContainer.appendChild(tabD);

    const tabI = document.createElement('div');
    tabI.className = `page-tab ${currentPageId === 'I' ? 'active' : ''}`;
    tabI.textContent = 'I';
    tabI.style.fontWeight = 'bold';
    tabI.onclick = () => switchPage('I');
    pageTabsContainer.appendChild(tabI);

    pages.forEach((page, index) => {
        const tab = document.createElement('div');
        tab.className = `page-tab ${page.id === currentPageId ? 'active' : ''}`;
        tab.textContent = (index + 1).toString();
        tab.onclick = () => switchPage(page.id);
        pageTabsContainer.appendChild(tab);
    });
}

function renderIHVList() {
    const ihvList = document.getElementById('ihv-list');
    if (!ihvList) return;
    
    ihvList.innerHTML = '';
    
    pages.forEach((page, index) => {
        const row = document.createElement('div');
        row.className = 'ihv-row';
        
        row.innerHTML = `
            <div class="ihv-page-name" style="width: 60px; text-align: center; font-size: 1.2em;">${index + 1}</div>
            <input type="text" class="ihv-input ihv-large" placeholder="Beschreibung / Anlage..." value="${page.desc || ''}">
            <input type="text" class="ihv-input ihv-small" style="width: 150px;" placeholder="TT.MM.JJJJ" value="${page.rev || ''}">
        `;
        
        const inputs = row.querySelectorAll('input');
        inputs[0].addEventListener('input', (e) => { page.desc = e.target.value; });
        inputs[1].addEventListener('input', (e) => { page.rev = e.target.value; });
        
        ihvList.appendChild(row);
    });
}

function getActiveLayer(id) {
    let layer = document.getElementById(`page-layer-${id}`);
    if (!layer) {
        const area4 = document.getElementById('area-4');
        if (area4) {
            layer = document.createElement('div');
            layer.id = `page-layer-${id}`;
            layer.className = 'page-layer';
            
            const wLayer = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            wLayer.id = `wiring-layer-${id}`;
            wLayer.className = 'wiring-layer-svg';
            wLayer.style.position = 'absolute';
            wLayer.style.top = '0';
            wLayer.style.left = '0';
            wLayer.style.width = '100%';
            wLayer.style.height = '100%';
            wLayer.style.pointerEvents = 'none';
            wLayer.style.zIndex = '100';
            
            layer.appendChild(wLayer);
            area4.appendChild(layer);
        }
    }
    return layer;
}


function switchPage(id) {
    if (currentPageId !== 'D' && currentPageId !== 'I') {
        saveCurrentPageState();
    }
    
    currentPageId = id;

    const area4 = document.getElementById('area-4');
    const deckblattView = document.getElementById('deckblatt-view');
    const ihvView = document.getElementById('ihv-view');
    
    // BUGFIX B: Wir überschreiben die hartnäckigen Inline-Styles mit display = 'none'
    if (area4) {
        area4.classList.add('hidden');
        area4.style.display = 'none';
    }
    if (deckblattView) {
        deckblattView.classList.add('hidden');
        deckblattView.style.display = 'none';
    }
    if (ihvView) {
        ihvView.classList.add('hidden');
        ihvView.style.display = 'none';
    }

    if (id === 'D') {
        if (deckblattView) {
            deckblattView.classList.remove('hidden');
            deckblattView.style.display = 'flex'; // Wichtig für das Zentrieren der Textfelder!
        }
        if (typeof window.hideAllKontaktspiegel === 'function') window.hideAllKontaktspiegel();
        if(typeof addHistory === 'function') addHistory('Deckblatt geöffnet');
    } else if (id === 'I') {
        if (ihvView) {
            ihvView.classList.remove('hidden');
            ihvView.style.display = 'block';
        }
        renderIHVList();
        if (typeof window.hideAllKontaktspiegel === 'function') window.hideAllKontaktspiegel();
        if(typeof addHistory === 'function') addHistory('Inhaltsverzeichnis geöffnet');
    } else {
        if (area4) {
            area4.classList.remove('hidden');
            area4.style.display = 'block';
        }
        
        document.querySelectorAll('.page-layer').forEach(l => l.classList.remove('active'));
        
        const activeLayer = getActiveLayer(id);
        activeLayer.classList.add('active');
        
        window.wiringLayer = document.getElementById(`wiring-layer-${id}`);
        window.canvas = activeLayer;

        if (typeof window.hideAllKontaktspiegel === 'function') window.hideAllKontaktspiegel();

        // Dein Zombie-Kabel-Fix von vorhin (ohne if-Bedingung)!
        loadPageState(id);

        if (typeof window.renderKontaktspiegelForPage === 'function') {
            setTimeout(() => window.renderKontaktspiegelForPage(), 50);
        }
        
        if (typeof drawFrame === 'function') drawFrame(); 
    }

    renderTabs();
}





function addPage() {
    if (currentPageId !== 'D' && currentPageId !== 'I') {
        saveCurrentPageState();
    }
    const newId = pages.length > 0 ? Math.max(...pages.map(p => p.id)) + 1 : 1;
    pages.push({ id: newId, name: newId.toString(), desc: "", rev: "", components: [], connections: [] });
    switchPage(newId);
    if(typeof addHistory === 'function') addHistory('Neue Seite erstellt');
}

function deletePage() {
    if (currentPageId === 'D' || currentPageId === 'I') {
        alert("Deckblatt (D) und Inhaltsverzeichnis (I) können nicht gelöscht werden.");
        return;
    }
    if (pages.length <= 1) {
        alert("Du kannst die letzte Zeichen-Seite nicht löschen! Der Schaltplan braucht mindestens eine Arbeitsfläche.");
        return;
    }
    if (!confirm("⚠️ Willst du diese Seite wirklich löschen? Alle Bauteile und Kabel darauf gehen dauerhaft verloren!")) return;

    const layerToRemove = document.getElementById(`page-layer-${currentPageId}`);
    if (layerToRemove) layerToRemove.remove();

    // BUGFIX A: Alte ID speichern und die Seite aus dem Array werfen.
    const oldId = currentPageId;
    pages = pages.filter(p => p.id !== oldId);
    
    // BUGFIX A: switchPage aufrufen. Die ID (currentPageId) ändern wir HIER NICHT manuell!
    // switchPage regelt das selbst und speichert so nicht versehentlich den Cache auf die neue Seite.
    switchPage(pages[0].id);
    
    if(typeof addHistory === 'function') addHistory('Seite gelöscht');
}

function saveCurrentPageState() {
    if (currentPageId === 'D' || currentPageId === 'I') return; 

    const currentPage = pages.find(p => p.id === currentPageId);
    if (!currentPage) return;

    const activeLayer = document.getElementById(`page-layer-${currentPageId}`);
    if (!activeLayer) return;

    const comps = [];
    activeLayer.querySelectorAll('.dropped-component').forEach(el => {
        comps.push({
            id: el.dataset.id, type: el.dataset.type, label: el.dataset.label,
            baseLabel: el.dataset.baseLabel, subtype: el.dataset.subtype,
            poles: el.dataset.poles, hubbel: el.dataset.hubbel, 
            terminals: el.dataset.terminals, parentId: el.dataset.parentId, 
            linkId: el.dataset.linkId, linkPage: el.dataset.linkPage, 
            html: el.innerHTML, left: el.style.left, top: el.style.top,
            rotation: el.dataset.rotation, flipX: el.dataset.flipX
        });
    });
    currentPage.components = comps;
    
    if (typeof window.serializePotConnections === 'function') {
        currentPage.potConnections = window.serializePotConnections();
    }
    
    if (typeof connections !== 'undefined') {
        const conns = connections.map(c => ({
            port1Id: c.port1.closest('.dropped-component').dataset.id,
            port1Index: Array.from(c.port1.closest('.dropped-component').querySelectorAll('.port')).indexOf(c.port1),
            port2Id: c.port2.closest('.dropped-component').dataset.id,
            port2Index: Array.from(c.port2.closest('.dropped-component').querySelectorAll('.port')).indexOf(c.port2),
            customX1: c.customX1, customY: c.customY, customX2: c.customX2,
            color: c.color,   
            name: c.name      
        }));
        currentPage.connections = conns;
    }
}

function loadPageState(id) {
    const page = pages.find(p => p.id === id);
    if (!page) return;

    const activeLayer = getActiveLayer(id);
    const wLayer = document.getElementById(`wiring-layer-${id}`);
    
    activeLayer.querySelectorAll('.dropped-component').forEach(c => c.remove());
    if (wLayer) wLayer.innerHTML = ''; 
    if (typeof connections !== 'undefined') connections.length = 0;
    if (window.potConnectionsLayer) window.potConnectionsLayer = [];

    window.wiringLayer = wLayer;
    window.canvas = activeLayer;

    page.components.forEach(c => {
        const div = document.createElement('div');
        div.className = 'dropped-component'; div.style.left = c.left; div.style.top = c.top;
        div.dataset.id = c.id; div.dataset.type = c.type;
        if(c.label) div.dataset.label = c.label;
        if(c.baseLabel) div.dataset.baseLabel = c.baseLabel;
        if(c.subtype) div.dataset.subtype = c.subtype;
        if(c.poles) div.dataset.poles = c.poles;
        if(c.hubbel) div.dataset.hubbel = c.hubbel;
        if(c.terminals) div.dataset.terminals = c.terminals;
        if(c.parentId) div.dataset.parentId = c.parentId;
        if(c.linkId) div.dataset.linkId = c.linkId;
        if(c.linkPage) div.dataset.linkPage = c.linkPage;
        if(c.rotation) div.dataset.rotation = c.rotation;
        if(c.flipX) div.dataset.flipX = c.flipX;
        div.innerHTML = c.html;

        if (c.type === 'pfeil_raus' || c.type === 'pfeil_rein') {
            if (typeof updateArrowVisuals === 'function') updateArrowVisuals(div);
        }

        div.addEventListener('mousedown', typeof startMovingComponent === 'function' ? startMovingComponent : null);
        div.addEventListener('click', typeof handleComponentClick === 'function' ? handleComponentClick : null);
        div.addEventListener('dblclick', (e) => {
            if ((typeof isAssignMode !== 'undefined' && isAssignMode) || (window.crossPageAssign && window.crossPageAssign.active)) return;
            window.contextMenuTarget = div;
            if(typeof showContextMenu === 'function') showContextMenu(e.clientX, e.clientY);
        });
        div.querySelectorAll('.port').forEach(p => p.onclick = typeof handlePortClick === 'function' ? handlePortClick : null);
        
        activeLayer.appendChild(div);
    });

    page.connections.forEach(conn => {
        const comp1 = activeLayer.querySelector(`[data-id="${conn.port1Id}"]`);
        const comp2 = activeLayer.querySelector(`[data-id="${conn.port2Id}"]`);
        if (comp1 && comp2) {
            const port1 = comp1.querySelectorAll('.port')[conn.port1Index];
            const port2 = comp2.querySelectorAll('.port')[conn.port2Index];
            if(typeof window.addConnection === 'function') {
                window.addConnection(port1, port2, { 
                    customX1: conn.customX1, customY: conn.customY, customX2: conn.customX2,
                    color: conn.color,   
                    name: conn.name      
                });
            }
        }
    });

    if(typeof updateCables === 'function') updateCables();
    if(typeof window.renderPotentials === 'function') window.renderPotentials(); 

    if (typeof window.restorePotConnections === 'function') {
        window.restorePotConnections(page.potConnections || []);
    }

    if (window.crossPageAssign && window.crossPageAssign.active) {
        activeLayer.classList.add('assign-mode');
    }
}

const btnAddPage = document.getElementById('btn-add-page');
if (btnAddPage) btnAddPage.onclick = addPage;

const btnDeletePage = document.getElementById('btn-delete-page');
if (btnDeletePage) btnDeletePage.onclick = deletePage;

initPages();