let interactionMode = 'wire';
let currentStyle = 'bezier';
let currentCompSize = 'M';

let wireColor = '#00e5ff';
let compColor = '#21222d';
let recentColors = ['#00e5ff', '#ff5555', '#50fa7b', '#ffb86c', '#f1fa8c', '#ffffff', '#bd93f9', '#ff79c6', '#8be9fd', '#44475a'];

let gridMode = 'off';
const A4_PORT = { w: 794, h: 1123 };
const A4_LAND = { w: 1123, h: 794 };
const WORKSPACE_SIZE = 4000; // Muss zur Breite/Höhe von #workspace in style.css passen

let workspaceScale = 1.0; let workspacePanX = 0; let workspacePanY = 0;

function applyWorkspaceTransform() { document.getElementById('workspace').style.transform = `translate(${workspacePanX}px, ${workspacePanY}px) scale(${workspaceScale})`; }
function setZoom(newScale) { workspaceScale = Math.max(0.2, Math.min(newScale, 3.0)); document.getElementById('zoom-label').innerText = Math.round(workspaceScale * 100) + '%'; applyWorkspaceTransform(); }
document.getElementById('workspace-wrapper').addEventListener('wheel', (e) => { if (e.ctrlKey) { e.preventDefault(); if (e.deltaY < 0) setZoom(workspaceScale + 0.1); else setZoom(workspaceScale - 0.1); } }, { passive: false });

function setGridMode(mode) {
  gridMode = mode;
  ['off', 'port', 'land'].forEach(m => document.getElementById('btn-grid-' + m).classList.toggle('active', m === mode));
  drawGridMarks();
}

// FIX (Performance): Vorher wurde immer ein festes 10x10 Raster (100 Seiten) gezeichnet,
// unabhängig davon wie viele Seiten überhaupt in den 4000x4000px Workspace passen.
// Das erzeugte pro Aufruf bis zu 200 unnötige SVG-Knoten. Jetzt wird die Anzahl aus der
// tatsächlichen Workspace-Größe berechnet.
function drawGridMarks() {
  const layer = document.getElementById('grid-layer'); layer.innerHTML = '';
  if (gridMode === 'off') return;
  const w = gridMode === 'land' ? A4_LAND.w : A4_PORT.w, h = gridMode === 'land' ? A4_LAND.h : A4_PORT.h;
  const cols = Math.ceil(WORKSPACE_SIZE / w), rows = Math.ceil(WORKSPACE_SIZE / h);

  const frag = document.createDocumentFragment();
  for (let x = 1; x <= cols; x++) {
    for (let y = 1; y <= rows; y++) {
      const cx = x * w, cy = y * h;
      const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
      path.setAttribute('d', `M ${cx-15} ${cy} L ${cx+15} ${cy} M ${cx} ${cy-15} L ${cx} ${cy+15}`);
      path.setAttribute('stroke', '#6272a4'); path.setAttribute('stroke-width', '2');
      frag.appendChild(path);

      // Weiße Seitenzahlen oben links in jeder Seite
      const pageNum = (y - 1) * cols + x;
      const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
      text.setAttribute('x', ((x-1)*w) + 12); text.setAttribute('y', ((y-1)*h) + 24);
      text.setAttribute('fill', '#ffffff'); text.setAttribute('font-size', '16px'); text.setAttribute('font-weight', 'bold');
      text.textContent = pageNum;
      frag.appendChild(text);
    }
  }
  layer.appendChild(frag);
}

function setInteractionMode(mode) {
  interactionMode = mode;
  ['wire', 'edit', 'pan', 'img'].forEach(m => document.getElementById('btn-mode-' + m).className = 'mode-btn' + (m === mode ? ` active-${m}` : ''));
  if (connectSourcePinId) { document.getElementById(connectSourcePinId)?.classList.remove('connecting'); connectSourcePinId = null; }
}

function setCompSize(size) { currentCompSize = size; ['s', 'm', 'l'].forEach(s => document.getElementById('btn-size-' + s).classList.toggle('active', s.toUpperCase() === size)); }
function setLineStyle(style) { currentStyle = style; ['bezier', 'ortho', 'straight'].forEach(s => document.getElementById('btn-' + s).classList.toggle('active', s === style)); }
function updateWireColor(hex) { wireColor = hex; document.getElementById('wire-color').value = hex; if (typeof applyWireColorToActive === 'function') applyWireColorToActive(hex); }
function updateCompColor(hex) { compColor = hex; document.getElementById('comp-color').value = hex; if (typeof applyColorToActive === 'function') applyColorToActive(hex); }
function pushRecentColor(hex) { recentColors = recentColors.filter(c => c !== hex); recentColors.unshift(hex); if (recentColors.length > 10) recentColors.pop(); renderRecentColors(); }
function renderRecentColors() {
  const grid = document.getElementById('recent-colors-grid'); if(!grid) return; grid.innerHTML = '';
  recentColors.forEach(hex => {
    const btn = document.createElement('button'); btn.className = 'color-btn'; btn.style.background = hex;
    btn.onclick = () => { if (typeof activeCompId !== 'undefined' && activeCompId) updateCompColor(hex); else if (typeof activeWireId !== 'undefined' && activeWireId) updateWireColor(hex); else { updateWireColor(hex); updateCompColor(hex); } pushRecentColor(hex); };
    grid.appendChild(btn);
  });
}
renderRecentColors();
