// Pages.jsx — every non-Overview route of the workspace. Each page is a real
// composition on the kit's own classes so the shell stays token-driven.

function PageHead({ eyebrow, meta, title, sub, actions }) {
  return (
    <div className="page-head">
      <div>
        <div className="eyebrow-row">
          <span className="pill">{eyebrow}</span>
          {meta && <span className="muted" style={{ font: "400 11px var(--font-mono)" }}>{meta}</span>}
        </div>
        <div className="page-title">{title}</div>
        {sub && <div className="page-sub">{sub}</div>}
      </div>
      {actions && <div className="row" style={{ gap: 8 }}>{actions}</div>}
    </div>
  );
}

function Bar({ value, max = 100, tone }) {
  const pct = Math.min(100, Math.round((value / max) * 100));
  return (
    <div className="bar">
      <div className={"bar__fill" + (tone ? " bar__fill--" + tone : "")} style={{ width: pct + "%" }} />
    </div>
  );
}

/* Palettes ---------------------------------------------------------- */
const PALETTE_LIBRARY = [
  ["neutral",    0,   0,  "Ground · any"],
  ["redGray",    8,   18, "Urgency · alerts"],
  ["orangeGray", 28,  20, "Energy · creative"],
  ["yellowGray", 48,  16, "Focus · learning"],
  ["greenGray",  120, 14, "Growth · health"],
  ["tealGray",   170, 16, "Harmony · wellness"],
  ["blueGray",   210, 18, "Trust · finance"],
  ["indigoGray", 240, 16, "Depth · research"],
  ["violetGray", 265, 16, "Spirit · insight"],
  ["magentaGray",320, 14, "Care · community"],
];
const RAMP_L = [97, 93, 86, 74, 60, 46, 38, 30, 22, 14, 8];
const RAMP_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];

function ramp(h, s) {
  return RAMP_L.map((l, i) => `hsl(${h} ${Math.min(s + Math.max(0, i - 5) * 2, 28)}% ${l}%)`);
}

