// Top-level app + nav + scroll progress

// Single source of truth for IA. Consumed by Nav (scroll-spy + render),
// MobileNavDrawer (U6), and the footer Quick links in contact.jsx.
// Collapsed from 11 entries to 6 (2026-08-02) — Elephants-in-the-Room now
// absorbs Water/Power/Noise/Lights as deep-linkable panels under one nav
// entry, so the top bar doesn't need a slot per topic. Water, Environment,
// Comparison, Regulations, Day/Night, Dividend, and Power all still render
// as full sections in page order (see <App /> below); they just aren't
// each their own nav item anymore.
const SECTIONS = [
  { id: 'overview',    label: 'Overview' },
  { id: 'answers',     label: 'Straight answers' },
  { id: 'viewpoint',   label: 'See the site' },
  { id: 'regulations', label: 'Commitments' },
  { id: 'faq',         label: 'FAQ' },
  { id: 'contact',     label: 'Questions' },
];
window.SECTIONS = SECTIONS;

function Nav() {
  const [section, setSection] = useState(SECTIONS[0].id);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const ids = SECTIONS.map(s => s.id);
    const onScroll = () => {
      setScrolled(window.scrollY > 60);
      const y = window.scrollY + 140;
      let cur = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) cur = id;
      }
      setSection(cur);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const link = (id, label) => (
    <a href={`#${id}`} className={section === id ? 'active' : ''}>{label}</a>
  );
  // Render every section except the last (Contact) inline; Contact gets the CTA pill.
  const navSections = SECTIONS.slice(0, -1);
  const contactSection = SECTIONS[SECTIONS.length - 1];
  return (
    <nav className={`topnav ${scrolled ? 'scrolled' : 'transparent'}`}>
      <div className="brand">
        <LogoMark size={22} color={scrolled ? 'var(--ink)' : 'var(--cream-50)'} />
        <span>{SITE.park}</span>
      </div>
      <div className="nav-inline">
        {navSections.map(s => <React.Fragment key={s.id}>{link(s.id, s.label)}</React.Fragment>)}
        <a href={`#${contactSection.id}`} className="cta">{contactSection.label}</a>
      </div>
      <MobileNavDrawer activeId={section} scrolled={scrolled} />
    </nav>
  );
}

function MobileNavDrawer({ activeId, scrolled }) {
  const [open, setOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(
    typeof window !== 'undefined' && window.matchMedia
      ? window.matchMedia('(max-width: 899px)').matches
      : false
  );

  // matchMedia change listener — fires exactly at the breakpoint crossing.
  useEffect(() => {
    if (!window.matchMedia) return;
    const mql = window.matchMedia('(max-width: 899px)');
    const onChange = (e) => {
      setIsMobile(e.matches);
      if (!e.matches) {
        // Crossing into desktop — force-close + release scroll lock.
        setOpen(false);
      }
    };
    if (mql.addEventListener) mql.addEventListener('change', onChange);
    else mql.addListener(onChange); // Safari < 14 fallback
    return () => {
      if (mql.removeEventListener) mql.removeEventListener('change', onChange);
      else mql.removeListener(onChange);
    };
  }, []);

  // Body scroll lock while open.
  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  // ESC key dismisses.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  if (!isMobile) return null;

  const hamburgerColor = scrolled ? 'var(--ink)' : 'var(--cream-50)';

  return (
    <>
      <button
        type="button"
        className="hamburger"
        aria-label="Toggle navigation"
        aria-expanded={open}
        aria-controls="mobile-nav-drawer"
        onClick={() => setOpen(v => !v)}
        style={{
          background: 'transparent',
          border: 'none',
          padding: '10px 6px',
          marginLeft: 'auto',
          cursor: 'pointer',
          display: 'inline-flex',
          flexDirection: 'column',
          gap: 5,
          alignItems: 'flex-end',
        }}
      >
        <span style={{ display: 'block', width: 24, height: 1.5, background: hamburgerColor, transition: 'background .2s' }} />
        <span style={{ display: 'block', width: 18, height: 1.5, background: hamburgerColor, transition: 'background .2s' }} />
        <span style={{ display: 'block', width: 24, height: 1.5, background: hamburgerColor, transition: 'background .2s' }} />
      </button>

      <div
        className={`mobile-nav-backdrop ${open ? 'open' : ''}`}
        onClick={() => setOpen(false)}
        aria-hidden="true"
      />

      <aside
        id="mobile-nav-drawer"
        className={`mobile-nav-drawer ${open ? 'open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-label="Site navigation"
      >
        <div className="mobile-nav-drawer__head">
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--slate-500)' }}>
            Index
          </span>
          <button
            type="button"
            aria-label="Close navigation"
            onClick={() => setOpen(false)}
            style={{
              background: 'transparent',
              border: 'none',
              fontSize: 24,
              lineHeight: 1,
              cursor: 'pointer',
              color: 'var(--ink)',
              padding: '4px 8px',
            }}
          >
            ×
          </button>
        </div>

        <nav className="mobile-nav-drawer__list">
          {SECTIONS.map((s, i) => (
            <a
              key={s.id}
              href={`#${s.id}`}
              className={activeId === s.id ? 'active' : ''}
              onClick={() => setOpen(false)}
            >
              <span className="mobile-nav-drawer__num">{String(i + 1).padStart(2, '0')}</span>
              <span className="mobile-nav-drawer__label">{s.label}</span>
            </a>
          ))}
        </nav>
      </aside>
    </>
  );
}

function ScrollProgress() {
  useEffect(() => {
    const fill = document.getElementById('scrollbar-fill');
    const onScroll = () => {
      const h = document.documentElement;
      const pct = (h.scrollTop) / (h.scrollHeight - h.clientHeight) * 100;
      if (fill) fill.style.width = pct + '%';
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return null;
}

function App() {
  useEffect(() => {
    const scrollToHash = () => {
      const id = decodeURIComponent(window.location.hash.replace(/^#/, ''));
      if (!id) return;
      const el = document.getElementById(id);
      if (!el) return;
      requestAnimationFrame(() => el.scrollIntoView({ block: 'start' }));
    };

    scrollToHash();
    window.addEventListener('hashchange', scrollToHash);
    return () => window.removeEventListener('hashchange', scrollToHash);
  }, []);

  // Render order: Hero -> Elephants -> Water -> Environment -> Viewpoint ->
  // Comparison -> Regulations -> DayNight(+Noise) -> Power -> Dividend ->
  // FAQ -> Contact. Doesn't match SECTIONS 1:1 anymore (see note above) —
  // SECTIONS is nav IA, this is page IA.
  //
  // Power now renders BEFORE Dividend (2026-08-02 roundtable redesign,
  // spec item 3) — benefits after risk answers, not before. The $13B/jobs
  // figures already moved out of the Hero for the same reason (see
  // hero.jsx); this keeps the same "risk answers first" ordering all the
  // way through the page, not just at the top.
  return (
    <>
      <ScrollProgress />
      <Nav />
      <Hero />
      <Elephants />
      <Water />
      <Environment />
      <Radar />
      <Comparison />
      <Regulations />
      <DayNight />
      <Power />
      <Dividend />
      <FAQ />
      <Contact />
      <Tweaks />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
