// Banner "NUEVO CAPÍTULO" / "PRÓXIMAMENTE" en la sala.
// Lógica:
//   - Si hay caps programados a futuro → muestra el más cercano con countdown.
//   - Si no, busca caps publicados en los últimos 14 días NO leídos por el user.
//   - Si nada de lo anterior, no renderiza nada.

const NEW_CHAPTER_RECENT_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;

function findFeaturedChapterNCB(arcs, readIds) {
  const now = Date.now();
  const all = [];
  for (const a of arcs || []) {
    for (const c of a.chapters || []) {
      if (!c.publishAt) continue;
      const t = new Date(c.publishAt).getTime();
      if (isNaN(t)) continue;
      all.push({ chapter: c, arc: a, publishMs: t });
    }
  }

  // Próximo programado (futuro), el más cercano.
  const upcoming = all
    .filter(x => x.publishMs > now)
    .sort((a, b) => a.publishMs - b.publishMs)[0];
  if (upcoming) return { ...upcoming, status: "upcoming" };

  // Reciente disponible no leído.
  const reads = readIds || new Set();
  const recent = all
    .filter(x => x.publishMs <= now && now - x.publishMs <= NEW_CHAPTER_RECENT_WINDOW_MS)
    .filter(x => !reads.has(x.chapter.id))
    .sort((a, b) => b.publishMs - a.publishMs)[0];
  if (recent) return { ...recent, status: "available" };

  return null;
}

function formatCountdownNCB(ms) {
  if (ms <= 0) return "ahora";
  const sec = Math.floor(ms / 1000);
  const min = Math.floor(sec / 60);
  const hour = Math.floor(min / 60);
  const day = Math.floor(hour / 24);
  if (day >= 2) return `en ${day} días`;
  if (day === 1) return `en 1 día`;
  if (hour >= 2) return `en ${hour} horas`;
  if (hour === 1) return `en 1 hora`;
  if (min >= 2) return `en ${min} min`;
  if (min === 1) return `en 1 min`;
  return `en ${sec} s`;
}

function formatDateNCB(iso) {
  const d = new Date(iso);
  if (isNaN(d.getTime())) return "";
  return d.toLocaleDateString("es-MX", { day: "2-digit", month: "short" })
    + " · " + d.toLocaleTimeString("es-MX", { hour: "2-digit", minute: "2-digit" });
}

function NewChapterBanner({ user, readIds, onOpenChapter }) {
  const t = (typeof window !== "undefined" && window.t) ? window.t : ((k) => k);
  const lang = (typeof window !== "undefined" && window.useLang) ? window.useLang() : "es";
  // Re-render cada minuto para que el countdown avance.
  const [, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(x => x + 1), 60 * 1000);
    return () => clearInterval(id);
  }, []);

  const [store] = window.NovelStore.useNovelStore();

  if (!user) return null;
  const reads = (readIds instanceof Set) ? readIds : new Set();
  const featured = findFeaturedChapterNCB(store?.arcs || [], reads);
  if (!featured) return null;

  const { chapter, arc, status, publishMs } = featured;
  const isUpcoming = status === "upcoming";
  const ra = (typeof window !== "undefined" && window.resolveArc) ? window.resolveArc(arc, lang) : arc;
  const rc = (typeof window !== "undefined" && window.resolveChapter) ? window.resolveChapter(chapter, lang) : chapter;

  // Countdown traducido al idioma actual.
  const countdownLabel = (() => {
    const ms = publishMs - Date.now();
    if (ms <= 0) return t("banner.almost");
    const sec = Math.floor(ms / 1000);
    const min = Math.floor(sec / 60);
    const hour = Math.floor(min / 60);
    const day = Math.floor(hour / 24);
    if (day >= 1) return t("banner.in.days", day);
    if (hour >= 1) return t("banner.in.hours", hour);
    if (min >= 1) return t("banner.in.minutes", min);
    return t("banner.almost");
  })();

  const eyebrow = isUpcoming ? t("banner.upcoming") : t("banner.new");
  const meta = isUpcoming
    ? formatDateNCB(chapter.publishAt) + " · " + countdownLabel
    : t("banner.available");

  const click = () => {
    if (isUpcoming) return; // no se puede abrir aún
    if (typeof onOpenChapter === "function") onOpenChapter(chapter, arc);
  };

  const accent = arc?.cover?.accent || "#ff5aa0";

  return (
    <div
      className={"new-chapter-banner" + (isUpcoming ? " is-upcoming" : " is-available")}
      onClick={click}
      style={{ "--ncb-accent": accent }}
    >
      {rc.image && (
        <div className="new-chapter-banner-bg" style={{ backgroundImage: `url("${rc.image}")` }} />
      )}
      <div className="new-chapter-banner-shade" />
      <div className="new-chapter-banner-body">
        <div className="new-chapter-banner-eyebrow" style={{ color: accent }}>{eyebrow}</div>
        <div className="new-chapter-banner-title">{rc.title}</div>
        <div className="new-chapter-banner-sub">
          {ra.title} · {t("reader.cap")} {chapter.num}
        </div>
        <div className="new-chapter-banner-meta">{meta}</div>
      </div>
    </div>
  );
}

window.NewChapterBanner = NewChapterBanner;