function PalettesPage({ toast }) {
  const [selected, setSelected] = React.useState("blueGray");
  const [q, setQ] = React.useState("");
  const list = PALETTE_LIBRARY.filter(([n, , , use]) => (n + use).toLowerCase().includes(q.toLowerCase()));
  const sel = PALETTE_LIBRARY.find(([n]) => n === selected) || PALETTE_LIBRARY[6];
  const shades = ramp(sel[1], sel[2]);

  return (
    <div>
      <PageHead
        eyebrow="PALETTES"
        meta={`${PALETTE_LIBRARY.length} hue families · 11 steps`}
        title="Palettes"
        sub="Every ramp is one hue at fixed lightness stops. Saturation never exceeds 28% — color is felt, not shouted."
        actions={[
          <label key="s" className="topbar__search" style={{ width: 220, margin: 0 }}>
            <Icon name="search" size={14} />
            <input placeholder="Filter hue or intent…" value={q} onChange={(e) => setQ(e.target.value)} />
          </label>,
          <button key="n" className="btn btn--primary" onClick={() => toast("Created palette · untitled-7")}>
            <Icon name="plus" size={14} />New palette
          </button>,
        ]}
      />

      <div className="grid grid--two" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="card__head">
            <div className="card__title">{sel[0]} · {sel[1]}° · {sel[2]}% base saturation</div>
            <button className="btn btn--ghost" style={{ padding: "4px 8px" }} onClick={() => toast(`Copied ${sel[0]} ramp as CSS`)}>
              Copy CSS <Icon name="arrow-up-right" size={12} />
            </button>
          </div>
          <div className="ramp">
            {shades.map((c, i) => {
              const step = RAMP_STEPS[i];
              return (
                <button
                  key={step}
                  className="ramp__step"
                  style={{ background: c, color: i < 5 ? "hsl(0 0% 9%)" : "hsl(0 0% 98%)" }}
                  onClick={() => toast(`Copied --c-${sel[0]}-${step}`)}
                  title={c}
                >
                  <span>{step}</span>
                  <code>{RAMP_L[i]}%</code>
                </button>
              );
            })}
          </div>
          <div className="divider" />
          <div className="muted" style={{ fontSize: 12, lineHeight: 1.5 }}>
            Intent: <span style={{ color: "var(--foreground)" }}>{sel[3]}</span>. Steps 50–400 are surfaces, 500 is the semantic primary, 600–950 are text and dark-mode ground.
          </div>
        </div>

        <div className="card">
          <div className="card__head">
            <div className="card__title">Contrast check</div>
            <span className="pill pill--success">AA</span>
          </div>
          <div className="list">
            {[["500 on 50", "7.1 : 1", "success"], ["600 on 100", "6.4 : 1", "success"], ["400 on 950", "5.2 : 1", "success"], ["300 on 50", "1.9 : 1", "danger"]].map(([pair, ratio, tone]) => (
              <div className="list-item" key={pair}>
                <span className="list-item__avatar" style={{ background: shades[Number(pair.split(" ")[0]) / 100] }} />
                <div>
                  <div className="list-item__title">{pair}</div>
                  <div className="list-item__meta">body text</div>
                </div>
                <div className="list-item__right"><span className={"pill pill--" + tone}>{ratio}</span></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card__title" style={{ margin: "8px 4px 12px" }}>Library</div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(5, 1fr)" }}>
        {list.map(([name, h, s, use]) => (
          <button
            key={name}
            className={"tile" + (selected === name ? " tile--active" : "")}
            onClick={() => setSelected(name)}
          >
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 10 }}>
              <div className="row" style={{ gap: 8 }}>
                <span style={{ width: 18, height: 18, borderRadius: 4, background: `hsl(${h} ${s}% 46%)`, border: "1px solid var(--border)" }} />
                <span style={{ fontWeight: 500, fontSize: 13 }}>{name}</span>
              </div>
              <span className="muted" style={{ font: "400 11px var(--font-mono)" }}>{h}°</span>
            </div>
            <div className="ramp ramp--mini">
              {ramp(h, s).map((c, i) => <div key={i} style={{ background: c }} />)}
            </div>
            <div className="muted" style={{ fontSize: 11, marginTop: 8 }}>{use}</div>
          </button>
        ))}
        {list.length === 0 && <div className="muted" style={{ padding: 20, fontSize: 13 }}>No palettes match.</div>}
      </div>
    </div>
  );
}

/* Components -------------------------------------------------------- */
const COMPONENT_INVENTORY = [
  ["Actions",    ["Button", "Icon button", "Button group", "Split button", "Link", "Menu", "Context menu", "Dropdown", "Command palette", "Toolbar", "Floating action", "Segmented control"]],
  ["Inputs",     ["Text field", "Textarea", "Select", "Combobox", "Checkbox", "Radio", "Switch", "Slider", "Range", "Date picker", "Time picker", "Color picker", "File drop", "Search", "OTP", "Tag input", "Number field", "Rating"]],
  ["Feedback",   ["Toast", "Alert", "Banner", "Progress", "Progress ring", "Skeleton", "Spinner", "Empty state", "Tooltip", "Inline message", "Status dot"]],
  ["Navigation", ["Sidebar", "Topbar", "Tabs", "Breadcrumb", "Pagination", "Stepper", "Tree", "Anchor nav", "Bottom bar", "Link list"]],
  ["Surfaces",   ["Card", "Sheet", "Dialog", "Alert dialog", "Popover", "Hover card", "Drawer", "Accordion", "Collapsible", "Table", "Data grid", "Kanban", "Scroll area", "Resizable panel", "Aspect ratio", "Separator"]],
  ["Display",    ["Avatar", "Avatar group", "Badge", "Pill", "Metric", "Sparkline", "Chart", "Timeline", "Calendar", "Code block", "Keyboard key", "Description list", "Stat group", "Image", "Video", "Marquee", "Carousel"]],
];
const STATUSES = ["STABLE", "STABLE", "STABLE", "BETA", "STABLE", "REVIEW"];

