const { fmt, ui, $ } = Admin;

Admin.onStatus((status) => {
  const forYou = status.forYou || {};
  $('for-you-tiles').innerHTML = ui.tiles([
    ['Tracearr sessions', fmt.number(forYou.tracearrSessions), { icon: 'play', tone: 'info' }],
    ['user profiles', fmt.number(forYou.profiles), { icon: 'people', tone: 'note' }],
    ['ranked candidates', fmt.number(forYou.candidates), { icon: 'sparkle', tone: 'note' }],
    ['last full import', fmt.when(forYou.lastFullImport), { small: true, icon: 'clock' }],
  ]);

  const running = Boolean(status.forYouRunning);
  ['for-you-import', 'for-you-full', 'for-you-rebuild'].forEach((id) => {
    $(id).disabled = running;
  });
  $('for-you-hint').textContent = running
    ? 'For You maintenance running…'
    : 'Prepared pools normally refresh in the background.';
});

const action = (name) => Admin.api('/admin/api/for-you', {
  method: 'POST', body: JSON.stringify({ action: name }),
});

Admin.ready(() => {
  $('for-you-import').addEventListener('click', () =>
    Admin.act(() => action('incremental-import')));
  $('for-you-full').addEventListener('click', () => {
    if (!confirm('Backfill all Tracearr history and rebuild every active user pool?')) return;
    Admin.act(() => action('full-import'));
  });
  $('for-you-rebuild').addEventListener('click', () => Admin.act(() => action('rebuild-all')));
});
