// Helm — App orchestrator. 手機=底部分頁全螢幕;桌面=左側邊欄+內容置中加寬。
(function () {
  const NS = window.HelmDesignSystem_9613a7;
  const { TabBar, IconButton, SyncBadge, HelmMark, Toast, ToastViewport, Button } = NS;

  const TABS = [
    { key: "overview", label: "總覽", icon: "ph-compass" },
    { key: "detail", label: "明細", icon: "ph-list-bullets" },
    { key: "cashflow", label: "現金流", icon: "ph-arrows-left-right", soon: true },
    { key: "goals", label: "目標", icon: "ph-target", soon: true },
    { key: "settings", label: "設定", icon: "ph-gear-six", soon: true },
  ];

  function systemTheme() {
    return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
  }

  function App() {
    const [unlocked, setUnlocked] = React.useState(false);
    const [tab, setTab] = React.useState("overview");
    const [sheet, setSheet] = React.useState(null);
    const [toast, setToast] = React.useState(null);
    const [sync, setSync] = React.useState("synced");
    const [theme, setTheme] = React.useState(systemTheme());
    const [rev, setRev] = React.useState(0);
    const [isDesktop, setIsDesktop] = React.useState(window.matchMedia("(min-width: 760px)").matches);

    React.useEffect(() => { document.documentElement.setAttribute("data-theme", theme); }, [theme]);
    React.useEffect(() => {
      const mq = window.matchMedia("(prefers-color-scheme: dark)");
      const fn = () => setTheme(mq.matches ? "dark" : "light");
      mq.addEventListener("change", fn); return () => mq.removeEventListener("change", fn);
    }, []);
    React.useEffect(() => {
      const mq = window.matchMedia("(min-width: 760px)");
      const fn = () => setIsDesktop(mq.matches);
      mq.addEventListener("change", fn); return () => mq.removeEventListener("change", fn);
    }, []);
    React.useEffect(() => {
      if (window.HelmData.getPw()) {
        window.HelmData.refresh().then((ok) => { if (ok) { setUnlocked(true); setRev((r) => r + 1); } });
      }
    }, []);


    function showToast(msg, tone = "success") {
      setToast({ msg, tone });
      clearTimeout(showToast._t);
      showToast._t = setTimeout(() => setToast(null), 2600);
    }
    function openNew() { setSheet({ item: null }); }
    function openEdit(item) { setSheet({ item }); }
    function closeSheet() { setSheet(null); }
    function afterWrite(msg) { setSheet(null); showToast(msg); setSync("syncing"); setRev((r) => r + 1); setTimeout(() => setSync("synced"), 700); }
    function manualRefresh() { setSync("syncing"); window.HelmData.refresh().then(() => { setRev((r) => r + 1); setSync("synced"); }); }

    function screen() {
      return tab === "overview"
        ? React.createElement(window.Overview, { key: "ov" + rev })
        : React.createElement(window.Detail, { key: "dt" + rev, onEdit: openEdit });
    }

    return (
      <div className="helm-root">
        {!unlocked && <window.Lock onUnlock={() => { setUnlocked(true); setRev((r) => r + 1); }} />}

        {/* ---- 手機 ---- */}
        {unlocked && !isDesktop && (
          <div className="mobile-shell">
            <header className="app-header">
              <SyncBadge state={sync} time="剛剛" onRetry={manualRefresh} />
              <div className="app-header__brand"><HelmMark size={20} /><span className="app-header__word">Helm</span></div>
            </header>
            <div className="app-scroll">{screen()}</div>
            <div className="app-fab"><IconButton icon="ph-plus" variant="fab" label="新增項目" onClick={openNew} /></div>
            <div className="app-tabbar"><TabBar items={TABS} active={tab} onChange={setTab} /></div>
          </div>
        )}

        {/* ---- 桌面:側邊欄 + 主內容 ---- */}
        {unlocked && isDesktop && (
          <div className="desktop-shell">
            <nav className="helm-sidebar">
              <div className="helm-sidebar__brand">
                <span className="helm-sidebar__brand-mark"><HelmMark size={26} /></span>
                <span className="helm-sidebar__brand-name">Helm</span>
              </div>
              <div className="helm-sidebar__add">
                <Button variant="primary" block iconLeft="ph-plus" onClick={openNew}>新增項目</Button>
              </div>
              {TABS.map((t) => (
                <button key={t.key} type="button"
                  className={"helm-navitem" + (t.soon ? " helm-navitem--soon" : "")}
                  aria-current={tab === t.key ? "page" : undefined}
                  onClick={() => !t.soon && setTab(t.key)}>
                  <i className={"ph " + t.icon} aria-hidden="true" />{t.label}
                  {t.soon && <span className="helm-navitem__soon">即將推出</span>}
                </button>
              ))}
              <div className="helm-sidebar__foot"><SyncBadge state={sync} time="剛剛" onRetry={manualRefresh} /></div>
            </nav>
            <main className="app-main"><div className="app-main__inner">{screen()}</div></main>
          </div>
        )}

        {sheet && (
          <window.AddEditSheet item={sheet.item} onClose={closeSheet} onSaved={afterWrite} onDeleted={afterWrite} />
        )}
        {toast && (<ToastViewport><Toast tone={toast.tone}>{toast.msg}</Toast></ToastViewport>)}
      </div>
    );
  }

  window.HelmApp = App;
})();
