// Helm — App orchestrator (真資料版). header, tabs, FAB, sheet, toast, 跟隨系統深淺色, 自動登入.
(function () {
  const NS = window.HelmDesignSystem_9613a7;
  const { TabBar, IconButton, SyncBadge, HelmMark, Toast, ToastViewport } = 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); // 資料版本:+1 就重繪畫面

    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(() => {
      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); }
    // 新增/編輯/刪除完成(此時 HelmData 已把 window.HELM 重新拉好)
    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"); });
    }

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

          {unlocked && (
            <React.Fragment>
              <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">
                {tab === "overview" && <window.Overview key={"ov" + rev} />}
                {tab === "detail" && <window.Detail key={"dt" + rev} onEdit={openEdit} />}
              </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>

              {sheet && (
                <window.AddEditSheet item={sheet.item} onClose={closeSheet}
                  onSaved={afterWrite} onDeleted={afterWrite} />
              )}

              {toast && (
                <ToastViewport><Toast tone={toast.tone}>{toast.msg}</Toast></ToastViewport>
              )}
            </React.Fragment>
          )}
        </div>
      </div>
    );
  }

  window.HelmApp = App;
})();
