window.tvConn = {
  save: function(id) { localStorage.setItem('tv_conn', String(id)); },
  load: function() { return localStorage.getItem('tv_conn'); },

  // Normalize raw /api/connections response:
  // - filters out removed_connection rows
  // - adds a label field (display name for option text)
  parseList: function(data) {
    // Two API shapes are in use and both must work: /api/connections returns a
    // BARE ARRAY (13 callers), while /api/ebs-deep/connections returns a WRAPPER
    // {connections:[...]}. Returning [] for the wrapper silently blanked the
    // entire Deep EBS page — it showed "Demo data (no EBS connections)" to users
    // who had connections, and the SSH-checks selector with it. A silent [] is
    // indistinguishable from "you genuinely have none", so an unusable payload
    // now warns instead of vanishing.
    var list = Array.isArray(data) ? data
             : (data && Array.isArray(data.connections)) ? data.connections
             : null;
    if (list === null) {
      if (data !== null && data !== undefined && typeof console !== 'undefined') {
        console.warn('[tvConn] parseList: unusable payload, expected an array or {connections:[...]} — got', data);
      }
      return [];
    }
    return list
      .filter(function(c) { return !c.removed_connection; })
      .map(function(c) {
        return Object.assign({}, c, {
          label: c.name || (c.host + (c.port ? ':' + c.port : ''))
        });
      });
  },

  // Restore last-used connection in a <select> element.
  // Sets sel.value to the saved ID only if it still exists in connections.
  bind: function(sel, connections) {
    var saved = localStorage.getItem('tv_conn');
    if (!saved) return;
    var found = connections.some(function(c) { return String(c.id) === saved; });
    if (found) sel.value = saved;
  }
};
