/* ==============================================
   WebSocket
   ============================================== */
function connectWs() {
  const wsUrl = (location.protocol==='https:'?'wss:':'ws:') + '//' + location.host + '/api/ws';
  dbg('ws: connecting to ' + wsUrl);
  const ws = new WebSocket(wsUrl);
  ws.onopen = () => dbg('ws: connected');
  ws.onmessage = (e) => {
    const msg = e.data;
    dbg('ws: ' + msg);
    if (msg === 'projects') {
      const oldPid = currentProject;
      loadProjects().then(() => {
        if (oldPid && projects.find(p => p.id === oldPid)) {
          selectProject(oldPid);
        }
      });
    } else if (msg.startsWith('graph:')) {
      const pid = msg.slice(6);
      if (pid === currentProject) loadGraph();
    }
  };
  ws.onclose = () => { dbg('ws: closed, reconnect in 2s'); setTimeout(connectWs, 2000); };
  ws.onerror = () => ws.close();
}
