// 'onboarding' MUST be in this list. It is a real page in the renderer below, but it used to be
// reachable only by an in-app go('onboarding') from the Hero / SubscribeCTA — so a direct
// https://readsynth.ca/#onboarding fell through to 'home'. The welcome email's primary CTA is
// exactly that URL, which would have landed every reader on the homepage (2026-09-09).
// 'privacy' and 'terms' are the interim legal pages (PR #4). All four route additions must
// coexist here — dropping any one silently re-breaks that route.
const HASH_PAGES = ['home','product','changing','faq','team','newsletters','onboarding','privacy','terms'];
function initialPage() {
  const h = (location.hash || '').replace('#','');
  return HASH_PAGES.indexOf(h) > -1 ? h : 'home';
}
// Email prefill. The wizard already accepts a seedEmail, but nothing ever read one from the URL,
// so an emailed "choose your teams" link made the reader retype the address we already knew — and
// the /lead capture in OnboardingPage is gated on a valid email, so it never fired either.
//
// The query must sit BEFORE the fragment (/?email=x#onboarding). The SPA is hash-routed, so in
// /#onboarding?email=x the query is part of the FRAGMENT and location.search is empty; we read the
// hash form too rather than silently dropping a link written that way.
function initialSeedEmail() {
  try {
    var q = new URLSearchParams(location.search).get('email');
    if (!q) {
      var h = location.hash || '';
      var i = h.indexOf('?');
      if (i > -1) q = new URLSearchParams(h.slice(i + 1)).get('email');
    }
    // Only accept something email-shaped. A junk value would put the wizard's final step into a
    // valid-looking state it cannot submit.
    return q && /.+@.+\..+/.test(q) ? q.trim() : '';
  } catch (e) {
    return '';   // malformed URI, ancient browser — the wizard still works, just unseeded
  }
}
function Site() {
  const [page, setPage] = React.useState(initialPage);
  const [shown, setShown] = React.useState(initialPage);
  const [op, setOp] = React.useState(1);
  const [seedEmail, setSeedEmail] = React.useState(initialSeedEmail);
  const go = (p, email) => {
    if (typeof email === 'string') setSeedEmail(email);
    if (p === page) return;
    setPage(p);
    setOp(0);
    setTimeout(() => { setShown(p); window.scrollTo(0, 0); setOp(1); }, 240);
  };
  // Respond to the URL changing after mount: pasting /#privacy into the address bar,
  // and browser back/forward. Without this `initialPage()` only runs on a cold load, so
  // a hash change would leave the app showing the previous page. No dep array — the
  // listener is cheap to re-register and this always closes over the current `go`
  // (which early-returns when the page is unchanged, so this cannot loop).
  React.useEffect(() => {
    const onHash = () => {
      const h = (location.hash || '').replace('#', '');
      go(HASH_PAGES.indexOf(h) > -1 ? h : 'home');
    };
    window.addEventListener('hashchange', onHash);
    window.addEventListener('popstate', onHash);
    return () => {
      window.removeEventListener('hashchange', onHash);
      window.removeEventListener('popstate', onHash);
    };
  });

  const dark = page === 'team' || page === 'product';
  const page5 = shown;
  return (
    <div style={{
      minHeight: '100vh',
      backgroundColor: dark ? 'var(--syn-navy)' : 'var(--syn-paper)',
      transition: 'background-color 520ms cubic-bezier(0.2,0.7,0.2,1)',
    }}>
      <Nav dark={dark} page={page} onNav={go} />
      <div style={{ opacity: op, transition: 'opacity 240ms cubic-bezier(0.2,0.7,0.2,1)' }}>
        {page5 === 'home' ? (
          <React.Fragment>
            <Hero onStart={email => go('onboarding', email)} />
            <SubscribeCTA onStart={email => go('onboarding', email)} />
          </React.Fragment>
        ) : page5 === 'product' ? (
          <ProductPage onNav={go} />
        ) : page5 === 'changing' ? (
          <ChangingPage onNav={go} />
        ) : page5 === 'faq' ? (
          <FAQPage onNav={go} />
        ) : page5 === 'onboarding' ? (
          <OnboardingPage seedEmail={seedEmail} onNav={go} />
        ) : page5 === 'newsletters' ? (
          <NewslettersPage onNav={go} />
        ) : page5 === 'privacy' ? (
          <LegalPage doc="privacy" onNav={go} />
        ) : page5 === 'terms' ? (
          <LegalPage doc="terms" onNav={go} />
        ) : (
          <TeamPage />
        )}
        {page5 === 'onboarding' ? null : <SiteFooter onNav={go} page={page5} />}
      </div>
    </div>
  );
}
// ---- email image-export mode ----------------------------------------------
// When loaded as ?card_export=1&team=IND&date=2025-12-08 the page renders ONLY the
// newsletter scaffolding for that (team,date), with per-card data-card anchors and NO
// nav/selector/footer chrome — a clean surface for the email image-render pipeline
// (scripts/render_email_from_site.py) to screenshot each card. This path is inert for
// normal visitors (guarded by the query param) so it never affects the live site.
function ExportScaffold() {
  const q = new URLSearchParams(location.search);
  const date = q.get('date');
  // LEAGUE mode: ?card_export=1&league=1&date=YYYY-MM-DD renders the teamless "All 32" edition
  // (window.SYNTH_LEAGUE_EDITIONS[date]) via SynthLeagueEdition; TEAM mode keys by team_date.
  const isLeague = q.get('league') === '1';  // exact contract the league renderer passes (?league=1)
  const team = q.get('team');
  const key = isLeague ? date : (team + '_' + date);
  const issue = isLeague
    ? (window.SYNTH_LEAGUE_EDITIONS || {})[date]
    : (window.SYNTH_ISSUES || {})[key];
  React.useEffect(() => {
    // signal readiness for the renderer to wait on (after fonts settle it screenshots)
    if (issue) document.documentElement.setAttribute('data-export-ready', '1');
    else document.documentElement.setAttribute('data-export-error', 'no-issue');
  }, []);
  return (
    <div style={{ background:'var(--syn-paper, #FBF7F1)', padding:'0' }}>
      {issue
        ? (isLeague
            ? <window.SynthLeagueEdition issue={issue} exportMode={true} />
            : <window.SynthScaffolding issue={issue} exportMode={true} />)
        : <div data-export-error="no-issue">No issue for {key}</div>}
    </div>
  );
}

(function mount() {
  const q = new URLSearchParams(location.search);
  const root = ReactDOM.createRoot(document.getElementById('root'));
  if (q.get('card_export')) root.render(<ExportScaffold />);
  else root.render(<Site />);
})();
