/* global React, ReactDOM */
const { useState: useStateApp, useEffect: useEffectApp, useRef: useRefApp } = React;

const CHAPTERS = [
  { id: "ch-01", num: "01", title: "Orientation", section: "Foundations" },
  { id: "ch-02", num: "02", title: "What is an agent?", section: "Foundations" },
  { id: "ch-03", num: "03", title: "Messages, prompts, models", section: "Foundations" },
  { id: "ch-04", num: "04", title: "LCEL & the pipe operator", section: "Composition" },
  { id: "ch-05", num: "05", title: "Tools & tool calling", section: "Composition" },
  { id: "ch-06", num: "06", title: "Agent types — ReAct, tools, structured", section: "Agents" },
  { id: "ch-07", num: "07", title: "AgentExecutor internals", section: "Agents" },
  { id: "ch-08", num: "08", title: "MCP — Model Context Protocol", section: "Integration" },
  { id: "ch-09", num: "09", title: "Streaming, callbacks, LangSmith", section: "Production" },
  { id: "ch-10", num: "10", title: "Production checklist", section: "Production" },
];

function App() {
  const [active, setActive] = useStateApp("ch-01");
  const [progress, setProgress] = useStateApp(0);
  const mainRef = useRefApp(null);

  // Scrollspy: pick the chapter whose top is closest to viewport top
  useEffectApp(() => {
    const onScroll = () => {
      const sections = CHAPTERS.map(c => document.getElementById(c.id)).filter(Boolean);
      const scrollY = window.scrollY + 120;
      let current = sections[0]?.id;
      for (const s of sections) {
        if (s.offsetTop <= scrollY) current = s.id;
      }
      if (current) setActive(current);

      const scrollMax = document.documentElement.scrollHeight - window.innerHeight;
      const pct = scrollMax > 0 ? (window.scrollY / scrollMax) * 100 : 0;
      setProgress(pct);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Keyboard nav j / k
  useEffectApp(() => {
    const onKey = (e) => {
      if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
      const idx = CHAPTERS.findIndex(c => c.id === active);
      if (e.key === "j" || e.key === "ArrowDown" && e.metaKey) {
        const next = CHAPTERS[Math.min(CHAPTERS.length - 1, idx + 1)];
        document.getElementById(next.id)?.scrollIntoView({ behavior: "smooth", block: "start" });
      } else if (e.key === "k" || e.key === "ArrowUp" && e.metaKey) {
        const prev = CHAPTERS[Math.max(0, idx - 1)];
        document.getElementById(prev.id)?.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [active]);

  const goTo = (id) => {
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  // Group chapters by section
  const groups = [];
  let lastSection = null;
  for (const c of CHAPTERS) {
    if (c.section !== lastSection) { groups.push({ section: c.section, chapters: [] }); lastSection = c.section; }
    groups[groups.length - 1].chapters.push(c);
  }

  return (
    <div className="app">
      <aside className="sidebar">
        <div className="sidebar-header">
          <div className="brand-mark">
            <div className="brand-logo">λ</div>
            <div className="brand-name">LangChain <span className="muted">/ Deep Dive</span></div>
          </div>
          <h1 className="sidebar-title">Agents, Tools &amp; MCP</h1>
          <div className="sidebar-meta">
            <span>10 chapters</span>
            <span className="dot"></span>
            <span>~2 hr read</span>
          </div>
          <div className="sidebar-progress"><div className="sidebar-progress-fill" style={{ width: `${progress}%` }} /></div>
        </div>

        <nav className="sidebar-nav">
          {groups.map(g => (
            <div key={g.section}>
              <div className="nav-section-label">{g.section}</div>
              {g.chapters.map(c => (
                <div
                  key={c.id}
                  className={`nav-item ${active === c.id ? "active" : ""}`}
                  onClick={() => goTo(c.id)}
                >
                  <span className="nav-num">{c.num}</span>
                  <span>{c.title}</span>
                </div>
              ))}
            </div>
          ))}
        </nav>

        <div className="sidebar-footer">
          <span>Navigate</span>
          <span><span className="kbd">j</span> <span className="kbd">k</span></span>
        </div>
      </aside>

      <main className="main" ref={mainRef}>
        <Chapter01 />
        <Chapter02 />
        <Chapter03 />
        <Chapter04 />
        <Chapter05 />
        <Chapter06 />
        <Chapter07 />
        <Chapter08 />
        <Chapter09 />
        <Chapter10 />

        <div style={{ maxWidth: 880, margin: "0 auto", padding: "0 64px 80px", color: "var(--ink-3)", fontSize: 13, fontFamily: "var(--mono)", textAlign: "center" }}>
          End of course · λ
        </div>
      </main>
    </div>
  );
}

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