// App shell — 左側固定側欄 + 主內容（hash 路由）
(() => {
const { Panel, Badge } = window.WCATalentGameDesignSystem_377d00;

const NAV = [
  { hash: "#/", label: "戰情總覽", en: "COMMAND", ready: true },
  { hash: "#/map", label: "創業地圖", en: "MAP", ready: true },
  { hash: "#/quests", label: "關卡工作區", en: "QUESTS", ready: true },
  { hash: "#/energy", label: "能量與軍餉", en: "SUPPLY", ready: true },
  { hash: "#/pitch", label: "Pitch 組裝台", en: "FINAL", ready: true },
  { hash: "#/guide", label: "使用說明", en: "GUIDE", ready: true },
];
const ADMIN_NAV = [
  { hash: "#/admin", label: "戰情監控", en: "WAR ROOM", ready: true },
  { hash: "#/admin/settings", label: "活動設定", en: "RULES", ready: true },
];

function useHash() {
  const [hash, setHash] = React.useState(location.hash || "#/");
  React.useEffect(() => {
    const on = () => setHash(location.hash || "#/");
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return hash;
}

function Placeholder({ title }) {
  return (
    <Panel header={title}>
      <div style={{ textAlign: "center", padding: "48px 0", color: "var(--text-muted)" }}>
        <div style={{ fontSize: 30, color: "var(--gold-500)", marginBottom: 12 }}>◆</div>
        <div style={{ letterSpacing: ".15em" }}>此區域尚在鍛造中</div>
        <div style={{ fontFamily: "Cinzel,serif", fontSize: 11, letterSpacing: ".3em", marginTop: 8 }}>UNDER FORGING</div>
      </div>
    </Panel>
  );
}

function App() {
  const hash = useHash();
  const [me, setMe] = React.useState(null);
  const [mobileNav, setMobileNav] = React.useState(false);
  React.useEffect(() => { api("/api/me").then(setMe).catch(() => {}); }, []);

  const logout = async () => { await api("/api/logout", { method: "POST" }); location.href = "/login.html"; };

  const sidebar = (
    <nav style={{
      width: 216, minWidth: 216, background: "var(--navy-900)", borderRight: "1px solid var(--border-default)",
      display: "flex", flexDirection: "column", padding: "20px 14px", gap: 4,
    }}>
      <img src="/assets/wca-logo.png" alt="WCA" style={{ width: 150, margin: "0 auto 6px" }} />
      <div style={{ textAlign: "center", fontFamily: "Cinzel,serif", color: "var(--gold-500)", fontSize: 10, letterSpacing: ".32em", marginBottom: 18 }}>
        STARTUP QUEST
      </div>
      {(me && me.role === "admin" ? ADMIN_NAV : NAV).map((n) => {
        const active = hash === n.hash || (n.hash !== "#/" && hash.startsWith(n.hash));
        return (
          <a key={n.hash} href={n.hash} onClick={() => setMobileNav(false)} style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "10px 14px", borderRadius: 999, textDecoration: "none",
            background: active ? "linear-gradient(180deg,#e6c96b,#b8912b)" : "transparent",
            color: active ? "#1a1406" : "var(--text-secondary)",
            fontWeight: active ? 700 : 400, fontSize: 14, letterSpacing: ".06em",
            transition: "all var(--dur-fast, .15s)",
          }}>
            <span>{n.label}</span>
            {!n.ready && <span style={{ fontSize: 9, opacity: .6, fontFamily: "Cinzel,serif", letterSpacing: ".1em" }}>SOON</span>}
          </a>
        );
      })}
      <div style={{ marginTop: "auto", paddingTop: 16, borderTop: "1px solid var(--border-default)" }}>
        {me && (
          <div style={{ fontSize: 13, color: "var(--gold-300)", marginBottom: 8, textAlign: "center", letterSpacing: ".08em" }}>
            {me.role === "admin" ? "系統管理員" : me.team_name}
          </div>
        )}
        <button onClick={logout} style={{
          width: "100%", background: "transparent", border: "1px solid var(--border-default)",
          color: "var(--text-muted)", borderRadius: 6, padding: "7px 0", cursor: "pointer", fontSize: 12, letterSpacing: ".2em",
        }}>離開戰場</button>
      </div>
    </nav>
  );

  let page = <Placeholder title="戰情總覽" />;
  const questMatch = hash.match(/^#\/quests\/(\d+)$/);
  const isAdmin = me && me.role === "admin";
  if (!me) page = <div style={{ color: "var(--text-muted)", padding: 60, textAlign: "center", letterSpacing: ".2em" }}>載入中…</div>;
  else if (isAdmin) {
    if (hash === "#/admin/settings") page = <window.AdminSettings />;
    else page = <window.AdminMonitor />;
  }
  else if (hash === "#/") page = <window.Overview me={me} />;
  else if (questMatch) page = <window.ModuleView id={questMatch[1]} />;
  else if (hash === "#/quests") page = <window.Quests />;
  else if (hash === "#/map") page = <window.MapPage />;
  else if (hash === "#/energy") page = <window.Energy />;
  else if (hash === "#/pitch") page = <window.Pitch />;
  else if (hash === "#/guide") page = <window.Guide />;
  else {
    const item = NAV.find((n) => hash.startsWith(n.hash) && n.hash !== "#/");
    page = <Placeholder title={item ? item.label : "未知區域"} />;
  }

  return (
    <div style={{ display: "flex", minHeight: "100vh", fontFamily: '"Noto Sans TC",sans-serif', color: "var(--text-primary)", background: "#05070f" }}>
      {/* 主視窗底圖：魔幻古戰場地圖＋深色遮罩（fixed 層避免 iOS background-attachment 問題） */}
      <div aria-hidden style={{
        position: "fixed", inset: 0, zIndex: 0, pointerEvents: "none",
        background: "linear-gradient(rgba(5,7,15,.5), rgba(5,7,15,.68)), url(/assets/battlefield-map.jpg) center / cover no-repeat",
      }} />
      {/* 桌機側欄 */}
      <div className="sq-sidebar" style={{ display: "flex", position: "relative", zIndex: 1 }}>{sidebar}</div>
      <main style={{
        flex: 1, minWidth: 0, padding: "24px 28px 60px",
        position: "relative", zIndex: 1,
      }}>
        {/* 手機頂欄 */}
        <div className="sq-mobilebar" style={{ display: "none", alignItems: "center", gap: 12, marginBottom: 14 }}>
          <button onClick={() => setMobileNav(!mobileNav)} style={{
            background: "transparent", border: "1px solid var(--border-default)", color: "var(--gold-300)",
            borderRadius: 6, padding: "6px 12px", cursor: "pointer", fontSize: 16,
          }}>☰</button>
          <img src="/assets/wca-crest.png" alt="" style={{ height: 30 }} />
          <span style={{ fontFamily: '"Noto Serif TC",serif', color: "var(--gold-300)", fontWeight: 900, letterSpacing: ".1em" }}>AI 創業戰情室</span>
        </div>
        {mobileNav && (
          <div onClick={() => setMobileNav(false)} style={{ position: "fixed", inset: 0, zIndex: 90, background: "rgba(5,7,15,.7)" }}>
            <div onClick={(e) => e.stopPropagation()} style={{ width: 230, height: "100%", background: "var(--navy-900)", display: "flex" }}>{sidebar}</div>
          </div>
        )}
        {page}
      </main>
      <style>{`
        @media (max-width: 760px) {
          .sq-sidebar { display: none !important; }
          .sq-mobilebar { display: flex !important; }
        }
      `}</style>
    </div>
  );
}

window.App = App;
})();
