/* Main shell */

window.App = function() {
  const data = window.PLAN_DATA;
  const [progress, updateProgress, resetAll, syncStatus, syncNow] = window.useProgress();
  const [tab, setTab] = React.useState("home");
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [collapsed, setCollapsed] = React.useState(() => {
    try { return localStorage.getItem("rrr-drawer-collapsed") === "1"; } catch (e) { return false; }
  });

  React.useEffect(() => {
    try { localStorage.setItem("rrr-drawer-collapsed", collapsed ? "1" : "0"); } catch (e) {}
  }, [collapsed]);

  const currentWeek = window.findCurrentWeek(data.weeks, data.days);
  const today = window.todayISO();
  const todayDay = data.days.find(d => d.iso === today);
  const daysToRace = window.daysBetween(today, window.RACE_ISO);

  // Stats for nav badges
  const totalDone = Object.values(progress).filter(p => p.done).length;
  const totalDays = data.days.length;

  const tabs = [
    { id: "home",    label: "儀表板",   icon: "◐" },
    { id: "plan",    label: "訓練計畫", icon: "▦", badge: `${totalDone}/${totalDays}` },
    { id: "explain", label: "名詞解釋", icon: "✦" },
    { id: "zones",   label: "配速心率", icon: "≡" },
    { id: "race",    label: "比賽日",   icon: "◆" },
    { id: "settings",label: "設定",     icon: "✱" }
  ];

  const goto = (t) => { setTab(t); setDrawerOpen(false); window.scrollTo(0, 0); };

  let topbarTitle = "儀表板", topbarSub = "";
  switch (tab) {
    case "home":     topbarTitle = "儀表板"; topbarSub = `本週 W${currentWeek}`; break;
    case "plan":     topbarTitle = "訓練計畫"; topbarSub = "21 週 sub-2:00"; break;
    case "explain":  topbarTitle = "名詞解釋"; topbarSub = "六種訓練類型"; break;
    case "zones":    topbarTitle = "配速心率"; topbarSub = "Z1–Z6"; break;
    case "race":     topbarTitle = "比賽日策略"; topbarSub = "9/20 (日)"; break;
    case "settings": topbarTitle = "設定"; topbarSub = "資料管理"; break;
  }

  return (
    <div className="app">
      <div className={"scrim" + (drawerOpen ? " open" : "")} onClick={() => setDrawerOpen(false)}></div>

      <aside className={"drawer" + (drawerOpen ? " open" : "") + (collapsed ? " collapsed" : "")}>
        <div className="drawer-brand">
          <button
            className="brand-mark brand-mark-btn"
            onClick={() => setCollapsed(c => !c)}
            aria-label={collapsed ? "展開選單" : "收合選單"}
            title={collapsed ? "展開選單" : "收合選單"}
          >
            RUN
          </button>
          <div className="brand-text">
            <div className="brand-title">RUN RUN RUN</div>
            <div className="brand-sub">SUB-2:00 · 9/20</div>
          </div>
        </div>

        <div className="drawer-section">主選單</div>
        {tabs.map(t => (
          <button key={t.id} className={"nav-item" + (tab === t.id ? " active" : "")}
                  onClick={() => goto(t.id)}
                  title={collapsed ? t.label : undefined}>
            <span className="nav-icon">{t.icon}</span>
            <span>{t.label}</span>
            {t.badge && <span className="nav-badge">{t.badge}</span>}
          </button>
        ))}

        <div className="drawer-footer">
          {collapsed ? (
            <div className="drawer-footer-mark" title={`距離比賽 ${Math.max(0, daysToRace)} 天`}></div>
          ) : (
            <div className="drawer-footer-text">
              <div className="race-line">距離比賽 {Math.max(0, daysToRace)} 天</div>
              2026 · 9/20 (日)<br/>
              21.1 km @ 5:40/km
            </div>
          )}
        </div>
      </aside>

      <main className={"main" + (collapsed ? " drawer-collapsed" : "")}>
        <div className="topbar">
          <button className="topbar-burger" onClick={() => setDrawerOpen(true)} aria-label="選單">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <line x1="3" y1="6" x2="21" y2="6"/>
              <line x1="3" y1="12" x2="21" y2="12"/>
              <line x1="3" y1="18" x2="21" y2="18"/>
            </svg>
          </button>
          <div className="topbar-title">{topbarTitle}</div>
          <div className="topbar-sub">{topbarSub}</div>
          <div className="topbar-spacer"></div>
          <div className="topbar-pill">
            {todayDay ? <>今日 · <b>{todayDay.title}</b></> :
             today < window.TRAIN_START ? <>訓練 <b>{window.daysBetween(today, window.TRAIN_START)}</b> 天後開始</> :
             today > window.RACE_ISO ? <>比賽已結束 🎉</> : <>今日休息</>}
          </div>
        </div>

        {tab === "home" && <window.Home data={data} progress={progress} gotoTab={goto} />}
        {tab === "plan" && <window.Plan data={data} progress={progress} updateProgress={updateProgress} />}
        {tab === "explain" && <window.Explain />}
        {tab === "zones" && <window.Zones />}
        {tab === "race" && <window.RaceDay />}
        {tab === "settings" && <window.Settings resetAll={resetAll} progress={progress} data={data} syncStatus={syncStatus} syncNow={syncNow} />}
      </main>
    </div>
  );
};

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