// ============================================================================
// COMPREHENSIVE FUNCTION BACKUP FOR LAYOUT CREATOR
// ============================================================================

// MULTI-SELECT FUNCTIONALITY
function updateMultiSelectProperties() {
  if (state.selectedTracks.size === 0) {
    hideProperties();
    return;
  }
  
  if (state.selectedTracks.size === 1) {
    const trackId = Array.from(state.selectedTracks)[0];
    state.selectedTrack = trackId;
    showProperties(trackId);
    return;
  }
  
  // Multi-select properties
  showMultiSelectProperties();
}

function showMultiSelectProperties() {
  const panel = document.getElementById('properties-panel');
  if (!panel) return;
  
  panel.style.display = 'block';
  
  const title = document.getElementById('properties-title');
  if (title) {
    title.textContent = `Multi-Select (${state.selectedTracks.size} tracks)`;
  }
  
  const content = document.getElementById('properties-content');
  if (!content) return;
  
  // Hide other content
  const noSelection = document.getElementById('no-selection');
  const trackProperties = document.getElementById('track-properties');
  if (noSelection) noSelection.style.display = 'none';
  if (trackProperties) trackProperties.style.display = 'none';
  
  // Show multi-select content
  content.style.display = 'block';
  content.innerHTML = `
    <div class="prop-group">
      <label>Selected Tracks:</label>
      <div style="max-height: 150px; overflow-y: auto; background: #f8f9fa; padding: 8px; border-radius: 4px;">
        ${Array.from(state.selectedTracks).map(id => {
          const track = state.layout.tracks[id];
          return `<div style="display: flex; justify-content: space-between; align-items: center; padding: 2px 0;">
            <span>${id} (${track.type})</span>
            <button onclick="removeFromSelection('${id}')" style="background: #e74c3c; color: white; border: none; border-radius: 3px; padding: 2px 6px; cursor: pointer;">✕</button>
          </div>`;
        }).join('')}
      </div>
    </div>
    
    <div class="prop-group">
      <label>Actions:</label>
      <div style="display: flex; gap: 8px; flex-wrap: wrap;">
        <button onclick="deleteSelectedTracks()" class="danger-btn" style="font-size: 12px;">Delete All</button>
        <button onclick="clearSelection()" class="secondary-btn" style="font-size: 12px;">Clear Selection</button>
        <button onclick="normalizeSelectedTracks()" class="secondary-btn" style="font-size: 12px;">Normalize IDs</button>
      </div>
    </div>
  `;
}

function removeFromSelection(trackId) {
  state.selectedTracks.delete(trackId);
  if (state.selectedTracks.size === 0) {
    hideProperties();
  } else {
    updateMultiSelectProperties();
  }
  draw();
}

function deleteSelectedTracks() {
  if (state.selectedTracks.size === 0) return;
  
  if (confirm(`Delete ${state.selectedTracks.size} selected tracks?`)) {
    for (const trackId of state.selectedTracks) {
      delete state.layout.tracks[trackId];
    }
    state.selectedTracks.clear();
    state.selectedTrack = null;
    hideProperties();
    saveHistory();
    updateStats();
    draw();
    setStatus(`Deleted ${state.selectedTracks.size} tracks`);
  }
}

function clearSelection() {
  state.selectedTracks.clear();
  state.selectedTrack = null;
  hideProperties();
  draw();
}

function normalizeSelectedTracks() {
  if (state.selectedTracks.size === 0) return;
  
  // Get selected tracks and normalize their IDs
  const selectedTracks = Array.from(state.selectedTracks);
  const newTracks = {};
  const idMap = new Map();
  
  // Create new sequential IDs for selected tracks
  let counters = { N: 1, B: 1, P: 1, S: 1 };
  
  for (const oldId of selectedTracks) {
    const track = state.layout.tracks[oldId];
    const match = oldId.match(/^([A-Z]+)(\d+)$/);
    if (match) {
      const prefix = match[1];
      const newId = `${prefix}${counters[prefix]}`;
      counters[prefix]++;
      idMap.set(oldId, newId);
      newTracks[newId] = { ...track };
    }
  }
  
  // Update connections and references
  for (const [newId, track] of Object.entries(newTracks)) {
    if (track.connections) {
      track.connections = track.connections.map(oldConnId => {
        const newConnId = idMap.get(oldConnId);
        return newConnId || oldConnId;
      });
    }
    
    if (track.type === 'point' && track.coacting) {
      track.coacting = track.coacting.map(oldId => idMap.get(oldId) || oldId);
    }
    
    if (track.type === 'pointsignal') {
      if (track.point) track.point = idMap.get(track.point) || track.point;
      if (track.pointleg) track.pointleg = idMap.get(track.pointleg) || track.pointleg;
      if (track.triggernode) track.triggernode = idMap.get(track.triggernode) || track.triggernode;
    }
    
    if (track.type === 'signal' && track.triggernode) {
      track.triggernode = idMap.get(track.triggernode) || track.triggernode;
    }
  }
  
  // Replace selected tracks
  for (const oldId of selectedTracks) {
    delete state.layout.tracks[oldId];
  }
  
  for (const [newId, track] of Object.entries(newTracks)) {
    state.layout.tracks[newId] = track;
  }
  
  // Update selection with new IDs
  state.selectedTracks.clear();
  for (const newId of Object.keys(newTracks)) {
    state.selectedTracks.add(newId);
  }
  
  saveHistory();
  updateMultiSelectProperties();
  draw();
  setStatus(`Normalized ${selectedTracks.length} selected tracks`);
}

