const { fmt, ui, $ } = Admin;

const label = (value) => {
  const text = String(value || '—').replaceAll('_', ' ');
  if (text === 'favorites') return 'Favourites';
  if (text === 'abandoned') return 'Abandoned / interrupted';
  return text;
};

Admin.onRefresh(async () => {
  const payload = await Admin.api('/admin/api/analytics?days=' + $('engagement-days').value);
  const rows = payload.rows || [];
  $('engagement-rows').innerHTML = rows.length ? rows.map((row) =>
    '<tr><td>' + fmt.escape(label(row.rowId)) + '</td>' +
    '<td class="muted">' + fmt.escape(label(row.rowKind)) + '</td>' +
    '<td class="num">' + fmt.duration(row.dwellMs) + '</td>' +
    '<td class="num">' + fmt.number(row.impressions) + '</td>' +
    '<td class="num">' + fmt.number(row.focuses) + '</td>' +
    '<td class="num">' + fmt.number(row.selects) + '</td>' +
    '<td class="num">' + Math.round((row.selectRate || 0) * 100) + '%</td>' +
    '<td class="num">' + fmt.number(row.viewers) + '</td></tr>').join('')
    : ui.emptyRow(8, 'No events in this window.');

});

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