// app.jsx — root: snap-scroll, dot nav, top nav, lang toggle, FAB
const { SiteCtx, useCurrentPage, I18N } = window.MM_HOOKS;
const { useState, useEffect, useRef, useMemo } = React;

const PAGE_IDS = ["home", "cases", "projects", "resume", "chat"];

function ProjectDetailModal({ id, onClose }) {
  const { lang } = React.useContext(SiteCtx);
  const t = I18N[lang];
  const p = window.SITE_DATA.PROJECTS.find(x => x.id === id);
  const post = window.SITE_POSTS && window.SITE_POSTS[id];
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);
  if (!p) return null;
  const preview = lang === "zh" ? p.preview_zh : p.preview_en;
  // Long-form essays in posts.js are intentionally NOT shown here.
  // The cases section shows what was done, not narrative writeups.
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(31,30,29,0.55)", backdropFilter: "blur(4px)", zIndex: 100, padding: 24, display: "flex", alignItems: "flex-start", justifyContent: "center", overflowY: "auto", animation: "fade-in 200ms" }}>
      <article onClick={(e) => e.stopPropagation()} style={{ background: "#fff", borderRadius: 18, padding: "36px 44px", maxWidth: 760, width: "100%", marginTop: 60, marginBottom: 60, position: "relative", animation: "rise 320ms cubic-bezier(0.16, 1, 0.3, 1)" }}>
        <button onClick={onClose} style={{ position: "absolute", top: 14, right: 14, width: 36, height: 36, borderRadius: "50%", fontSize: 22, color: "#73726c", background: "transparent" }}>×</button>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 8 }}>{p.category}</div>
        <h1 style={{ fontFamily: "var(--font-serif)", fontSize: 36, lineHeight: 1.1, letterSpacing: "-0.02em", margin: "0 0 14px", textWrap: "pretty" }}>{lang === "zh" ? p.title_zh : p.title_en}</h1>
        <p style={{ color: "var(--ink-2)", fontSize: 17, lineHeight: 1.55, margin: "0 0 24px" }}>{lang === "zh" ? p.oneLiner_zh : p.oneLiner_en}</p>
        <div style={{ background: "var(--accent-soft)", padding: "20px 24px", borderRadius: 14, marginBottom: 28 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--accent-ink)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 12 }}>{lang === "zh" ? "做了什么 · " + (p.period || "") : "What I did · " + (p.period || "")}</div>
          {preview.map((para, i) => <p key={i} style={{ margin: "0 0 10px", fontSize: 15, lineHeight: 1.6, textWrap: "pretty" }}>{para}</p>)}
        </div>
        <div style={{ marginTop: 28, paddingTop: 18, borderTop: "1px solid var(--line)", textAlign: "right" }}>
          <button onClick={onClose} className="btn">← {t.nav_cases}</button>
        </div>
      </article>
    </div>
  );
}

function App() {
  const [lang, setLangState] = useState(() => {
    try { return localStorage.getItem("mm-lang") || "en"; } catch (e) { return "en"; }
  });
  const setLang = (l) => { setLangState(l); try { localStorage.setItem("mm-lang", l); } catch (e) {} };
  const [openProject, setOpenProject] = useState(null);
  const [scrolled, setScrolled] = useState(false);

  const rootRef = useRef(null);
  const pageIds = useMemo(() => PAGE_IDS, []);
  const currentPage = useCurrentPage(rootRef, pageIds);

  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const onScroll = () => setScrolled(root.scrollTop > 40);
    onScroll();
    root.addEventListener("scroll", onScroll, { passive: true });
    return () => root.removeEventListener("scroll", onScroll);
  }, []);

  const motion = !window.matchMedia || !window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  const jumpTo = (id) => {
    const el = document.getElementById(id);
    if (!el || !rootRef.current) return;
    rootRef.current.scrollTo({ top: el.offsetTop, behavior: "smooth" });
  };

  const t = I18N[lang];
  const navItems = [
    { id: "home", label: t.nav_home },
    { id: "cases", label: t.nav_cases },
    { id: "projects", label: t.nav_projects },
    { id: "resume", label: t.nav_resume },
    { id: "chat", label: t.nav_chat },
  ];

  return (
    <SiteCtx.Provider value={{ lang, setLang }}>
      <nav className={`topnav ${scrolled ? "topnav--scrolled" : ""}`}>
        <button className="topnav-brand" onClick={() => jumpTo("home")}>
          <span className="brand-pixel"></span>
          <span className="brand-name-en">Ming Mu</span>
          <span className="brand-name-zh">慕铭</span>
        </button>
        <div className="topnav-links">
          {navItems.map(n => (
            <button
              key={n.id}
              className={`topnav-link ${currentPage === n.id ? "topnav-link--active" : ""}`}
              onClick={() => jumpTo(n.id)}
            >{n.label}</button>
          ))}
          <button className="topnav-lang" onClick={() => setLang(lang === "en" ? "zh" : "en")}>{t.lang}</button>
        </div>
      </nav>

      <div className="dotnav">
        {navItems.map(n => (
          <div key={n.id}
            className={`dotnav-item ${currentPage === n.id ? "dotnav-item--active" : ""}`}
            onClick={() => jumpTo(n.id)}>
            <span className="dotnav-label">{n.label}</span>
            <span className="dotnav-dot"></span>
          </div>
        ))}
      </div>

      <button className="chat-fab" onClick={() => jumpTo("chat")}>
        <span className="pixel-dot"></span>
        {t.fab}
      </button>

      <main className="snap-root" ref={rootRef}>
        <window.HomePage motion={motion} onJump={jumpTo} />
        <window.CasesPage onOpen={(id) => setOpenProject(id)} />
        <window.ProjectsPage />
        <window.ResumePage />
        <window.ChatPage />
      </main>

      {openProject && <ProjectDetailModal id={openProject} onClose={() => setOpenProject(null)} />}
    </SiteCtx.Provider>
  );
}

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