// ===========================================================
// TodayPage — /today, a stable URL for the one thing here with a daily cadence.
//
// Album of the Day had an email and (since 2 Aug) a homepage card, but no
// destination: nothing to put in a bio link, nothing for the email to point at
// beyond a specific essay, and no page that answers "what's today's record?" for
// somebody who has not signed up. That is what this is. It is deliberately a
// visit target, not an essay — the essay is one click away.
//
// The pick MUST agree with the morning email and the homepage card, so it calls
// bbrAlbumOfDay() from TodayCard.jsx rather than recomputing the rotation. If that
// file has not loaded yet the page renders nothing rather than a different record.
//
// The countdown is driven by setInterval and recomputed from Date() on every tick,
// so a throttled or backgrounded tab self-corrects when it wakes. It is decoration:
// the page is complete and correct without it ever firing, which is the lesson from
// the homepage counters that froze in background tabs.
// ===========================================================
const { useState: useTpState, useEffect: useTpEffect } = React;

// Milliseconds until the next UTC midnight, when the rotation advances.
function bbrMsToRollover() {
  const n = new Date();
  const next = Date.UTC(n.getUTCFullYear(), n.getUTCMonth(), n.getUTCDate() + 1);
  return Math.max(0, next - n.getTime());
}

function bbrCountdownLabel(ms) {
  const total = Math.floor(ms / 1000);
  const h = Math.floor(total / 3600);
  const m = Math.floor((total % 3600) / 60);
  if (h >= 1) return h + "h " + String(m).padStart(2, "0") + "m";
  if (m >= 1) return m + "m";
  return "moments";
}

function TodayPage({ onAlbum, onHome, onList, user }) {
  const store = window.BBR_store;
  const [, force] = useTpState(0);
  const [left, setLeft] = useTpState(bbrMsToRollover());

  useTpEffect(() => (store ? store.subscribe(() => force((n) => n + 1)) : undefined), []);

  useTpEffect(() => {
    // Recomputed from the clock each tick, so this survives being throttled.
    const t = setInterval(() => setLeft(bbrMsToRollover()), 30000);
    return () => clearInterval(t);
  }, []);

  const pick = window.bbrAlbumOfDay;
  const album = pick ? pick(0) : null;
  if (!album) return null;

  const visit = store && store.visit;
  const streak = visit && visit.streakDays > 1 ? visit.streakDays : 0;
  const essay = (window.ESSAYS_FULL && window.ESSAYS_FULL[album.slug]) || {};
  const hook = (window.BLURBS && window.BLURBS[album.rank]) ||
    (essay.essay && essay.essay.dek) || "";

  // The four days behind us. Not the days ahead — knowing tomorrow's record is
  // the one thing that would remove the reason to come back tomorrow.
  const recent = [];
  for (let d = 1; d <= 4; d++) {
    const a = pick(-d);
    if (a) recent.push(a);
  }

  const dateLabel = new Date().toLocaleDateString("en-GB", {
    weekday: "long", day: "numeric", month: "long", timeZone: "UTC",
  });

  return (
    <main className="tdp">
      <div className="tdp-inner">
        <nav className="tdp-crumb" aria-label="Breadcrumb">
          <a href="/" onClick={(e) => { if (!e.metaKey && !e.ctrlKey && e.button === 0) { e.preventDefault(); onHome && onHome(); } }}>The Lead-In</a>
          <span aria-hidden="true"> / </span>
          <span>Today</span>
        </nav>

        <header className="tdp-head">
          <div className="tdp-kicker">
            Today from the canon
            <span className="tdp-date"> · {dateLabel}</span>
          </div>
          <h1 className="tdp-title">
            One record a day, out of the hundred.
          </h1>
          <p className="tdp-standfirst">
            The same record as this morning&rsquo;s email, chosen by the date rather than by us,
            so everybody reading is on the same one. It changes in <strong>{bbrCountdownLabel(left)}</strong>.
          </p>
        </header>

        <section className="tdp-pick" aria-labelledby="tdp-pick-h">
          <div className="tdp-cover">
            <img src={"/covers/" + album.slug + ".jpg"}
                 alt={album.title + " — " + album.artist}
                 width="320" height="320" />
          </div>
          <div className="tdp-meta">
            <div className="tdp-rank">&#8470;{album.rank} of the hundred</div>
            <h2 className="tdp-album" id="tdp-pick-h">{album.title}</h2>
            <div className="tdp-artist">{album.artist} · {album.year}{album.genre ? " · " + album.genre : ""}</div>
            {hook ? <p className="tdp-hook">{hook}</p> : null}
            <div className="tdp-actions">
              <button className="tdp-cta" onClick={() => onAlbum && onAlbum(album.slug)}>
                Read the case for &#8470;{album.rank} &rarr;
              </button>
              <button className="tdp-cta2" onClick={() => onList && onList()}>
                See all 100
              </button>
            </div>
            {streak ? (
              <div className="tdp-streak" title="Consecutive days you have visited">
                You&rsquo;re on a <strong>{streak}-day streak</strong>. Come back tomorrow to keep it.
              </div>
            ) : user ? (
              <div className="tdp-streak">
                Visit tomorrow and a streak starts counting here.
              </div>
            ) : (
              <div className="tdp-streak">
                Sign in and this page starts counting your streak.
              </div>
            )}
          </div>
        </section>

        {/* The notification ask lives here rather than in settings alone: this is the
            page a returning collector opens, so it is where an offer to interrupt
            them is least unwelcome. Asked once — it remembers "Not now". */}
        {window.PushOptIn ? <PushOptIn variant="inline" user={user} /> : null}

        {recent.length ? (
          <section className="tdp-recent" aria-labelledby="tdp-recent-h">
            <h2 className="tdp-recent-h" id="tdp-recent-h">The last few days</h2>
            <ul className="tdp-recent-list">
              {recent.map((a, i) => (
                <li key={a.slug}>
                  <a href={"/album/" + a.slug}
                     onClick={(e) => { if (!e.metaKey && !e.ctrlKey && e.button === 0) { e.preventDefault(); onAlbum && onAlbum(a.slug); } }}>
                    <img src={"/covers/" + a.slug + ".jpg"} alt="" width="64" height="64" loading="lazy" />
                    <span className="tdp-recent-when">{i === 0 ? "Yesterday" : i + 1 + " days ago"}</span>
                    <span className="tdp-recent-title">{a.title}</span>
                    <span className="tdp-recent-artist">{a.artist}</span>
                  </a>
                </li>
              ))}
            </ul>
          </section>
        ) : null}
      </div>
    </main>
  );
}

Object.assign(window, { TodayPage });
