/* A directory, and only a directory. Everything you can *do* to a person lives on their own
   page: this list used to render a full seventeen-control settings editor for every account
   at once, which meant the page grew with the household and an operator scrolled past four
   other people's preferences to reach the one they came for. */

const { fmt, ui, $ } = Admin;

function accountRow(account) {
  const devices = account.devices || [];
  const active = devices.filter((device) => fmt.recent(device.lastSeen)).length;
  const prompt = account.recommendations || {};
  const state = prompt.completed
    ? ui.tag('personalised', 'ok')
    : prompt.prompted ? ui.tag('prompt queued', 'warn') : ui.tag('not invited', 'idle');
  const seen = fmt.presence(account.lastSeen);
  return '<a class="list-row" href="/admin/accounts/' + encodeURIComponent(account.id) + '">' +
    '<span class="list-main">' +
      '<span class="avatar">' + fmt.escape(fmt.initials(account.username)) + '</span>' +
      '<span>' +
        '<span class="list-title">' + fmt.escape(account.username || 'Unnamed user') +
          '<span class="dot" data-tone="' + seen.tone + '" title="' + seen.label + '"></span>' +
          '</span>' +
        '<span class="list-meta">' + fmt.number(devices.length) + ' device' +
          (devices.length === 1 ? '' : 's') +
          (active ? ' · ' + active + ' active now' : '') +
          ' · last seen ' + fmt.escape(fmt.when(account.lastSeen)) + '</span>' +
      '</span>' +
    '</span>' +
    '<span class="list-actions">' + state + '<span class="crumb">Manage</span></span></a>';
}

Admin.onRefresh(async () => {
  const payload = await Admin.api('/admin/api/accounts');
  const accounts = payload.accounts || [];
  const devices = accounts.flatMap((account) => account.devices || []);
  const prompts = accounts.filter((account) => account.recommendations?.completed).length;
  const queued = accounts.filter((account) =>
    account.recommendations?.prompted && !account.recommendations?.completed).length;

  $('account-tiles').innerHTML = ui.tiles([
    ['Memby users', fmt.number(accounts.length), { icon: 'people', tone: 'note' }],
    ['signed-in devices', fmt.number(devices.length), { icon: 'tv', tone: 'info' }],
    ['active in the last quarter hour', fmt.number(devices.filter((device) =>
      fmt.recent(device.lastSeen)).length), { icon: 'pulse', tone: 'ok' }],
    ['recommendation setups completed', fmt.number(prompts), { icon: 'check', tone: 'ok' }],
    ['setup prompts queued', fmt.number(queued), { icon: 'sparkle', tone: 'note' }],
  ]);

  $('account-list').innerHTML = accounts.length
    ? accounts.map(accountRow).join('')
    : ui.empty('No one has signed in to Memby yet. Emby-only accounts are intentionally not listed here.');
});