function ComponentsPage({ toast }) {
  const [cat, setCat] = React.useState("All");
  const [checked, setChecked] = React.useState(true);
  const [radio, setRadio] = React.useState("md");
  const cats = ["All", ...COMPONENT_INVENTORY.map(([c]) => c)];
  const total = COMPONENT_INVENTORY.reduce((n, [, l]) => n + l.length, 0);
  const rows = COMPONENT_INVENTORY.filter(([c]) => cat === "All" || c === cat);

  return (
    <div>
      <PageHead
        eyebrow="COMPONENTS"
        meta={`${total} primitives · 6 categories`}
        title="Components"
        sub="Every primitive reads semantic tokens only. Swap the theme and the whole inventory recomposes."
        actions={<button className="btn btn--secondary" onClick={() => toast("Exported tokens · tailwind.config.ts")}><Icon name="arrow-up-right" size={14} />Export tokens</button>}
      />

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card__head">
          <div className="card__title">Live specimens</div>
          <span className="muted" style={{ font: "400 11px var(--font-mono)" }}>rendered · current theme</span>
        </div>
        <div className="specimen">
          <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
            <button className="btn btn--primary" onClick={() => toast("Primary pressed")}><Icon name="check" size={14} />Primary</button>
            <button className="btn btn--secondary">Secondary</button>
            <button className="btn btn--ghost">Ghost</button>
            <button className="icon-btn" aria-label="Settings"><Icon name="settings" size={16} /></button>
          </div>
          <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
            <span className="pill">DEFAULT</span>
            <span className="pill pill--success">SUCCESS</span>
            <span className="pill pill--warning">WARNING</span>
            <span className="pill pill--danger">DANGER</span>
            <span className="pill pill--info">INFO</span>
          </div>
          <div className="row" style={{ gap: 16, flexWrap: "wrap", alignItems: "flex-end" }}>
            <label className="field" style={{ width: 240 }}>
              <span className="field__label">Token name</span>
              <input className="field__input" defaultValue="--primary" />
            </label>
            <label className="check">
              <input type="checkbox" checked={checked} onChange={(e) => setChecked(e.target.checked)} />
              <span>Sync to Figma</span>
            </label>
            <div className="seg">
              {["sm", "md", "lg"].map((s) => (
                <button key={s} className={"seg__item" + (radio === s ? " seg__item--active" : "")} onClick={() => setRadio(s)}>{s}</button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="chip-row" style={{ marginBottom: 12 }}>
        {cats.map((c) => (
          <button key={c} className={"theme-chip" + (cat === c ? " theme-chip--active" : "")} onClick={() => setCat(c)}>{c}</button>
        ))}
      </div>

      <div className="grid" style={{ gridTemplateColumns: cat === "All" ? "repeat(3, 1fr)" : "1fr" }}>
        {rows.map(([category, list]) => (
          <div className="card" key={category} style={{ padding: 16 }}>
            <div className="card__head" style={{ marginBottom: 8 }}>
              <div className="card__title">{category}</div>
              <span className="nav-item__count">{list.length}</span>
            </div>
            <div className="list">
              {list.map((name, i) => {
                const status = STATUSES[(name.length + i) % STATUSES.length];
                const tone = status === "STABLE" ? "success" : status === "BETA" ? "info" : "warning";
                return (
                  <div className="list-item" key={name} style={{ padding: "8px 0" }}>
                    <Icon name="box" size={14} style={{ color: "var(--muted-foreground)" }} />
                    <div className="list-item__title">{name}</div>
                    <div className="list-item__right"><span className={"pill pill--" + tone}>{status}</span></div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* Typography -------------------------------------------------------- */
const TYPE_SCALE = [
  ["Display",  "600 44px/1.05",  "-0.03em", "--font-sans", "The law of gradation"],
  ["Heading 1","600 30px/1.15",  "-0.02em", "--font-sans", "Twenty intention-mapped themes"],
  ["Heading 2","600 22px/1.2",   "-0.01em", "--font-sans", "Saturation is a ceiling, not a target"],
  ["Heading 3","600 17px/1.3",   "-0.01em", "--font-sans", "Semantic tokens compose by hue family"],
  ["Body",     "400 14px/1.55",  "0",       "--font-sans", "Color should be felt before it is seen. A palette that announces itself has already failed the reader; the eye belongs on the content."],
  ["Small",    "400 12px/1.5",   "0",       "--font-sans", "Secondary explanation, captions, helper text under fields."],
  ["Mono",     "400 12px/1.5",   "0",       "--font-mono", "hsl(210 18% 38%) · --primary · 0.25rem"],
  ["Eyebrow",  "600 10px/1.2",   "0.08em",  "--font-mono", "CALIBRATED · 8–24% SATURATION"],
];

function TypographyPage() {
  const [sample, setSample] = React.useState("");
  return (
    <div>
      <PageHead
        eyebrow="TYPOGRAPHY"
        meta="Geist Sans · Geist Mono · 8 steps"
        title="Typography"
        sub="Two families, one scale. Weight and tracking tighten as size grows; nothing below 12px carries meaning."
        actions={
          <label className="topbar__search" style={{ width: 280, margin: 0 }}>
            <Icon name="type" size={14} />
            <input placeholder="Type to preview your own copy…" value={sample} onChange={(e) => setSample(e.target.value)} />
          </label>
        }
      />
      <div className="card" style={{ padding: 0 }}>
        {TYPE_SCALE.map(([name, font, tracking, family, text]) => (
          <div className="type-row" key={name}>
            <div className="type-row__meta">
              <div style={{ fontWeight: 500, fontSize: 13 }}>{name}</div>
              <code className="muted" style={{ fontSize: 11 }}>{font} · {tracking}</code>
              <code className="muted" style={{ fontSize: 11 }}>{family}</code>
            </div>
            <div className="type-row__sample" style={{ font: `${font} var(${family})`, letterSpacing: tracking, textTransform: name === "Eyebrow" ? "uppercase" : "none" }}>
              {sample || text}
            </div>
          </div>
        ))}
      </div>
      <div className="grid grid--two" style={{ marginTop: 16 }}>
        <div className="card">
          <div className="card__head"><div className="card__title">Rules</div></div>
          <div className="list">
            {[
              ["Body line-height", "1.5–1.6", "Readable at 14px across 60–75 characters."],
              ["Heading tracking", "-0.01 to -0.03em", "Tighter as size grows; never positive on sans headings."],
              ["Mono usage", "tokens · values · code", "Never for prose. Never for headings."],
              ["Minimum size", "12px", "Eyebrows at 10px are uppercase mono only."],
            ].map(([k, v, d]) => (
              <div className="list-item" key={k}>
                <div>
                  <div className="list-item__title">{k} <code style={{ fontSize: 11, marginLeft: 6 }}>{v}</code></div>
                  <div className="list-item__meta">{d}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="card">
          <div className="card__head"><div className="card__title">Families</div></div>
          <div style={{ font: "600 34px/1.1 var(--font-sans)", letterSpacing: "-0.02em" }}>Aa Gg Rr</div>
          <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>Geist Sans · 400 500 600</div>
          <div className="divider" />
          <div style={{ font: "400 26px/1.1 var(--font-mono)" }}>0O 1lI {"{}"}</div>
          <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>Geist Mono · 400 500</div>
        </div>
      </div>
    </div>
  );
}

/* Activity ---------------------------------------------------------- */
const ACTIVITY = [
  ["EB", "Edwin B.",  "regenerated palette", "harmony · 11 shades",        "12m",       "palette"],
  ["AB", "Annie B.",  "exported tokens",     "tailwind.config.ts",         "47m",       "export"],
  ["CL", "C. Lead",   "approved review",     "Card · radius-lg",           "2h",        "review"],
  ["MK", "M. Kahn",   "added theme",         "spirit",                     "5h",        "theme"],
  ["JM", "J. Mendez", "fixed contrast",      "muted-foreground · light",   "yesterday", "review"],
  ["EB", "Edwin B.",  "renamed token",       "--accent → --accent-soft",   "yesterday", "palette"],
  ["AB", "Annie B.",  "published",           "v2.4.0 · 84 components",     "2d",        "export"],
  ["MK", "M. Kahn",   "opened review",       "Dialog · focus ring",        "2d",        "review"],
  ["CL", "C. Lead",   "archived theme",      "legacy-blue",                "3d",        "theme"],
];

function ActivityPage() {
  const [filter, setFilter] = React.useState("all");
  const kinds = [["all", "All"], ["palette", "Palettes"], ["theme", "Themes"], ["review", "Reviews"], ["export", "Exports"]];
  const items = ACTIVITY.filter((a) => filter === "all" || a[5] === filter);
  return (
    <div>
      <PageHead eyebrow="ACTIVITY" meta={`${ACTIVITY.length} events · 7 unread`} title="Activity" sub="Everything the workspace did, in order. Reviews and exports are the two events that ship." />
      <div className="grid grid--two">
        <div>
          <div className="chip-row" style={{ marginBottom: 12 }}>
            {kinds.map(([id, label]) => (
              <button key={id} className={"theme-chip" + (filter === id ? " theme-chip--active" : "")} onClick={() => setFilter(id)}>{label}</button>
            ))}
          </div>
          <div className="card">
            <div className="list">
              {items.map(([initials, name, action, target, when, kind], i) => (
                <div className="list-item" key={name + when + i}>
                  <span className="list-item__avatar">{initials}</span>
                  <div>
                    <div className="list-item__title">
                      <span style={{ fontWeight: 500 }}>{name}</span> <span className="muted">{action}</span> <code style={{ fontSize: 11 }}>{target}</code>
                    </div>
                    <div className="list-item__meta">{when} ago</div>
                  </div>
                  <div className="list-item__right">
                    <span className={"pill " + (kind === "review" ? "pill--warning" : kind === "export" ? "pill--info" : "pill--success")}>{kind.toUpperCase()}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="card">
          <div className="card__head"><div className="card__title">This week</div></div>
          {[["Palettes touched", 14, 20], ["Reviews closed", 9, 12], ["Exports", 6, 6], ["Themes added", 2, 4]].map(([k, v, max]) => (
            <div key={k} style={{ marginBottom: 14 }}>
              <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                <span style={{ fontSize: 13 }}>{k}</span>
                <span className="muted" style={{ font: "400 11px var(--font-mono)" }}>{v}/{max}</span>
              </div>
              <Bar value={v} max={max} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* Library ----------------------------------------------------------- */
const FOLDERS = [
  ["Brand",        "folder", 12, "2h"],
  ["Tokens",       "file",   48, "12m"],
  ["Components",   "layers", 84, "47m"],
  ["Illustration", "folder", 19, "3d"],
  ["Motion",       "play",   7,  "1w"],
  ["Docs",         "file",   23, "yesterday"],
  ["Exports",      "arrow-up-right", 31, "2d"],
  ["Archive",      "box",    102, "3w"],
];

function LibraryPage({ toast }) {
  return (
    <div>
      <PageHead
        eyebrow="LIBRARY"
        meta={`${FOLDERS.reduce((n, f) => n + f[2], 0)} files · 8 folders`}
        title="Library"
        sub="Source of truth for every asset the system ships. Exports are generated, never hand-edited."
        actions={<button className="btn btn--primary" onClick={() => toast("Upload started · 3 files")}><Icon name="plus" size={14} />Upload</button>}
      />
      <div className="grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", marginBottom: 16 }}>
        {FOLDERS.map(([name, icon, count, when]) => (
          <button key={name} className="tile" onClick={() => toast(`Opened ${name}`)}>
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 14 }}>
              <span className="icon-btn" style={{ pointerEvents: "none" }}><Icon name={icon} size={16} /></span>
              <span className="nav-item__count">{count}</span>
            </div>
            <div style={{ fontWeight: 500, fontSize: 13 }}>{name}</div>
            <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>updated {when} ago</div>
          </button>
        ))}
      </div>
      <div className="card">
        <div className="card__head"><div className="card__title">Recent</div></div>
        <div className="list">
          {[["tailwind.config.ts", "Exports", "4.1 KB", "12m"], ["colors_and_type.css", "Tokens", "18.2 KB", "47m"], ["chromatic-mark.svg", "Brand", "1.0 KB", "2h"], ["Card.stories.tsx", "Components", "2.7 KB", "yesterday"]].map(([f, folder, size, when]) => (
            <div className="list-item" key={f}>
              <Icon name="file" size={14} style={{ color: "var(--muted-foreground)" }} />
              <div>
                <div className="list-item__title"><code style={{ fontSize: 12 }}>{f}</code></div>
                <div className="list-item__meta">{folder} · {size}</div>
              </div>
              <div className="list-item__right muted" style={{ font: "400 11px var(--font-mono)" }}>{when} ago</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* Inbox ------------------------------------------------------------- */
const INBOX_SEED = [
  { id: 1, from: "Annie B.",  initials: "AB", subject: "Review requested · Dialog focus ring", body: "The ring reads 2px on retina but 1px on 1x. Can we lock it to --ring at 2px and let the browser round?", when: "9m",  unread: true },
  { id: 2, from: "System",    initials: "CS", subject: "Export finished · tailwind.config.ts",  body: "84 components, 20 themes, 0 warnings. Hash 7f3a…e2.", when: "47m", unread: true },
  { id: 3, from: "M. Kahn",   initials: "MK", subject: "spirit theme is live",                  body: "Pushed to main. Saturation held at 16%. Dark-mode ground is 265 22% 8%.", when: "5h",  unread: true },
  { id: 4, from: "C. Lead",   initials: "CL", subject: "Approved · Card radius-lg",            body: "12px it is. Closing the thread.", when: "2h", unread: false },
  { id: 5, from: "J. Mendez", initials: "JM", subject: "Contrast fix merged",                  body: "muted-foreground on light is now 45% lightness. 4.6:1 against --background.", when: "yesterday", unread: false },
];

function InboxPage({ toast, items, setItems }) {
  const [openId, setOpenId] = React.useState(items[0] ? items[0].id : null);
  const open = items.find((m) => m.id === openId);
  const unread = items.filter((m) => m.unread).length;

  function select(id) {
    setOpenId(id);
    setItems((l) => l.map((m) => (m.id === id ? { ...m, unread: false } : m)));
  }
  function archive(id) {
    setItems((l) => l.filter((m) => m.id !== id));
    setOpenId((cur) => (cur === id ? null : cur));
    toast("Archived");
  }

  return (
    <div>
      <PageHead
        eyebrow="INBOX"
        meta={`${unread} unread · ${items.length} total`}
        title="Inbox"
        sub="Reviews, exports, and mentions. Mark everything read and the sidebar count follows."
        actions={<button className="btn btn--secondary" onClick={() => { setItems((l) => l.map((m) => ({ ...m, unread: false }))); toast("All read"); }}><Icon name="check" size={14} />Mark all read</button>}
      />
      <div className="grid" style={{ gridTemplateColumns: "minmax(280px, 1fr) 2fr" }}>
        <div className="card" style={{ padding: 8 }}>
          {items.map((m) => (
            <button key={m.id} className={"mail" + (m.id === openId ? " mail--active" : "")} onClick={() => select(m.id)}>
              <span className="list-item__avatar">{m.initials}</span>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="row" style={{ justifyContent: "space-between", gap: 8 }}>
                  <span style={{ fontWeight: m.unread ? 600 : 500, fontSize: 13 }}>{m.from}</span>
                  <span className="muted" style={{ font: "400 11px var(--font-mono)" }}>{m.when}</span>
                </div>
                <div className="mail__subject" style={{ fontWeight: m.unread ? 500 : 400 }}>{m.subject}</div>
              </div>
              {m.unread && <span className="mail__dot" />}
            </button>
          ))}
          {items.length === 0 && <div className="muted" style={{ padding: 24, fontSize: 13, textAlign: "center" }}>Inbox zero.</div>}
        </div>
        <div className="card">
          {open ? (
            <div>
              <div className="card__head" style={{ alignItems: "flex-start" }}>
                <div>
                  <div style={{ font: "600 17px/1.3 var(--font-sans)", letterSpacing: "-0.01em" }}>{open.subject}</div>
                  <div className="list-item__meta" style={{ marginTop: 4 }}>{open.from} · {open.when} ago</div>
                </div>
                <div className="row" style={{ gap: 6 }}>
                  <button className="icon-btn" aria-label="Archive" onClick={() => archive(open.id)}><Icon name="trash" size={14} /></button>
                </div>
              </div>
              <div style={{ fontSize: 14, lineHeight: 1.6, color: "var(--foreground)" }}>{open.body}</div>
              <div className="divider" />
              <div className="row" style={{ gap: 8 }}>
                <button className="btn btn--primary" onClick={() => toast("Reply sent")}><Icon name="arrow-right" size={14} />Reply</button>
                <button className="btn btn--secondary" onClick={() => toast("Opened thread")}>Open thread</button>
              </div>
            </div>
          ) : (
            <div className="muted" style={{ padding: 40, textAlign: "center", fontSize: 13 }}>Select a message.</div>
          )}
        </div>
      </div>
    </div>
  );
}

/* Team -------------------------------------------------------------- */
const TEAM_SEED = [
  ["EB", "Edwin B.",  "edwin@chromatic.design",  "Owner",  "active"],
  ["AB", "Annie B.",  "annie@chromatic.design",  "Admin",  "active"],
  ["CL", "C. Lead",   "cl@chromatic.design",     "Editor", "active"],
  ["MK", "M. Kahn",   "m.kahn@chromatic.design", "Editor", "active"],
  ["JM", "J. Mendez", "jm@chromatic.design",     "Viewer", "invited"],
];
const ROLES = ["Owner", "Admin", "Editor", "Viewer"];

function TeamPage({ toast }) {
  const [team, setTeam] = React.useState(TEAM_SEED);
  const [email, setEmail] = React.useState("");
  function invite(e) {
    e.preventDefault();
    if (!email.includes("@")) return;
    const initials = email.slice(0, 2).toUpperCase();
    setTeam((t) => [...t, [initials, email.split("@")[0], email, "Viewer", "invited"]]);
    setEmail("");
    toast(`Invited ${email}`);
  }
  function setRole(i, role) {
    setTeam((t) => t.map((m, idx) => (idx === i ? [m[0], m[1], m[2], role, m[4]] : m)));
    toast(`${team[i][1]} → ${role}`);
  }
  return (
    <div>
      <PageHead eyebrow="TEAM" meta={`${team.length} members · 1 owner`} title="Team" sub="Roles gate publishing. Editors change tokens; only Admins export." />
      <div className="grid grid--two">
        <div className="card" style={{ padding: 0 }}>
          <table className="table">
            <thead>
              <tr><th>Member</th><th>Role</th><th>Status</th><th /></tr>
            </thead>
            <tbody>
              {team.map(([initials, name, mail, role, status], i) => (
                <tr key={mail}>
                  <td>
                    <div className="row" style={{ gap: 10 }}>
                      <span className="list-item__avatar">{initials}</span>
                      <div>
                        <div style={{ fontWeight: 500, fontSize: 13 }}>{name}</div>
                        <div className="list-item__meta">{mail}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <select className="select" value={role} disabled={role === "Owner"} onChange={(e) => setRole(i, e.target.value)}>
                      {ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
                    </select>
                  </td>
                  <td><span className={"pill " + (status === "active" ? "pill--success" : "pill--warning")}>{status.toUpperCase()}</span></td>
                  <td style={{ textAlign: "right" }}>
                    {role !== "Owner" && (
                      <button className="icon-btn" aria-label="Remove" onClick={() => { setTeam((t) => t.filter((_, idx) => idx !== i)); toast(`Removed ${name}`); }}>
                        <Icon name="x" size={14} />
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card">
          <div className="card__head"><div className="card__title">Invite</div></div>
          <form className="col" style={{ gap: 12 }} onSubmit={invite}>
            <label className="field">
              <span className="field__label">Email</span>
              <input className="field__input" type="email" placeholder="name@company.com" value={email} onChange={(e) => setEmail(e.target.value)} />
            </label>
            <button className="btn btn--primary" type="submit" style={{ justifyContent: "center" }}><Icon name="plus" size={14} />Send invite</button>
          </form>
          <div className="divider" />
          <div className="muted" style={{ fontSize: 12, lineHeight: 1.5 }}>Invites default to Viewer. Promote after the first approved review.</div>
        </div>
      </div>
    </div>
  );
}

/* Billing ----------------------------------------------------------- */
function BillingPage({ toast }) {
  const [plan, setPlan] = React.useState("Team");
  const plans = [
    ["Free", "$0",  "3 themes · 1 export/day · 1 seat"],
    ["Team", "$48", "20 themes · unlimited exports · 5 seats"],
    ["Pro",  "$120","Unlimited · SSO · audit log · 25 seats"],
  ];
  return (
    <div>
      <PageHead
        eyebrow="BILLING"
        meta="Team · renews Oct 14"
        title="Billing"
        sub="Usage resets on the renewal date. Seats above the plan are billed at the plan's per-seat rate."
        actions={<button className="btn btn--secondary" onClick={() => toast("Opened invoice history")}><Icon name="file" size={14} />Invoices</button>}
      />
      <div className="grid" style={{ gridTemplateColumns: "repeat(3, 1fr)", marginBottom: 16 }}>
        {plans.map(([name, price, desc]) => (
          <button key={name} className={"tile" + (plan === name ? " tile--active" : "")} onClick={() => { setPlan(name); toast(`Plan → ${name}`); }}>
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 8 }}>
              <span style={{ fontWeight: 600, fontSize: 14 }}>{name}</span>
              {plan === name && <span className="pill pill--success">CURRENT</span>}
            </div>
            <div style={{ font: "600 28px/1.1 var(--font-sans)", letterSpacing: "-0.02em" }}>{price}<span className="muted" style={{ font: "400 12px var(--font-sans)" }}> /mo</span></div>
            <div className="muted" style={{ fontSize: 12, marginTop: 8, lineHeight: 1.5 }}>{desc}</div>
          </button>
        ))}
      </div>
      <div className="grid grid--two">
        <div className="card">
          <div className="card__head"><div className="card__title">Usage this cycle</div><span className="muted" style={{ font: "400 11px var(--font-mono)" }}>18 days left</span></div>
          {[["Seats", 5, 5, "warning"], ["Themes", 20, 20, "warning"], ["Exports", 61, 500, null], ["Storage", 2.1, 10, null]].map(([k, v, max, tone]) => (
            <div key={k} style={{ marginBottom: 14 }}>
              <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                <span style={{ fontSize: 13 }}>{k}</span>
                <span className="muted" style={{ font: "400 11px var(--font-mono)" }}>{v} / {max}{k === "Storage" ? " GB" : ""}</span>
              </div>
              <Bar value={v} max={max} tone={tone} />
            </div>
          ))}
        </div>
        <div className="card">
          <div className="card__head"><div className="card__title">Payment method</div></div>
          <div className="row" style={{ gap: 12 }}>
            <span className="icon-btn" style={{ pointerEvents: "none" }}><Icon name="credit-card" size={16} /></span>
            <div>
              <div style={{ fontWeight: 500, fontSize: 13 }}>Visa ending 4242</div>
              <div className="list-item__meta">exp 08/28</div>
            </div>
          </div>
          <div className="divider" />
          <div className="list">
            {[["Sep 14", "$48.00", "PAID"], ["Aug 14", "$48.00", "PAID"], ["Jul 14", "$48.00", "PAID"]].map(([d, amt, s]) => (
              <div className="list-item" key={d} style={{ padding: "8px 0" }}>
                <span style={{ fontSize: 13 }}>{d}</span>
                <span className="muted" style={{ font: "400 12px var(--font-mono)", marginLeft: "auto", marginRight: 12 }}>{amt}</span>
                <span className="pill pill--success">{s}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.PalettesPage = PalettesPage;
window.ComponentsPage = ComponentsPage;
window.TypographyPage = TypographyPage;
window.ActivityPage = ActivityPage;
window.LibraryPage = LibraryPage;
window.InboxPage = InboxPage;
window.INBOX_SEED = INBOX_SEED;
window.TeamPage = TeamPage;
window.BillingPage = BillingPage;
