const { fmt, ui, $ } = Admin;

Admin.onRefresh(async () => {
  const payload = await Admin.api('/admin/api/searches?days=' + $('searches-days').value);
  const terms = payload.terms || [];
  const recent = payload.recent || [];
  const totals = payload.totals || {};

  $('searches-tiles').innerHTML = ui.tiles([
    ['searches', fmt.number(totals.searches), { icon: 'search', tone: 'info' }],
    ['distinct queries', fmt.number(totals.queries), { icon: 'list', tone: 'data' }],
    ['viewers searching', fmt.number(totals.viewers), { icon: 'people', tone: 'note' }],
    // Stated rather than assumed: every figure on this page is bounded by how long the
    // table keeps a row, and an operator reading a quiet week has no other way to tell a
    // household that stopped searching from one whose history has aged out.
    ['history kept', payload.retentionDays + ' days', { small: true, icon: 'clock' }],
  ]);

  $('searches-terms').innerHTML = terms.length ? terms.map((term) =>
    '<tr><td>' + fmt.escape(term.query) + '</td>' +
    '<td class="num">' + fmt.number(term.searches) + '</td>' +
    '<td class="num">' + fmt.number(term.viewers) + '</td>' +
    '<td class="muted">' + fmt.when(term.lastAt) + '</td></tr>').join('')
    : ui.emptyRow(4, 'Nothing searched in this window.');

  // An unattributed search keeps its row and shows the id: the query is the point, and a
  // viewer whose sessions have all expired is still one searcher rather than nobody.
  $('searches-recent').innerHTML = recent.length ? recent.map((event) =>
    '<tr><td class="muted">' + fmt.when(event.occurredAt) + '</td>' +
    '<td>' + (event.username
      ? fmt.escape(event.username)
      : ui.tag(event.userId || 'unknown', 'warn')) + '</td>' +
    '<td>' + fmt.escape(event.query) + '</td></tr>').join('')
    : ui.emptyRow(3, 'No searches in this window.');
});

Admin.ready(() => $('searches-days').addEventListener('change', Admin.refresh));
