/* global React, ReactDOM, useDeck, FirehoseColumn, RadarColumn, PodcastColumn, SynthesisColumn, UpdatePill */
// Root shell: top bar + the deck.
(() => {
  const e = React.createElement;

  function freshnessOf(heartbeats) {
    if (!heartbeats || !heartbeats.length) return null;
    const latest = heartbeats.reduce((m, h) => (h.last_run_at > m ? h.last_run_at : m), "");
    if (!latest) return null;
    const then = new Date(latest.replace(" ", "T") + (latest.includes("Z") ? "" : "Z"));
    const hours = (Date.now() - then.getTime()) / 3600000;
    const label = then.toLocaleString("en-US", {
      month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
    });
    return { label, stale: hours > 30 };
  }

  function App() {
    const { data, error, loading } = useDeck(7, 21);
    const tweets = (data && data.tweets) || [];
    const podcasts = (data && data.podcasts) || [];
    const pod7 = podcasts.filter((p) => {
      const [y, m, d] = p.published_at.split("-").map(Number);
      return (Date.now() - new Date(y, m - 1, d).getTime()) / 86400000 <= 7;
    });
    const fresh = freshnessOf(data && data.heartbeats);

    if (error) {
      return e("div", { className: "load-error" },
        "failed to load the deck; check /api/deck and the D1 binding");
    }

    return e(React.Fragment, null,
      e("header", { className: "topbar" },
        e("div", { className: "brand" },
          e("span", { className: "zg-mark" }, "zeitgeist"),
          e("span", { className: "zg-sub" }, "THE WEEK, DISTILLED")),
        e("div", { className: "topbar-stats" },
          !loading && e("span", { className: "tabnum hide-sm" },
            `${tweets.length} tweets · ${pod7.length} episodes · trailing 7 days`),
          fresh && e(React.Fragment, null,
            e("span", { className: `dot${fresh.stale ? " stale" : ""}` }),
            e("span", { className: "tabnum" }, `refreshed ${fresh.label}`)))),
      e("main", { className: "deck" },
        e(SynthesisColumn, { synthesis: data && data.synthesis, loading }),
        e(FirehoseColumn, { tweets, loading }),
        e(RadarColumn, { tweets, loading }),
        e(PodcastColumn, { podcasts, loading })),
      e(UpdatePill));
  }

  ReactDOM.createRoot(document.getElementById("root")).render(e(App));
})();
