const { fmt, ui, $ } = Admin;

// Display names for the providers MDBList answers with. An unknown key is shown as itself
// rather than hidden — a source the server offers and the console cannot name is still a
// source the operator may want on.
const sourceNames = {
  imdb: 'IMDb', tomatoes: 'Rotten Tomatoes', audience: 'Rotten Tomatoes Audience',
  metacritic: 'Metacritic', letterboxd: 'Letterboxd', rogerebert: 'Roger Ebert',
  tmdb: 'TMDb', trakt: 'Trakt', mal: 'MyAnimeList', anilist: 'AniList',
  anidb: 'AniDB', kitsu: 'Kitsu', score: 'MDBList Score', score_average: 'MDBList Average',
};

Admin.onStatus((status) => {
  const mdblist = status.mdblist || {};
  const cached = Number(mdblist.cachedTitles || 0);

  $('ratings-tiles').innerHTML = ui.tiles([
    ['titles stored', fmt.number(cached), { icon: 'database', tone: 'data' }],
    ['due to be re-checked', fmt.number(mdblist.staleTitles), { icon: 'sync', tone: 'warn' }],
    ['sources shown', fmt.number((mdblist.sources || []).length), { icon: 'star', tone: 'note' }],
    ['API key', mdblist.apiKeyConfigured ? 'saved' : 'not set',
      { small: true, icon: 'key', tone: mdblist.apiKeyConfigured ? 'ok' : undefined }],
  ]);

  Admin.check($('mdblist-enabled'), mdblist.enabled);
  $('mdblist-state').innerHTML = mdblist.enabled
    ? ui.tag('on · ' + (mdblist.sources || []).length + ' sources', 'ok')
    : ui.tag(mdblist.apiKeyConfigured ? 'off · key saved' : 'off · no key', 'idle');

  $('mdblist-cache').textContent = cached
    ? 'Ratings are fetched as televisions browse, never on the request path.'
    : 'No ratings stored yet. They are saved as televisions browse the library.';

  const keyField = $('mdblist-api-key');
  keyField.placeholder = mdblist.apiKeyConfigured
    ? 'Saved key (leave blank to keep)' : 'Paste an API key';

  const sources = $('mdblist-sources');
  if (!Admin.settled(sources)) return;
  const selected = new Set(mdblist.sources || []);
  sources.innerHTML = (mdblist.availableSources || []).map((source) =>
    '<label class="check"><input type="checkbox" data-mdblist-source="' + fmt.escape(source) + '"' +
    (selected.has(source) ? ' checked' : '') + '><span>' +
    fmt.escape(sourceNames[source] || source) + '</span></label>').join('') ||
    ui.empty('No rating sources are available.');
});

Admin.ready(() => {
  $('mdblist-save').addEventListener('click', () => {
    const sources = [...document.querySelectorAll('[data-mdblist-source]:checked')]
      .map((box) => box.dataset.mdblistSource);
    Admin.act(() => Admin.api('/admin/api/mdblist-settings', {
      method: 'POST',
      body: JSON.stringify({
        enabled: $('mdblist-enabled').checked,
        apiKey: $('mdblist-api-key').value.trim(),
        clearApiKey: $('mdblist-clear-key').checked,
        sources,
      }),
    }).then(() => {
      $('mdblist-api-key').value = '';
      $('mdblist-clear-key').checked = false;
    }));
  });
});
