const { fmt, ui, $ } = Admin;

// Every build this set has been seen running, newest first, with the one it is on now in
// accent. The current version is already its own column; this is the column that says
// whether a row is one television with a history or one of several rows a single set left
// behind, which is the question duplicates used to make unanswerable.
function versionHistory(client) {
  const versions = client.versions || [];
  if (!versions.length) return '<span class="muted">—</span>';
  return '<span class="list-versions">' + versions.map((entry) =>
    ui.chip(entry.version, entry.version === client.version ? 'accent' : null)).join('') +
    '</span>';
}

Admin.onStatus((status) => {
  const clients = status.clients || [];
  const capable = clients.filter((client) =>
    (client.capabilities || []).includes('server_features_v1'));
  const versions = new Set(clients.map((client) => client.version).filter(Boolean));

  $('client-tiles').innerHTML = ui.tiles([
    ['devices known', fmt.number(clients.length), { icon: 'tv', tone: 'info' }],
    ['active in the last quarter hour', fmt.number(clients.filter((client) =>
      fmt.recent(client.lastSeen)).length), { icon: 'pulse', tone: 'ok' }],
    ['reporting their capabilities', fmt.number(capable.length), { icon: 'sliders', tone: 'ok' }],
    ['app builds in service', fmt.number(versions.size), { icon: 'download', tone: 'note' }],
  ]);

  $('client-rows').innerHTML = clients.length ? clients.map((client) => {
    const declares = (client.capabilities || []).includes('server_features_v1');
    const seen = fmt.presence(client.lastSeen);
    return '<tr><td><span class="row tight">' +
        '<span class="dot" data-tone="' + seen.tone + '" title="' + seen.label + '"></span>' +
        fmt.escape(client.deviceName || 'Memby TV') + '</span></td>' +
      '<td>' + fmt.escape(client.username) + '</td>' +
      '<td>' + fmt.escape(client.version || 'legacy') + '</td>' +
      '<td>' + versionHistory(client) + '</td>' +
      '<td>' + ui.tag(declares ? 'reported' : 'missing', declares ? 'ok' : 'warn') + '</td>' +
      '<td>' + fmt.escape(fmt.when(client.lastSeen)) + '</td></tr>';
  }).join('') : ui.emptyRow(6, 'No devices have signed in yet.');
});
