// Book shell — left rail nav + page area (responsive: drawer on mobile)
const { useState: useStateA, useEffect: useEffectA } = React;

function App() {
  const [unlocked, setUnlocked] = useStateA(false);
  const [tab, setTab] = useStateA("diary");
  const [sidebarOpen, setSidebarOpen] = useStateA(false);
  const [, forceTick] = useStateA(0);
  const data = window.LifeData;

  useEffectA(() => {
    const h = () => forceTick(x => x + 1);
    window.addEventListener('life-data-updated', h);
    return () => window.removeEventListener('life-data-updated', h);
  }, []);

  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "ambience": "pond",
    "showLotusFooter": true
  }/*EDITMODE-END*/;
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  const tabs = [
    { id: "diary",     num: "I",    zh: "日 記",     en: "Diary" },
    { id: "tasks",     num: "II",   zh: "待 辦",     en: "Pending" },
    { id: "mottos",    num: "III",  zh: "座 右 銘",  en: "Mottos" },
    { id: "portfolio", num: "IV",   zh: "淨 資 產",  en: "Net Worth" },
    { id: "goals",     num: "V",    zh: "目 標",     en: "Goals" },
    { id: "habits",    num: "VI",   zh: "日 課",     en: "Practice" },
    { id: "trades",    num: "VII",  zh: "交 易",     en: "Trade Journal" },
    { id: "health",    num: "VIII", zh: "健 康",     en: "Health" },
    { id: "dates",     num: "IX",   zh: "日 期",     en: "Dates" },
    { id: "notes",     num: "X",    zh: "備 忘",     en: "Notes" },
  ];
  const currentTab = tabs.find(t => t.id === tab);

  const lock = async () => {
    window.LifeCrypto.lock();
    await window.LifeAPI.authLogout();
    setUnlocked(false);
  };

  const switchTab = (id) => {
    setTab(id);
    setSidebarOpen(false); // close drawer on mobile after selection
  };

  if (!unlocked) {
    return (
      <>
        <UnlockScreen onUnlock={() => setUnlocked(true)} ambience={tweaks.ambience} />
        <TweakControls tweaks={tweaks} setTweak={setTweak} />
      </>
    );
  }

  const Page = {
    diary: DiaryPage, tasks: TasksPage, mottos: MottosPage,
    portfolio: PortfolioPage, goals: GoalsPage, habits: HabitsPage,
    trades: TradeJournalPage, health: HealthPage, dates: DatesPage,
    notes: NotesPage,
  }[tab];

  return (
    <>
      <div className="book-shell">
        <div style={{ position: "fixed", inset: 0, opacity: 0.35, pointerEvents: "none", zIndex: 0 }}>
          <Ambience mode={tweaks.ambience} />
        </div>

        {/* Mobile overlay (click to close drawer) */}
        <div className={`book-overlay ${sidebarOpen ? 'open' : ''}`} onClick={() => setSidebarOpen(false)} />

        {/* Sidebar (drawer on mobile, fixed rail on desktop) */}
        <aside className={`book-sidebar paper paper-scroll ${sidebarOpen ? 'open' : ''}`}>
          <button className="book-mobile-close" onClick={() => setSidebarOpen(false)} aria-label="Close">✕</button>
          <div style={{ padding: "32px 24px 20px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <LotusMark size={32} />
              <div>
                <div className="han-display" style={{ fontSize: 16, letterSpacing: "0.25em", fontWeight: 500 }}>一 冊 人 生</div>
                <div className="en-title" style={{ fontSize: 11, color: "var(--ink-3)" }}>The Life Book</div>
              </div>
            </div>
            <div style={{ marginTop: 14, fontSize: 11, color: "var(--ink-3)", fontFamily: "var(--font-en)", fontStyle: "italic" }}>
              Vol. {new Date().getFullYear() - parseInt(data.user.since)} · since {data.user.since}
            </div>
          </div>
          <hr className="rule" style={{ margin: "0 16px" }} />

          <nav style={{ padding: "16px 0" }}>
            <div className="en-caps" style={{ fontSize: 9, color: "var(--ink-3)", padding: "8px 24px" }}>Table of Contents · 目錄</div>
            {tabs.map(t => (
              <div key={t.id} className={`tab ${tab === t.id ? "active" : ""}`} onClick={() => switchTab(t.id)}>
                <span className="num">{t.num}</span>
                <span style={{ flex: 1 }}>{t.zh}</span>
                <span className="en-title" style={{ fontSize: 11, color: "var(--ink-3)" }}>{t.en}</span>
              </div>
            ))}
          </nav>

          <hr className="rule" style={{ margin: "8px 16px" }} />
          <div style={{ padding: "16px 24px", color: "var(--ink-3)", fontSize: 11, lineHeight: 1.8 }}>
            <div className="en-caps" style={{ fontSize: 9, marginBottom: 6 }}>Year · {data.yearTheme.year}</div>
            <div className="han-display" style={{ fontSize: 18, color: "var(--gold-deep)", letterSpacing: "0.15em" }}>{data.yearTheme.word}</div>
            <div className="en-title" style={{ fontSize: 12, marginTop: 2 }}>{data.yearTheme.enWord}</div>
          </div>

          <div style={{ padding: "20px 24px", borderTop: "1px solid var(--rule-2)", marginTop: 12 }}>
            <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center", fontSize: 12 }}
              onClick={lock}>✦ 闔卷</button>
          </div>
        </aside>

        {/* Main content area */}
        <main className="book-main paper paper-deckled">
          {/* Mobile-only top bar (hamburger + chapter + lock) */}
          <div className="book-mobile-bar">
            <button className="menu" onClick={() => setSidebarOpen(true)} aria-label="Menu">☰</button>
            <span className="crumb">{currentTab?.zh || ''}</span>
            <button className="lock" onClick={lock}>闔卷</button>
          </div>

          <Page key={tab} go={switchTab} data={data} />
        </main>

        {/* Desktop-only top right label */}
        <div className="top-corner-label" style={{
          position: "fixed", top: 14, right: 24,
          fontFamily: "var(--font-en)", fontStyle: "italic",
          fontSize: 11, color: "oklch(0.78 0.06 80 / 0.5)",
          letterSpacing: "0.2em", zIndex: 5,
          textTransform: "uppercase"
        }}>
          {data.user.enName}'s Life Book · {new Date().getFullYear()}
        </div>
      </div>
      <TweakControls tweaks={tweaks} setTweak={setTweak} />
    </>
  );
}

function TweakControls({ tweaks, setTweak }) {
  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection title="氛圍 / Ambience">
        <window.TweakRadio
          label="背景"
          value={tweaks.ambience}
          options={[
            { value: "still", label: "靜 Still" },
            { value: "pond", label: "蓮池 Pond" },
            { value: "particles", label: "塵 Dust" }
          ]}
          onChange={v => setTweak("ambience", v)}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

window.App = App;
