/* ============================================================
   Lineage — app shell + routing + manual-attribution store
   ============================================================ */

/* ====================  APP  ==================== */
function App() {
  // route: which section, and whether a commit/session is open
  const [route, setRoute] = useState({ section: "history", hash: null, sid: null });
  // global repo filter: "all" or a repo name
  const [repo, setRepo] = useState("all");
  // manual attributions layered on top of intrinsic sessionId: { [hash]: sid }
  const [links, setLinks] = useState({});

  const linkActions = {
    link: (hash, sid) => setLinks(m => ({ ...m, [hash]: sid })),
    unlink: (hash) => setLinks(m => { const n = { ...m }; delete n[hash]; return n; }),
  };

  const go = {
    section: (s) => setRoute({ section: s, hash: null, sid: null }),
    commit: (hash) => setRoute({ section: "history", hash, sid: null }),
    session: (sid) => setRoute({ section: "agents", sid, hash: null }),
    backHistory: () => setRoute(r => ({ ...r, hash: null })),
    backAgents: () => setRoute(r => ({ ...r, sid: null })),
  };

  return (
    <div className="app">
      <TopBar section={route.section} setSection={go.section} repo={repo} setRepo={setRepo} />

      {route.section === "history" && (
        route.hash
          ? <CommitDetail hash={route.hash} links={links} linkActions={linkActions} go={go} onBack={go.backHistory} />
          : <HistoryView links={links} onOpen={go.commit} go={go} repo={repo} setRepo={setRepo} />
      )}

      {route.section === "agents" && (
        route.sid
          ? <SessionDetail sid={route.sid} links={links} linkActions={linkActions} go={go} onBack={go.backAgents} />
          : <AgentsView links={links} onOpen={go.session} repo={repo} setRepo={setRepo} />
      )}

      {route.section === "code" && <RepoView onSelectRun={(sid) => go.session(sid)} repo={repo === "all" ? "atlas" : repo} setRepo={setRepo} />}
    </div>
  );
}

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