// SELECTION BOX FUNCTIONALITY
function updateSelectionBox() {
  const startX = Math.min(state.selectionStart.x, state.selectionEnd.x);
  const startY = Math.min(state.selectionStart.y, state.selectionEnd.y);
  const endX = Math.max(state.selectionStart.x, state.selectionEnd.x);
  const endY = Math.max(state.selectionStart.y, state.selectionEnd.y);
  
  // Clear current selection
  state.selectedTracks.clear();
  
  // Find tracks within selection box
  for (const [id, track] of Object.entries(state.layout.tracks)) {
    const [x, y] = track.position;
    if (x >= startX && x <= endX && y >= startY && y <= endY) {
      state.selectedTracks.add(id);
    }
  }
  
  updateMultiSelectProperties();
}

function drawSelectionBox(ctx) {
  const startX = worldToScreenX(Math.min(state.selectionStart.x, state.selectionEnd.x));
  const startY = worldToScreenY(Math.min(state.selectionStart.y, state.selectionEnd.y));
  const endX = worldToScreenX(Math.max(state.selectionStart.x, state.selectionEnd.x));
  const endY = worldToScreenY(Math.max(state.selectionStart.y, state.selectionEnd.y));
  
  ctx.save();
  ctx.strokeStyle = '#3498db';
  ctx.lineWidth = 2;
  ctx.setLineDash([5, 5]);
  ctx.fillStyle = 'rgba(52, 152, 219, 0.1)';
  
  ctx.beginPath();
  ctx.rect(startX, startY, endX - startX, endY - startY);
  ctx.fill();
  ctx.stroke();
  
  ctx.restore();
}

function drawMultiSelectHighlights(ctx) {
  ctx.save();
  ctx.strokeStyle = '#e74c3c';
  ctx.lineWidth = 3;
  ctx.setLineDash([]);
  
  for (const trackId of state.selectedTracks) {
    const track = state.layout.tracks[trackId];
    if (!track) continue;
    
    const [x, y] = track.position;
    const sx = worldToScreenX(x);
    const sy = worldToScreenY(y);
    
    // Draw highlight circle
    ctx.beginPath();
    ctx.arc(sx, sy, 12, 0, 2 * Math.PI);
    ctx.stroke();
    
    // Draw track ID
    ctx.fillStyle = '#e74c3c';
    ctx.font = 'bold 12px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(trackId, sx, sy - 16);
  }
  
  ctx.restore();
}

// NODE NUMBERING NORMALIZATION
function normalizeNodeNumbering() {
  const oldTracks = state.layout.tracks;
  const newTracks = {};
  const idMap = new Map();
  const counters = { N: 1, B: 1, P: 1, S: 1 }; // Starting counters for each prefix

  // Group tracks by prefix and sort them by their current number
  const groupedTracks = {};
  for (const id in oldTracks) {
    const match = id.match(/^([A-Z]+)(\d+)$/);
    if (match) {
      const prefix = match[1];
      const num = parseInt(match[2]);
      if (!groupedTracks[prefix]) {
        groupedTracks[prefix] = [];
      }
      groupedTracks[prefix].push({ id, num, track: oldTracks[id] });
    } else {
      // Keep non-standard IDs as is
      newTracks[id] = oldTracks[id];
    }
  }

  // Sort each group and assign new sequential IDs
  for (const prefix in groupedTracks) {
    groupedTracks[prefix].sort((a, b) => a.num - b.num);
    for (const item of groupedTracks[prefix]) {
      const newId = `${prefix}${counters[prefix]++}`;
      idMap.set(item.id, newId);
      newTracks[newId] = { ...item.track }; // Copy track data
    }
  }

  // Update all connections and references to use new IDs
  for (const newId in newTracks) {
    const track = newTracks[newId];

    // Update connections
    if (track.connections) {
      track.connections = track.connections.map(connId => idMap.get(connId) || connId);
    }

    // Update point-specific properties
    if (track.type === 'point' && track.coacting) {
      track.coacting = track.coacting.map(coId => idMap.get(coId) || coId);
    }

    // Update signal-specific properties
    if (track.type === 'pointsignal') {
      if (track.point) track.point = idMap.get(track.point) || track.point;
      if (track.pointleg) track.pointleg = idMap.get(track.pointleg) || track.pointleg;
      if (track.triggernode) track.triggernode = idMap.get(track.triggernode) || track.triggernode;
      if (track.leglabels) {
        const newLegLabels = {};
        for (const oldLegId in track.leglabels) {
          newLegLabels[idMap.get(oldLegId) || oldLegId] = track.leglabels[oldLegId];
        }
        track.leglabels = newLegLabels;
      }
    } else if (track.type === 'signal' && track.triggernode) {
      track.triggernode = idMap.get(track.triggernode) || track.triggernode;
    }
  }

  state.layout.tracks = newTracks;

  // Update selected track if it was renumbered
  if (state.selectedTrack && idMap.has(state.selectedTrack)) {
    state.selectedTrack = idMap.get(state.selectedTrack);
    showProperties(state.selectedTrack);
  } else if (state.selectedTrack) {
    // If selected track was not renumbered (e.g., non-standard ID), just refresh properties
    showProperties(state.selectedTrack);
  } else {
    hideProperties();
  }

  // Update multi-selected tracks
  const newSelectedTracks = new Set();
  for (const oldId of state.selectedTracks) {
    newSelectedTracks.add(idMap.get(oldId) || oldId);
  }
  state.selectedTracks = newSelectedTracks;
  updateMultiSelectProperties();

  saveHistory();
  draw();
}

// GLOBAL FUNCTION EXPORTS
window.removeFromSelection = removeFromSelection;
window.deleteSelectedTracks = deleteSelectedTracks;
window.clearSelection = clearSelection;
window.normalizeSelectedTracks = normalizeSelectedTracks;
window.normalizeNodeNumbering = normalizeNodeNumbering;
