/*
  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) : [];
  }

  function loadHeroLogos(section, items) {
    const slides = section.querySelectorAll('.hero__slide');
    items.forEach((item, i) => {
      const slide = slides[i];
      if (!slide || !item || item.tmdbId == null) return;
      const titleEl = slide.querySelector('.hero__title');
      if (!titleEl) return;
      const logo = document.createElement('img');
      logo.className = 'hero__logo';
      logo.alt = item.name;
      logo.hidden = true;
      titleEl.insertAdjacentElement('beforebegin', logo);
      SR.api.details(item.type, item.tmdbId)
        .then((details) => {
          const images = (details && details.images) || {};
          const logos = images.logos || [];
          const url = (logos.find((l) => l && l.url && String(l.iso_639_1 || '').toLowerCase() === 'en') || {}).url;
          if (!url) return;
          logo.onerror = () => {
            logo.hidden = true;
            titleEl.hidden = false;
          };
          logo.src = SR.util.tmdbResize(url, 'w500');
          logo.hidden = false;
          titleEl.hidden = true;
        })
        .catch(() => {});
    });
  }

  (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);
        loadHeroLogos(hero, heroData);
      }
    } catch (e) {
      SR.app.showError(e, 'could not load featured titles');
    }
  })();
})();
