import { t, getSiteLocale, dataJsonUrl } from "../config/site.js";
import { apiUrl } from "../auth/session.js";
import { escapeHtml } from "../utils/escape-html.js";

/** Site alt menü ile aynı: lg = 1024px */
const HOME_FEED_MOBILE_MQ = "(max-width: 1023px)";

let homeYoutubeMount = null;

function formatVideoAge(publishedAt, locale) {
  const ts = Date.parse(publishedAt || "");
  if (!Number.isFinite(ts)) return "";
  const diffSec = Math.max(0, Math.floor((Date.now() - ts) / 1000));
  const tr = locale !== "en";

  if (diffSec < 3600) {
    const m = Math.max(1, Math.floor(diffSec / 60));
    return tr ? `${m}dk` : `${m}m`;
  }
  if (diffSec < 86400) {
    const h = Math.max(1, Math.floor(diffSec / 3600));
    return tr ? `${h}s` : `${h}h`;
  }
  if (diffSec < 86400 * 30) {
    const d = Math.max(1, Math.floor(diffSec / 86400));
    return tr ? `${d}g` : `${d}d`;
  }
  if (diffSec < 86400 * 365) {
    const mo = Math.max(1, Math.floor(diffSec / (86400 * 30)));
    return tr ? `${mo}ay` : `${mo}mo`;
  }
  const y = Math.max(1, Math.floor(diffSec / (86400 * 365)));
  return tr ? `${y}y` : `${y}y`;
}

function isHomeFeedMobile() {
  return window.matchMedia(HOME_FEED_MOBILE_MQ).matches;
}

function videoCardHtml(video, locale) {
  const title = escapeHtml(String(video.title || t("homeYoutubeUntitled")));
  const url = escapeHtml(String(video.url || "#"));
  const thumb = escapeHtml(String(video.thumbnail || ""));
  const isLive = Boolean(video.isLive);
  const isStream = Boolean(video.isStream);
  const age = isLive
    ? t("homeYoutubeLive")
    : isStream
      ? t("homeYoutubeStream")
      : formatVideoAge(video.publishedAt, locale);
  const ageClass = isLive || isStream ? " home-youtube-feed__age--live" : "";

  return `
    <article class="home-youtube-feed__card" role="listitem">
      <a href="${url}" class="home-youtube-feed__link" target="_blank" rel="noopener noreferrer" aria-label="${title}">
        <span class="home-youtube-feed__thumb">
          <img src="${thumb}" alt="" loading="lazy" decoding="async" class="home-youtube-feed__img" />
          ${isLive ? `<span class="home-youtube-feed__live-dot" aria-hidden="true"></span>` : ""}
          ${age ? `<span class="home-youtube-feed__age${ageClass}">${escapeHtml(age)}</span>` : ""}
        </span>
        <span class="home-youtube-feed__video-title">${title}</span>
      </a>
    </article>`;
}

/** @type {object | null} */
let youtubeFeedCache = null;

/** @type {Promise<object | null> | null} */
let youtubeFeedLoadPromise = null;

async function fetchYoutubeFeedData() {
  try {
    const r = await fetch(apiUrl("youtube_feed.php"), { credentials: "omit", cache: "default" });
    const data = await r.json().catch(() => ({}));
    if (r.ok && data?.ok && Array.isArray(data.videos) && data.videos.length) {
      return data;
    }
  } catch {
    /* API unavailable */
  }

  try {
    const r = await fetch(dataJsonUrl("youtube_feed.json"), { credentials: "omit", cache: "default" });
    const data = await r.json().catch(() => ({}));
    if (data?.ok && Array.isArray(data.videos) && data.videos.length) {
      return data;
    }
  } catch {
    /* no snapshot */
  }

  return null;
}

async function loadYoutubeFeedData() {
  if (youtubeFeedCache) return youtubeFeedCache;
  if (!youtubeFeedLoadPromise) {
    youtubeFeedLoadPromise = fetchYoutubeFeedData()
      .then((data) => {
        if (data) youtubeFeedCache = data;
        return data;
      })
      .finally(() => {
        youtubeFeedLoadPromise = null;
      });
  }
  return youtubeFeedLoadPromise;
}

export function prefetchHomeYoutubeFeed() {
  return loadYoutubeFeedData();
}

export function destroyHomeYoutubeFeed() {
  homeYoutubeMount = null;
}

export async function renderHomeYoutubeFeed(mount) {
  if (!mount) return;
  destroyHomeYoutubeFeed();
  homeYoutubeMount = mount;
  mount.innerHTML = "";

  const data = await loadYoutubeFeedData();
  if (!data) {
    mount.innerHTML = "";
    homeYoutubeMount = null;
    return;
  }

  const locale = getSiteLocale();
  const channelUrl = String(data.channelUrl || "").trim();
  const mobile = isHomeFeedMobile();
  const maxVideos = mobile ? 4 : 8;
  const videos = data.videos.slice(0, maxVideos);

  mount.innerHTML = `
    <section class="home-youtube-feed" aria-labelledby="home-youtube-feed-heading">
      <div class="home-youtube-feed__head">
        <h2 id="home-youtube-feed-heading" class="home-youtube-feed__heading">${escapeHtml(t("homeYoutubeFeedTitle"))}</h2>
        ${
          channelUrl
            ? `<a href="${escapeHtml(channelUrl)}" class="home-youtube-feed__channel-link" target="_blank" rel="noopener noreferrer">${escapeHtml(t("homeYoutubeChannelCta"))}</a>`
            : ""
        }
      </div>
      <div class="home-youtube-feed__viewport">
        <div class="home-youtube-feed__track" role="list">
          ${videos.map((v) => videoCardHtml(v, locale)).join("")}
        </div>
      </div>
    </section>
  `;
}
