/* global React */
// Freshness pill: poll /api/sync-status every 60s; when the newest heartbeat
// advances past the baseline, show "New data available" (pill only, never an
// auto-reload while visible; silent reload when hidden and safe).
(() => {
  const e = React.createElement;
  const POLL_MS = 60000;

  function safeToReload() {
    const a = document.activeElement;
    if (a && /^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName)) return false;
    if (a && a.isContentEditable) return false;
    return true;
  }

  function UpdatePill() {
    const [show, setShow] = React.useState(false);
    const baseline = React.useRef(null);

    React.useEffect(() => {
      let alive = true;
      async function check() {
        try {
          const r = await fetch("/api/sync-status", { cache: "no-store" });
          if (!r.ok) return;
          const { latest } = await r.json();
          if (!alive || !latest) return;
          if (baseline.current === null) { baseline.current = latest; return; }
          if (latest > baseline.current) {
            if (document.hidden && safeToReload()) window.location.reload();
            else setShow(true);
          }
        } catch { /* fail safe: no change */ }
      }
      const t0 = setTimeout(check, 3000);
      const iv = setInterval(check, POLL_MS);
      const onVis = () => { if (!document.hidden) check(); };
      document.addEventListener("visibilitychange", onVis);
      window.addEventListener("focus", onVis);
      return () => {
        alive = false; clearTimeout(t0); clearInterval(iv);
        document.removeEventListener("visibilitychange", onVis);
        window.removeEventListener("focus", onVis);
      };
    }, []);

    if (!show) return null;
    return e("button", {
      className: "update-pill",
      onClick: () => window.location.reload(),
    },
      e("span", { className: "update-pill-dot" }),
      "New data available · Refresh");
  }

  Object.assign(window, { UpdatePill });
})();
