/* SEAL — App shell: TopNav + Rail + routing + chatbot + live state */
const { useState, useEffect, useCallback, useMemo } = React;

const NAV = [
  { group: "공고", items: [{ k: "grants", n: "↗", label: "공고 발굴", icon: "doc", href: "SEAL-Grants.html" }] },
  { group: "현황", items: [{ k: "home", n: "④", label: "예실대비", icon: "home" }] },
  { group: "집행", items: [
    { k: "inbox", n: "⑤", label: "대화 인박스", icon: "inbox", badgeKey: "inbox" },
    { k: "propose", n: "⑥", label: "AI 제안", icon: "sparkles" },
    { k: "execute", n: "⑦", label: "집행 실행", icon: "bolt" },
    { k: "docs", n: "⑧", label: "서류 · 검토", icon: "file" },
  ] },
  { group: "근거", items: [
    { k: "proposal", n: "①", label: "사업계획서", icon: "doc" },
    { k: "budget", n: "②", label: "예산안", icon: "wallet" },
    { k: "rules", n: "③", label: "사업지침", icon: "book" },
  ] },
  { group: "보조", items: [
    { k: "history", n: "⑨", label: "집행 이력", icon: "history" },
    { k: "evidence", n: "⑩", label: "증빙 현황", icon: "shield" },
  ] },
  { group: "설정", items: [{ k: "settings", n: "⑪", label: "연동 설정", icon: "gear" }] },
];

function computeLive(store) {
  const base = window.SEAL_DATA.status;
  const exec = store.executed || {};
  let add = 0;
  const items = base.items.map((it) => {
    const ex = Object.values(exec).find((e) => e.categoryName === it.name);
    if (ex) { add += ex.totalKRW; return { ...it, spent: it.spent + ex.totalKRW, remain: it.remain - ex.totalKRW, active: true }; }
    return it;
  });
  const executions = [
    ...Object.values(exec).map((e) => ({ ...e, date: e.at })),
    ...window.SEAL_DATA.history,
  ];
  return { total: base.total, spent: base.spent + add, remain: base.remain - add, items, executions };
}

function App() {
  const [route, setRoute] = useState(() => (location.hash || "#home").slice(1).split("?")[0] || "home");
  const [store, setStore] = useState({ approved: {}, executed: {}, activeNeeds: null, inboxLoaded: false });
  const [chatOpen, setChatOpen] = useState(false);

  const nav = useCallback((k) => {
    setRoute(k);
    location.hash = "#" + k;
    window.scrollTo({ top: 0 });
  }, []);

  useEffect(() => {
    const h = () => setRoute((location.hash || "#home").slice(1).split("?")[0] || "home");
    window.addEventListener("hashchange", h);
    return () => window.removeEventListener("hashchange", h);
  }, []);

  const live = useMemo(() => computeLive(store), [store]);
  const { HomePage, InboxPage, ProposePage } = window.CorePages;
  const { ExecutePage, DocsPage } = window.FlowPages;
  const { PlanProposalPage, PlanBudgetPage, PlanRulesPage, HistoryPage, EvidencePage, SettingsPage } = window.RefPages;

  // pending-needs pip for inbox
  const inboxPip = store.inboxLoaded ? 0 : window.SEAL_DATA.conversations.reduce((a, c) => a + c.needs.length, 0);

  let Page;
  switch (route) {
    case "home": Page = <HomePage nav={nav} live={live} />; break;
    case "inbox": Page = <InboxPage nav={nav} store={store} setStore={setStore} />; break;
    case "propose": Page = <ProposePage nav={nav} store={store} setStore={setStore} />; break;
    case "execute": Page = <ExecutePage nav={nav} store={store} setStore={setStore} />; break;
    case "docs": Page = <DocsPage nav={nav} store={store} />; break;
    case "proposal": Page = <PlanProposalPage />; break;
    case "budget": Page = <PlanBudgetPage live={live} />; break;
    case "rules": Page = <PlanRulesPage />; break;
    case "history": Page = <HistoryPage live={live} />; break;
    case "evidence": Page = <EvidencePage />; break;
    case "settings": Page = <SettingsPage />; break;
    default: Page = <HomePage nav={nav} live={live} />;
  }

  return (
    <div className="app">
      {/* Top nav */}
      <header className="topnav">
        <div className="brand" onClick={() => nav("home")}>
          <span className="brand-name" style={{ fontWeight: 800, letterSpacing: "-0.04em", transform: "skewX(-8deg)", display: "inline-block", fontSize: 20, lineHeight: 1, background: "linear-gradient(100deg,#0066FF 8%,#4F95FF 50%,#0066FF 92%)", WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent", WebkitTextFillColor: "transparent" }}>SEAL</span>
        </div>
        <div className="proj-select" title={window.SEAL_DATA.project.title}>
          <Icons.folder size={16} />
          <span className="ptitle">{window.SEAL_DATA.project.title}</span>
          <span className="pmeta">{window.SEAL_DATA.project.code}</span>
          <Icons.chevDown size={15} />
        </div>
        <div className="nav-spacer" />
        <span className="badge badge-blue" style={{ height: 26 }}>혁신법 연구비</span>
        <span className="badge badge-gray" style={{ height: 26 }}>Law as Code</span>
        <button className={`nav-chat-toggle ${chatOpen ? "on" : ""}`} onClick={() => setChatOpen(!chatOpen)}>
          <Icons.chat size={17} />미소
        </button>
      </header>

      <div className="shell">
        {/* Left rail */}
        <nav className="rail">
          {NAV.map((g) => (
            <div className="rail-group" key={g.group}>
              <div className="rail-group-label">{g.group}</div>
              {g.items.map((it) => {
                const ActI = Icons[it.icon];
                const isActive = route === it.k;
                return (
                  <div key={it.k} className={`rail-item ${isActive ? "active" : ""}`} onClick={() => (it.href ? (window.location.href = it.href) : nav(it.k))}>
                    <span className="ico"><ActI size={18} /></span>
                    <span>{it.label}</span>
                    {it.k === "inbox" && inboxPip > 0
                      ? <span className="pip tnum">{inboxPip}</span>
                      : <span className="num">{it.n}</span>}
                  </div>
                );
              })}
            </div>
          ))}
        </nav>

        {/* Main */}
        <main className="main" key={route}>{Page}</main>
      </div>

      {chatOpen && <Chatbot onClose={() => setChatOpen(false)} nav={nav} />}
      <ToastHost />
    </div>
  );
}

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