// App shell: layout + page routing
const { useState: useStateA, useEffect: useEffectA } = React;

function Stub({ title }) {
  return (
    <div style={{ paddingTop: 64 }}>
      <h1 className="display" style={{ fontSize: "clamp(40px,5.4vw,76px)", marginTop: 24 }}>{title}</h1>
      <Footer />
    </div>);

}

function App() {
  const [page, setPage] = useStateA("home");
  const scrollerRef = React.useRef(null);
  const prevPage = React.useRef(null);

  useEffectA(() => {
    const el = scrollerRef.current;
    if (!el) return;

    const isInitial = prevPage.current === null;
    const changed = !isInitial && prevPage.current !== page;
    prevPage.current = page;

    if (isInitial) {
      // First mount. If we're returning from the full case page, restore the
      // saved scroll offset; otherwise leave the page where it loads (top).
      let saved = null;
      try { saved = sessionStorage.getItem("wiloReturnScroll"); } catch (e) {}
      if (saved != null) {
        try { sessionStorage.removeItem("wiloReturnScroll"); } catch (e) {}
        const y = parseInt(saved, 10) || 0;
        // Late-loading images/videos keep growing the page, so keep re-applying
        // until we actually reach the saved offset (or give up after ~5s).
        let attempts = 0;
        const tick = () => {
          el.scrollTo({ top: y, behavior: "auto" });
          attempts++;
          if (attempts < 60 && Math.abs(el.scrollTop - y) > 4) setTimeout(tick, 80);
        };
        requestAnimationFrame(tick);
      }
      return;
    }

    // Real page navigation → start at the top.
    if (changed) el.scrollTo({ top: 0, behavior: "auto" });
  }, [page]);

  return (
    <React.Fragment>
      <div style={{ display: "flex", minHeight: "100vh", height: "100vh", alignItems: "flex-start", minWidth: 1120 }}>
        <Sidebar page={page} setPage={setPage} />
        <main ref={scrollerRef} style={{ flex: 1, minWidth: 0, height: "100vh", overflowY: "auto", position: "relative" }}>
          <div style={{ position: "relative", zIndex: 1, maxWidth: 1480, margin: "0 auto", padding: "0 40px 0" }}>
            {page === "home" && <Home />}
            {page === "projects" && <div style={{ maxWidth: 980, margin: "0 auto" }}><Projects /></div>}
            {page === "about" && <div style={{ maxWidth: 980, margin: "0 auto" }}><About /></div>}
            {page === "services" && <div style={{ maxWidth: 980, margin: "0 auto" }}><Stub title="服务" /></div>}
          </div>
        </main>
      </div>
      <FontTweaks />
    </React.Fragment>);

}

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