(()=>{
// === Main app shell ===
const { ScreenHome, ScreenCapture, ScreenResults, ScreenDetail, ScreenAdvice, ScreenHistory, ScreenProfile } = window.ScreensUser;
const { TechArch, TechSAM2, TechColor, TechFeatures, TechXGB, TechDataFlow } = window.ScreensTech;

const NAV = [
  { group: "患者端 · Patient",  items: [
    { k:"home",     t:"健康总览",   icon:"home" },
    { k:"capture",  t:"新建检测",   icon:"camera" },
    { k:"results",  t:"检测结果",   icon:"gauge" },
    { k:"detail",   t:"单病种详情", icon:"droplet" },
    { k:"advice",   t:"健康建议",   icon:"lightbulb" },
    { k:"history",  t:"历史趋势",   icon:"history" },
    { k:"profile",  t:"个人档案",   icon:"user" },
  ]},
  { group: "技术管线 · Judge View",   items: [
    { k:"tech-arch",   t:"系统架构",       icon:"layers" },
    { k:"tech-sam2",   t:"SAM2 分割",     icon:"target" },
    { k:"tech-color",  t:"色彩标准化",     icon:"sun" },
    { k:"tech-feat",   t:"特征工程",       icon:"filter" },
    { k:"tech-xgb",    t:"XGBoost + SHAP",icon:"cpu" },
    { k:"tech-flow",   t:"数据流追踪",     icon:"atom" },
  ]},
];

const ALL_NAV_ITEMS = NAV.flatMap(group => group.items);
const VALID_PAGES = new Set(ALL_NAV_ITEMS.map(item => item.k));
const VALID_DETAIL_TARGETS = new Set(["diabetes", "cardiovascular", "kidney", "anemia"]);

const parseHashRoute = () => {
  const raw = window.location.hash.replace(/^#\/?/, "");
  const [candidatePage, candidateDetail] = raw.split("/");
  return {
    page: VALID_PAGES.has(candidatePage) ? candidatePage : "home",
    detail: VALID_DETAIL_TARGETS.has(candidateDetail) ? candidateDetail : "diabetes",
  };
};

const App = () => {
  const initialRoute = parseHashRoute();
  const [page, setPage] = React.useState(initialRoute.page);
  const [detailTarget, setDetailTarget] = React.useState(initialRoute.detail);
  const [navOpen, setNavOpen] = React.useState(false);
  const [elderly, setElderly] = React.useState(() => window.localStorage.getItem("chronicsense:elderly") === "true");

  React.useEffect(()=>{
    document.body.classList.toggle("elderly", elderly);
    window.localStorage.setItem("chronicsense:elderly", elderly ? "true" : "false");
  }, [elderly]);

  React.useEffect(()=>{
    const onHashChange = () => {
      const next = parseHashRoute();
      setPage(next.page);
      setDetailTarget(next.detail);
      setNavOpen(false);
      window.scrollTo({ top:0, behavior:"smooth" });
    };
    window.addEventListener("hashchange", onHashChange);
    return () => window.removeEventListener("hashchange", onHashChange);
  }, []);

  const nav = (k, extra) => {
    const nextDetail = k === "detail" ? (extra || detailTarget) : undefined;
    if (nextDetail) setDetailTarget(nextDetail);
    setPage(k);
    setNavOpen(false);
    const nextHash = nextDetail ? `#${k}/${nextDetail}` : `#${k}`;
    if (window.location.hash !== nextHash) window.location.hash = nextHash;
    window.scrollTo({ top:0, behavior:"smooth" });
  };

  const screen = (() => {
    switch(page) {
      case "home":     return <ScreenHome nav={nav}/>;
      case "capture":  return <ScreenCapture nav={nav}/>;
      case "results":  return <ScreenResults nav={nav}/>;
      case "detail":   return <ScreenDetail nav={nav} target={detailTarget}/>;
      case "advice":   return <ScreenAdvice nav={nav}/>;
      case "history":  return <ScreenHistory nav={nav}/>;
      case "profile":  return <ScreenProfile nav={nav}/>;
      case "tech-arch":  return <TechArch/>;
      case "tech-sam2":  return <TechSAM2/>;
      case "tech-color": return <TechColor/>;
      case "tech-feat":  return <TechFeatures/>;
      case "tech-xgb":   return <TechXGB/>;
      case "tech-flow":  return <TechDataFlow/>;
      default: return <ScreenHome nav={nav}/>;
    }
  })();

  const isPatient = !page.startsWith("tech");
  const currentTitle = ALL_NAV_ITEMS.find(i=>i.k===page)?.t || "";

  return (
    <div className="app-shell min-h-screen flex bg-paper">
      {/* Sidebar */}
      <aside className={`app-sidebar ${navOpen ? "is-open" : "is-collapsed"} w-[252px] flex-shrink-0 bg-white border-r border-ink-100 sticky top-0 h-screen overflow-y-auto nosel`}>
        <div className="px-5 py-5 border-b border-ink-100">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <div className="w-9 h-9 rounded-lg bg-clinic-700 text-white flex items-center justify-center"><Icon name="logo" size={22}/></div>
              <div>
                <div className="text-sm font-semibold serif-zh leading-tight">慢病先知</div>
                <div className="text-[10px] text-ink-400 num tracking-wider">CHRONICSENSE · v1.0.0</div>
              </div>
            </div>
            <button
              className="mobile-nav-toggle"
              onClick={()=>setNavOpen(open=>!open)}
              aria-label={navOpen ? "收起导航" : "展开导航"}
              title={navOpen ? "收起导航" : "展开导航"}
            >
              <Icon name={navOpen ? "x" : "menu"} size={18}/>
            </button>
          </div>
        </div>

        <nav className="app-nav px-3 py-4 space-y-5">
          {NAV.map((grp,gi)=>(
            <div key={gi}>
              <div className="text-[10px] tracking-[0.16em] uppercase text-ink-400 num px-2 mb-2">{grp.group}</div>
              <ul className="space-y-0.5">
                {grp.items.map(it=>{
                  const active = page === it.k;
                  return (
                    <li key={it.k}>
                      <button onClick={()=>nav(it.k)}
                        aria-current={active ? "page" : undefined}
                        className={`w-full flex items-center gap-2.5 px-2.5 h-9 rounded-md text-sm border transition-colors
                          ${active ? "nav-item-active text-clinic-700 font-medium" : "border-transparent text-ink-700 hover:bg-ink-50"}`}>
                        <Icon name={it.icon} size={15} className={active?"text-clinic-600":"text-ink-500"}/>
                        <span className="flex-1 text-left">{it.t}</span>
                        {active && <Icon name="chevron-right" size={14} className="text-clinic-500"/>}
                      </button>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </nav>

        <div className="demo-note px-4 py-4 border-t border-ink-100 mt-auto">
          <div className="bg-clinic-50 border border-clinic-200 rounded-md p-3 text-[11px] text-clinic-700 leading-relaxed">
            <div className="flex items-center gap-1 font-semibold mb-1"><Icon name="shield" size={12}/> 演示模式</div>
            演示数据均为虚构。患者 王伯伯 · 68 · 男为模型示例案例。
          </div>
        </div>
      </aside>

      {/* Main */}
      <main className="app-main flex-1 min-w-0 flex flex-col">
        {/* Top bar */}
        <header className="app-topbar sticky top-0 z-10 bg-white/85 backdrop-blur border-b border-ink-100 px-7 h-14 flex items-center justify-between">
          <div className="flex items-center gap-3 text-sm">
            <span className="text-ink-400">{isPatient ? "患者端" : "技术管线"}</span>
            <Icon name="chevron-right" size={14} className="text-ink-300"/>
            <span className="font-medium text-ink-900">{currentTitle}</span>
          </div>

          <div className="flex items-center gap-3">
            <div className="app-status flex items-center gap-2 text-xs text-ink-500">
              <span className="w-1.5 h-1.5 rounded-full bg-mint-500 pulse-dot"/>
              <span>模型已加载 · sam2_oral_v3 / xgb_4tasks_v2.1</span>
            </div>
            <div className="app-divider h-5 w-px bg-ink-200"/>
            <button onClick={()=>setElderly(e=>!e)}
              aria-pressed={elderly}
              className={`inline-flex items-center gap-2 px-3 h-8 rounded-md border text-xs font-medium transition-colors
              ${elderly ? "bg-mint-600 border-mint-700 text-white" : "bg-white border-ink-200 text-ink-700 hover:border-ink-300"}`}>
              <span className={`w-7 h-3.5 rounded-full relative ${elderly?"bg-white/30":"bg-ink-200"}`}>
                <span className={`absolute top-0.5 w-2.5 h-2.5 rounded-full bg-white transition-all ${elderly?"left-4":"left-0.5"}`}/>
              </span>
              老年模式
            </button>
            <div className="user-mini flex items-center gap-2 pl-2 border-l border-ink-200">
              <div className="w-7 h-7 rounded-full bg-clinic-100 border border-clinic-200 flex items-center justify-center text-clinic-700 text-xs font-semibold">王</div>
              <div className="text-xs">
                <div className="font-medium leading-none">王建国</div>
                <div className="text-[10px] text-ink-400 mt-0.5">CS-2025-00142</div>
              </div>
            </div>
          </div>
        </header>

        <div className="app-content flex-1 px-7 py-7 max-w-[1320px] w-full">
          {screen}
        </div>

        <footer className="app-footer px-7 py-6 border-t border-ink-100 text-[11px] text-ink-400 flex justify-between">
          <span>© 2026 ChronicSense · 慢病先知 演示系统。本系统输出不构成医疗诊断，最终诊断请以医生意见为准。</span>
          <span className="num">build 260511.1 · sam2 / xgb / shap</span>
        </footer>
      </main>
    </div>
  );
};

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

})();
