// App shell: sidebar nav + user menu pop

const { useState: useStateS } = React;

// ME is set dynamically from /api/v1/account on app load.
let ME = { name: "", email: "" };

function AppShell({ ctx }) {
  const { t, route, setRoute } = ctx;
  const [userMenuOpen, setUserMenuOpen] = useStateS(false);

  const navItems = [
    { k: "networks",  l: t.nav.networks,  icon: "⌥" },
    { k: "support",   l: t.nav.support,   icon: "?" },
  ];

  return (
    <div style={{ display: "grid", gridTemplateColumns: "var(--sidebar-w) 1fr", minHeight: "100vh" }}>
      <aside style={{
        borderRight: "1px solid var(--line)", background: "var(--bg-2)",
        display: "flex", flexDirection: "column", position: "sticky", top: 0, height: "100vh",
      }}>
        <div style={{ padding: "18px 16px 14px 16px", display: "flex", alignItems: "center", gap: 10 }}>
          <LogoMark size={22}/>
          <span style={{ flex: 1 }}/>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{window._wwVersion || ""}</span>
        </div>

        <nav style={{ padding: "6px 10px", flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 2 }}>
          {navItems.map(item => (
            <NavLink key={item.k} {...item}
              active={route === item.k || (item.k === "networks" && route === "network")}
              onClick={() => { ctx.setNetworkId(null); setRoute(item.k); }}/>
          ))}
        </nav>

        <div style={{ padding: 10, borderTop: "1px solid var(--line-2)" }}>
          <UserMenu ctx={ctx} open={userMenuOpen} setOpen={setUserMenuOpen}/>
        </div>
      </aside>

      <main style={{ minWidth: 0, position: "relative" }}>
        <TopRightControls ctx={ctx}/>
        <div style={{ padding: "28px 36px 56px 36px", maxWidth: 1400, margin: "0 auto" }}>
          <AppRouter ctx={ctx}/>
        </div>
      </main>
    </div>
  );
}

function NavLink({ k, l, icon, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "flex", alignItems: "center", gap: 10, width: "100%",
      padding: "7px 10px", borderRadius: 6, border: 0,
      background: active ? "var(--bg)" : "transparent",
      color: active ? "var(--ink)" : "var(--ink-2)",
      cursor: "pointer", fontSize: 13, textAlign: "left",
      boxShadow: active ? "0 0 0 1px var(--line)" : "none",
      fontWeight: active ? 500 : 400,
    }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.background = "var(--bg-3)"; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.background = "transparent"; }}
    >
      <Ic c={icon} color={active ? "var(--accent)" : "var(--ink-3)"}/>
      {l}
    </button>
  );
}

function UserMenu({ ctx, open, setOpen }) {
  const { t, setRoute } = ctx;
  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(!open)} style={{
        width: "100%", display: "flex", alignItems: "center", gap: 10,
        padding: "8px 10px", borderRadius: 8, border: 0,
        background: "transparent", cursor: "pointer", textAlign: "left",
      }}>
        <Avatar name={ME.name} size={28}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 500 }}>{ME.name}</div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 2 }}>{ME.email}</div>
        </div>
        <span style={{ fontSize: 11, color: "var(--ink-3)" }}>⋯</span>
      </button>

      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 30 }}/>
          <div style={{
            position: "absolute", bottom: "calc(100% + 4px)", left: 0, right: 0, zIndex: 40,
            background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 10,
            boxShadow: "0 -12px 40px -12px color-mix(in oklab, var(--ink) 30%, transparent)",
            padding: 6, display: "flex", flexDirection: "column",
          }}>
            <MenuItem onClick={() => { setRoute("settings"); setOpen(false); }}>{t.common.settings}</MenuItem>
            {ME.is_admin && <MenuItem onClick={() => { window.location.href = "admin.html"; }}>Admin Panel</MenuItem>}
            <MenuItem onClick={() => { window.location.href = "index.html"; }}>{t.common.backToSite}</MenuItem>
            <MenuItem onClick={() => { ww.logout(); window.location.href = "login.html"; }}>{t.common.signOut}</MenuItem>
          </div>
        </>
      )}
    </div>
  );
}

function TopRightControls({ ctx }) {
  const { lang, setLang, theme, toggleTheme } = ctx;
  return (
    <div style={{
      position: "absolute", top: 18, right: 24, zIndex: 25,
      display: "flex", gap: 8, alignItems: "center",
    }}>
      <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 6, padding: 2, background: "var(--bg-2)" }}>
        {["en", "zh"].map(l => (
          <button key={l} onClick={() => setLang(l)} style={{
            padding: "4px 10px", border: 0, borderRadius: 4,
            background: lang === l ? "var(--bg)" : "transparent",
            fontFamily: "var(--mono)", fontSize: 11, cursor: "pointer",
            color: lang === l ? "var(--ink)" : "var(--ink-3)",
            textTransform: "uppercase", letterSpacing: 0.05,
          }}>{l === "en" ? "EN" : "中"}</button>
        ))}
      </div>
      <button onClick={toggleTheme} aria-label="theme" style={{
        width: 30, height: 30, borderRadius: 6, border: "1px solid var(--line)",
        background: "var(--bg-2)", color: "var(--ink-2)", cursor: "pointer",
        display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 13,
      }}>{theme === "dark" ? "☾" : "☀"}</button>
    </div>
  );
}

function MenuItem({ children, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: "100%", textAlign: "left", padding: "8px 10px", borderRadius: 6,
      border: 0, background: "transparent", cursor: "pointer",
      color: "var(--ink-2)", fontSize: 13, fontFamily: "inherit",
    }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
      onMouseLeave={e => e.currentTarget.style.background = "transparent"}
    >{children}</button>
  );
}

function AppRouter({ ctx }) {
  const { route } = ctx;
  switch (route) {
    case "networks":  return <NetworksList ctx={ctx}/>;
    case "network":   return <NetworkDetail ctx={ctx}/>;
    case "support":   return <SupportPage ctx={ctx}/>;
    case "settings":  return <SettingsPage ctx={ctx}/>;
    default:          return <NetworksList ctx={ctx}/>;
  }
}

function AppTweaks({ state, setState, onReset }) {
  const t = APP_I18N[state.lang];
  return (
    <div style={{
      position: "fixed", bottom: 20, right: 20, zIndex: 60, width: 280,
      background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 12,
      boxShadow: "0 20px 50px -20px color-mix(in oklab, var(--ink) 35%, transparent)", overflow: "hidden",
    }}>
      <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ fontSize: 13, fontWeight: 500 }}>Tweaks</span>
        <button onClick={onReset} style={{ border: 0, background: "transparent", fontSize: 11, color: "var(--ink-3)", cursor: "pointer", fontFamily: "var(--mono)" }}>reset</button>
      </div>
      <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
        <div><div className="kicker" style={{ fontSize: 10, marginBottom: 6 }}>{t.common.language}</div>
          <Segmented value={state.lang} options={[["en", "EN"], ["zh", "中文"]]} onChange={v => setState({ ...state, lang: v })}/></div>
        <div><div className="kicker" style={{ fontSize: 10, marginBottom: 6 }}>{t.common.theme}</div>
          <Segmented value={state.theme} options={[["light", t.common.light], ["dark", t.common.dark]]} onChange={v => setState({ ...state, theme: v })}/></div>
      </div>
    </div>
  );
}

Object.assign(window, { AppShell, AppTweaks, ME });
