/*
  HOME — continue-watching row + trending rows.
*/
(function () {
  'use strict';

  SR.app.initChrome();

  const heroSlot = document.getElementById('heroSlot');
  const sections = document.getElementById('sections');

  const cont = SR.cards.continueRow();
  if (cont) sections.appendChild(cont);

  function appendRow(data, title) {
    if (!data || !data.count) return;
    sections.appendChild(SR.cards.row(title, data.results.map(SR.cards.normalizeItem)));
  }

  function itemsFrom(data) {
    return data && Array.isArray(data.results) ? data.results.map(SR.cards.normalizeItem) : [];
  }

  (async () => {
    const [movieRes, tvRes] = await Promise.allSettled([
      SR.api.trending('movie', 'day'),
      SR.api.trending('tv', 'week'),
    ]);

    if (movieRes.status === 'fulfilled') appendRow(movieRes.value, 'Trending movies today');
    else SR.app.showError(movieRes.reason, 'could not load trending movies');

    if (tvRes.status === 'fulfilled') appendRow(tvRes.value, 'Trending shows this week');
    else SR.app.showError(tvRes.reason, 'could not load trending shows');

    try {
      const heroData = [...itemsFrom(tvRes.value), ...itemsFrom(movieRes.value)]
        .filter((item) => item.backdrop && item.overview && item.name)
        .slice(0, 6);
      const hero = SR.cards.heroCarousel(heroData);
      if (hero) heroSlot.appendChild(hero);
    } catch (e) {
      SR.app.showError(e, 'could not load featured titles');
    }
  })();
})();
