/* ==============================================
   Sidebar: Project Rail (Cortex pattern)
   ============================================== */
const avatarPalette = [
  '#d44c4c','#c8960c','#3a9a50','#5c9cd4','#8a6cd4',
  '#d46c8a','#4cd4c8','#d4a04c','#6cd44c','#4cd48a',
];

function avatarColor(name) {
  let h = 0;
  for (let i = 0; i < name.length; i++) {
    h = name.charCodeAt(i) + ((h << 5) - h);
  }
  return avatarPalette[Math.abs(h) % avatarPalette.length];
}

function renderSidebar() {
  const list = document.getElementById('sidebar-projects');
  list.innerHTML = '';
  projects.forEach(p => {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'sidebar-project' + (p.id === currentProject ? ' is-active' : '') + (selectedProjects.has(p.id) ? ' is-selected' : '');
    btn.title = p.name;

    if (!manageMode) {
      btn.onclick = () => selectProject(p.id);
    } else {
      btn.onclick = (e) => {
        e.preventDefault();
        if (selectedProjects.has(p.id)) {
          selectedProjects.delete(p.id);
          btn.classList.remove('is-selected');
        } else {
          selectedProjects.add(p.id);
          btn.classList.add('is-selected');
        }
      };
    }

    const avatar = document.createElement('div');
    avatar.className = 'sidebar-avatar';
    avatar.style.background = avatarColor(p.name);
    avatar.textContent = p.name.charAt(0).toUpperCase();

    const tooltip = document.createElement('span');
    tooltip.className = 'sidebar-tooltip';
    let tooltipText = p.name;
    if (p.created_at) {
      tooltipText += ' · ' + formatDate(p.created_at).split(' ')[0];
    }
    tooltip.textContent = tooltipText;

    btn.appendChild(avatar);
    btn.appendChild(tooltip);
    list.appendChild(btn);
  });
}

/* ==============================================
   Project CRUD
   ============================================== */
function selectProject(id) {
  currentProject = id;
  savedZoom = null;  // reset zoom — fit new project
  savedPan = null;
  // Close any open panels
  closeCredentials();
  closeSearch();
  document.getElementById('current-project-name').textContent =
    (projects.find(p => p.id === id) || {}).name || '';
  document.getElementById('btn-analysis').disabled = false;
  document.getElementById('btn-credentials').disabled = false;
  document.getElementById('btn-import').disabled = false;
  renderSidebar();
  loadGraph();
}

function loadProjects() {
  return fetch(API+'/projects')
    .then(r => r.json())
    .then(j => {
      projects = j.data || [];
      renderSidebar();
      // If we had a selected project, make sure it's still valid
      if (currentProject && !projects.find(p => p.id === currentProject)) {
        currentProject = null;
        document.getElementById('btn-analysis').disabled = true;
        document.getElementById('btn-credentials').disabled = true;
        document.getElementById('btn-import').disabled = true;
        document.getElementById('current-project-name').textContent = '';
        cy.elements().remove();
        document.getElementById('stat-nodes').textContent = '0';
        document.getElementById('stat-edges').textContent = '0';
        updateEmptyState();
      }
    });
}

function showCreateModal() {
  document.getElementById('modal').classList.add('active');
  document.getElementById('modal-name').focus();
}
function hideCreateModal() {
  document.getElementById('modal').classList.remove('active');
  document.getElementById('modal-name').value='';
}
async function createProject() {
  const name = document.getElementById('modal-name').value.trim();
  if(!name) return;
  const res = await fetch(API+'/projects',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name})});
  const j = await res.json();
  hideCreateModal();
  await loadProjects();
  currentProject = j.data.id;
  document.getElementById('current-project-name').textContent = name;
  renderSidebar();
  loadGraph();
  toast('项目已创建');
}

async function deleteProject() {
  if(!currentProject) return;
  const p = projects.find(p => p.id === currentProject);
  if(!confirm('确定删除项目「'+(p?p.name:currentProject)+'」？所有节点和连线将被清除。')) return;
  await fetch(API+'/projects/'+currentProject,{method:'DELETE'});
  currentProject = null;
  document.getElementById('btn-analysis').disabled = true;
  document.getElementById('btn-credentials').disabled = true;
  document.getElementById('btn-import').disabled = true;
  document.getElementById('current-project-name').textContent = '';
  cy.elements().remove();
  document.getElementById('stat-nodes').textContent='0';
  document.getElementById('stat-edges').textContent='0';
  await loadProjects();
  updateEmptyState();
  toast('项目已删除');
}

/* ==============================================
   Batch Project Management
   ============================================== */
let manageMode = false;
const selectedProjects = new Set();

function toggleManageMode() {
  manageMode = !manageMode;
  selectedProjects.clear();
  document.getElementById('sidebar-rail').classList.toggle('manage-mode', manageMode);
  document.getElementById('btn-manage').textContent = manageMode ? '✕ 完成' : '✎ 管理';
  renderSidebar();
  // Clear any selection highlights
  document.querySelectorAll('.sidebar-project.is-selected').forEach(b => b.classList.remove('is-selected'));
}

async function batchDelete() {
  if (selectedProjects.size === 0) {
    toast('请先选择要删除的项目');
    return;
  }
  const names = [];
  for (const pid of selectedProjects) {
    const p = projects.find(p => p.id === pid);
    if (p) names.push(p.name);
  }
  if (!confirm('确定删除 ' + selectedProjects.size + ' 个项目？\n\n' + names.join('\n') + '\n\n所有节点和连线将被清除。此操作不可撤销。')) return;

  let deleted = 0;
  for (const pid of selectedProjects) {
    try {
      await fetch(API + '/projects/' + pid, { method: 'DELETE' });
      deleted++;
    } catch (e) { /* continue */ }
  }

  if (currentProject && selectedProjects.has(currentProject)) {
    currentProject = null;
    document.getElementById('btn-analysis').disabled = true;
    document.getElementById('btn-credentials').disabled = true;
    document.getElementById('btn-import').disabled = true;
    document.getElementById('current-project-name').textContent = '';
    cy.elements().remove();
    document.getElementById('stat-nodes').textContent = '0';
    document.getElementById('stat-edges').textContent = '0';
  }

  await loadProjects();
  updateEmptyState();
  toggleManageMode(); // exit manage mode
  toast('已删除 ' + deleted + ' 个项目');
}
