// dash-tabs.jsx — all dashboard tab screens (each fully functional)
const { useState: useT, useEffect: useTE, useRef: useTR } = React;

/* ---------- small building blocks ---------- */
function Card({ children, strong, style, className = "", ...rest }) {
  return <div className={(strong ? "glass-strong" : "glass") + " " + className} style={{ borderRadius: "var(--radius)", padding: 24, ...style }} {...rest}>{children}</div>;
}
function StatTile({ label, value, icon, accent }) {
  return (
    <div className="glass" style={{ padding: 18, borderRadius: "var(--radius-sm)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
        <span className="cap" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
        <span style={{ color: "var(--accent)" }}><DIcon name={icon} size={17} /></span>
      </div>
      <div style={{ fontSize: 27, fontWeight: 680, letterSpacing: "-0.03em", fontVariantNumeric: "tabular-nums", color: accent ? "var(--accent)" : "var(--ink)" }}>{value}</div>
    </div>
  );
}
function Badge({ running, idleText = "Idle", liveText = "Live" }) {
  return running
    ? <span className="status ok"><span className="sd live-dot" /> {liveText}</span>
    : <span className="status idle"><span className="sd" /> {idleText}</span>;
}
function FieldLabel({ children }) { return <span className="cap" style={{ display: "block", marginBottom: 8 }}>{children}</span>; }
// Bare +/- glyphs for nudging a slider value by exactly 1. Styled INLINE on purpose: dashboard.php
// links /ui/styles.css without cache-busting while the JS bundle is content-hashed, so a class-based
// style can arrive after its markup and render as an unstyled browser button. Inline styles ship
// with the bundle. Kept deliberately plain - no box, border or fill - because these rows are flat.
const stepBtn = (disabled) => ({
  width: 20, height: 20, padding: 0, margin: 0, lineHeight: 1,
  border: "none", background: "none", outline: "none",
  fontFamily: "var(--font)", fontSize: 16, fontWeight: 500,
  color: "var(--ink-3)",
  opacity: disabled ? 0.3 : 1,
  cursor: disabled ? "default" : "pointer",
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  transition: "color .15s ease, opacity .15s ease",
  WebkitAppearance: "none", appearance: "none",
});

function SliderRow({ label, value, min, max, step = 1, onChange, fmt = v => v.toLocaleString() }) {
  // The slider jumps in `step` increments (10 / 50 / 100 ...), which is quick but coarse. These
  // nudge by exactly 1 so an exact figure is reachable, clamped to the slider's own bounds.
  // type="button" is required - one of these rows sits inside a native <form method="POST">
  // (the auto-start slot in dash-wired.jsx), where a default-type button submits the form.
  const lo = Number(min), hi = Number(max), cur = Number(value) || 0;
  const atMin = !isNaN(lo) && cur <= lo;
  const atMax = !isNaN(hi) && cur >= hi;
  // Click-to-type. `draft` holds the raw digits while editing; the formatted string is only for
  // display, so entering edit mode swaps "1,250" for "1250" and back again on commit.
  const [editing, setEditing] = useT(false);
  const [draft, setDraft] = useT("");
  const inputRef = useTR(null);
  const clamp = (n) => {
    if (!isNaN(lo)) n = Math.max(lo, n);
    if (!isNaN(hi)) n = Math.min(hi, n);
    return n;
  };
  const beginEdit = () => { setDraft(String(cur)); setEditing(true); };
  const commit = () => {
    const parsed = parseInt(String(draft).replace(/[^0-9-]/g, ""), 10);
    setEditing(false);
    if (isNaN(parsed)) return;            // junk or empty -> keep the current value
    const next = clamp(parsed);
    if (next !== cur && onChange) onChange(next);
  };
  const onKey = (e) => {
    if (e.key === "Enter") {
      // Never let this bubble to a surrounding <form> - it would submit and reload the page.
      e.preventDefault();
      e.stopPropagation();
      commit();
    } else if (e.key === "Escape") {
      e.preventDefault();
      setEditing(false);
    }
  };
  const nudge = (delta) => {
    let next = cur + delta;
    if (!isNaN(lo)) next = Math.max(lo, next);
    if (!isNaN(hi)) next = Math.min(hi, next);
    if (next !== cur && onChange) onChange(next);
  };
  const hover = (on, disabled) => (e) => {
    if (disabled) return;
    e.currentTarget.style.color = on ? "var(--ink)" : "var(--ink-3)";
  };
  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 9 }}>
        <span className="cap">{label}</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 11 }}>
          <button
            type="button" style={stepBtn(atMin)} disabled={atMin}
            onClick={() => nudge(-1)}
            onMouseEnter={hover(true, atMin)} onMouseLeave={hover(false, atMin)}
            aria-label={"Decrease " + label + " by one"} title="Decrease by 1"
          >{"\u2212"}</button>
          <span style={{
            display: "inline-flex", justifyContent: "flex-end",
            minWidth: (String(fmt(value)).length + 1) + "ch",
          }}>
            {editing ? (
              <input
                ref={inputRef}
                type="text" inputMode="numeric" autoFocus
                value={draft}
                onChange={e => setDraft(e.target.value)}
                onKeyDown={onKey}
                onBlur={commit}
                onFocus={e => e.target.select()}
                aria-label={"Type a value for " + label}
                style={{
                  width: Math.max(2, String(draft).length + 1) + "ch",
                  background: "none", border: "none", outline: "none",
                  padding: 0, margin: 0, textAlign: "right",
                  fontFamily: "var(--font)", fontSize: "inherit", fontWeight: 640,
                  color: "var(--accent)", fontVariantNumeric: "tabular-nums",
                }}
              />
            ) : (
              <span
                onClick={beginEdit}
                title="Click to type a value"
                style={{
                  fontWeight: 640, color: "var(--accent)", fontVariantNumeric: "tabular-nums",
                  cursor: "text", userSelect: "none",
                }}
              >{fmt(value)}</span>
            )}
          </span>
          <button
            type="button" style={stepBtn(atMax)} disabled={atMax}
            onClick={() => nudge(1)}
            onMouseEnter={hover(true, atMax)} onMouseLeave={hover(false, atMax)}
            aria-label={"Increase " + label + " by one"} title="Increase by 1"
          >+</button>
        </span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(+e.target.value)} style={{ width: "100%" }} />
    </div>
  );
}
const grid = (cols, gap = 14) => ({ display: "grid", gridTemplateColumns: `repeat(${cols},1fr)`, gap });

/* reusable min/max delay control (clamped so max >= min) used across every bot */
function DelayFields({ min, max, setMin, setMax, lo = 1, hi = 60, step = 1, unit = "s", label = "RESPONSE DELAY", loMin, hiMin, loMax, hiMax }) {
  // MIN and MAX may take asymmetric bounds (matches the original dashboard — e.g. the viewbot
  // MIN delay capped at 450 while MAX capped at 900). They fall back to the shared lo/hi.
  const lMin = loMin != null ? loMin : lo, hMin = hiMin != null ? hiMin : hi;
  const lMax = loMax != null ? loMax : lo, hMax = hiMax != null ? hiMax : hi;
  const onMin = (v) => { setMin(v); if (v > max) setMax(v); };
  const onMax = (v) => { setMax(v); if (v < min) setMin(v); };
  return (
    <div style={{ marginBottom: 4 }}>
      <FieldLabel>{label}</FieldLabel>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <SliderRow label="MIN" value={min} min={lMin} max={hMin} step={step} onChange={onMin} fmt={v => v + unit} />
        <SliderRow label="MAX" value={max} min={lMax} max={hMax} step={step} onChange={onMax} fmt={v => v + unit} />
      </div>
    </div>
  );
}
function ToggleRow_unused() { return null; }

/* ================= AUTO-START SLOTS (paid) ================= */
function AutoStartSlots() {
  const [enabled, setEnabled] = useT(true);
  const limit = 5; // Pro plan
  const [slots, setSlots] = useT([
    { id: "s1", channel: "kick.com/yourchannel", viewers: 1500, armed: true },
    { id: "s2", channel: "kick.com/secondary", viewers: 800, armed: true },
    { id: "s3", channel: "kick.com/altstream", viewers: 400, armed: false },
  ]);
  const add = () => {
    if (slots.length >= limit) return;
    setSlots(s => [...s, { id: Math.random().toString(36).slice(2), channel: "kick.com/", viewers: 500, armed: false }]);
  };
  const update = (id, patch) => setSlots(s => s.map(x => x.id === id ? { ...x, ...patch } : x));
  const remove = (id) => setSlots(s => s.filter(x => x.id !== id));
  const armedCount = slots.filter(s => s.armed).length;

  return (
    <Card strong>
      <PanelHead eyebrow="Viewer bot · automation" title="Auto-Start Slots"
        right={
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span className="cap" style={{ whiteSpace: "nowrap" }}>{enabled ? `${armedCount} armed` : "Paused"}</span>
            <Toggle on={enabled} onChange={setEnabled} />
          </div>
        } />
      <p className="body" style={{ fontSize: 13.5, marginTop: -6, marginBottom: 18, maxWidth: 640 }}>
        The moment KVB detects your channel goes live, every armed slot launches its viewers automatically — no manual start. Included on paid Viewbot plans.
      </p>

      <div className="stack" style={{ gap: 10, opacity: enabled ? 1 : 0.5, transition: "opacity .25s", pointerEvents: enabled ? "auto" : "none" }}>
        {slots.map((s, i) => (
          <div key={s.id} className="glass" style={{ borderRadius: 14, padding: "12px 14px", display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ width: 30, height: 30, borderRadius: 9, flexShrink: 0, display: "grid", placeItems: "center", background: s.armed ? "linear-gradient(160deg, var(--accent), var(--accent-deep))" : "color-mix(in oklch, white 5%, transparent)", color: s.armed ? "var(--accent-ink)" : "var(--ink-3)", border: s.armed ? "none" : "1px solid var(--glass-border)" }}>
              <DIcon name="zap" size={15} />
            </span>
            <div style={{ flex: "1 1 auto", minWidth: 0 }}>
              <DField icon="globe" value={s.channel} onChange={v => update(s.id, { channel: v })} />
            </div>
            <div style={{ flexShrink: 0, width: 132 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                <span className="cap" style={{ fontSize: 10.5 }}>VIEWERS</span>
                <span style={{ fontSize: 11.5, fontWeight: 640, color: "var(--accent)" }}>{s.viewers.toLocaleString()}</span>
              </div>
              <input type="range" min={50} max={5000} step={50} value={s.viewers} onChange={e => update(s.id, { viewers: +e.target.value })} style={{ width: "100%" }} />
            </div>
            <button onClick={() => update(s.id, { armed: !s.armed })} title={s.armed ? "Armed" : "Idle"} style={{ flexShrink: 0, background: "transparent", border: "none", padding: 0, cursor: "pointer", lineHeight: 0 }}>
              {s.armed
                ? <span className="status ok" style={{ cursor: "pointer" }}><span className="sd live-dot" /> Armed</span>
                : <span className="status idle" style={{ cursor: "pointer" }}><span className="sd" /> Idle</span>}
            </button>
            <button onClick={() => remove(s.id)} style={{ flexShrink: 0, width: 30, height: 30, borderRadius: 8, border: "1px solid var(--glass-border)", background: "transparent", color: "var(--ink-3)", cursor: "pointer", display: "grid", placeItems: "center" }}
              onMouseEnter={e => { e.currentTarget.style.color = "oklch(0.78 0.18 25)"; e.currentTarget.style.borderColor = "color-mix(in oklch, oklch(0.65 0.2 25) 40%, transparent)"; }}
              onMouseLeave={e => { e.currentTarget.style.color = "var(--ink-3)"; e.currentTarget.style.borderColor = "var(--glass-border)"; }}>✕</button>
          </div>
        ))}
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 16 }}>
        <button className="btn btn-ghost btn-sm" onClick={add} disabled={slots.length >= limit} style={{ opacity: slots.length >= limit ? 0.5 : 1 }}>
          <Icon name="bolt" size={14} /> Add slot
        </button>
        <span className="cap">{slots.length} / {limit} slots used · Pro plan</span>
      </div>
    </Card>
  );
}

/* ================= OVERVIEW ================= */
const ACTIVITY = [
  { icon: "zap", t: "Auto-start armed for kick.com/yourchannel", time: "2m" },
  { icon: "signal", t: "Viewer session hit a 1,312 peak", time: "14m" },
  { icon: "poll", t: "Poll \u201cWho takes the 1v1?\u201d launched", time: "31m" },
  { icon: "users", t: "+318 followers gained today", time: "1h" },
  { icon: "spark", t: "AI Chatbot replied to 420 messages", time: "2h" },
  { icon: "scissors", t: "Clip boost finished \u2014 +2,500 views", time: "3h" },
];
const SERVICES = [
  { name: "Viewer Bot", icon: "signal", val: "1,240 live", on: true, go: "Viewer Bot" },
  { name: "Ai Chatbot", icon: "spark", val: "180 / min", on: true, go: "Ai Chatbot" },
  { name: "Follow Bot", icon: "users", val: "+42 / min", on: true, go: "Follow Bot" },
  { name: "Poll Bot", icon: "poll", val: "Voting", on: true, go: "Poll Bot" },
  { name: "Clip Viewbot", icon: "scissors", val: "Idle", on: false, go: "Clip Viewbot" },
];

function OverviewScreen({ go }) {
  const [live, setLive] = useT(1240);
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div style={grid(4)} className="rg4">
        <StatTile label="Live viewers" value={live.toLocaleString()} icon="signal" accent />
        <StatTile label="Followers gained" value="+318" icon="users" />
        <StatTile label="Messages / min" value="180" icon="chat" />
        <StatTile label="Engine uptime" value="99.98%" icon="refresh" />
      </div>

      {/* chart + active services */}
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 14 }}>
        <Card strong>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 }}>
            <div>
              <div className="eyebrow" style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><span className="dot" /> Viewer bot · active</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginTop: 12 }}>
                <span style={{ fontSize: 40, fontWeight: 720, letterSpacing: "-0.04em", color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>{live.toLocaleString()}</span>
                <span className="cap">concurrent · kick.com/yourchannel</span>
              </div>
            </div>
            <Badge running liveText="Live" />
          </div>
          <ViewerViz running target={1240} onValue={setLive} height={150} />
          <div style={{ display: "flex", gap: 0, marginTop: 16, paddingTop: 16, borderTop: "1px solid var(--glass-border-soft)" }}>
            {[["Session peak", "1,312"], ["Delivery time", "28s"], ["Avg. watch", "2h 14m"]].map(([l, v], i) => (
              <div key={l} style={{ flex: 1, paddingLeft: i ? 18 : 0, borderLeft: i ? "1px solid var(--glass-border-soft)" : "none" }}>
                <div style={{ fontSize: 18, fontWeight: 680, letterSpacing: "-0.02em" }}>{v}</div>
                <div className="cap" style={{ marginTop: 3 }}>{l}</div>
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <PanelHead title="Active services" right={<span className="cap">4 running</span>} />
          <div className="stack" style={{ gap: 8 }}>
            {SERVICES.map(s => (
              <div key={s.name} onClick={() => go(s.go)} className="tile" style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 12px", borderRadius: 12, cursor: "pointer", border: "1px solid var(--glass-border-soft)", background: "color-mix(in oklch, white 3%, transparent)" }}>
                <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: "grid", placeItems: "center", background: s.on ? "color-mix(in oklch, var(--accent) 14%, transparent)" : "color-mix(in oklch, white 4%, transparent)", border: s.on ? "1px solid color-mix(in oklch, var(--accent) 30%, transparent)" : "1px solid var(--glass-border)", color: s.on ? "var(--accent)" : "var(--ink-3)" }}><DIcon name={s.icon} size={16} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 540 }}>{s.name}</div>
                  <div className="cap" style={{ fontSize: 11.5 }}>{s.val}</div>
                </div>
                {s.on ? <span className="status ok" style={{ flexShrink: 0 }}><span className="sd live-dot" /> On</span> : <span className="status idle" style={{ flexShrink: 0 }}><span className="sd" /> Off</span>}
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* recent activity + quick launch */}
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 14 }}>
        <Card>
          <PanelHead title="Recent activity" right={<span className="cap">Last 3 hours</span>} />
          <div className="stack" style={{ gap: 2 }}>
            {ACTIVITY.map((a, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 13, padding: "11px 0", borderBottom: i < ACTIVITY.length - 1 ? "1px solid var(--glass-border-soft)" : "none" }}>
                <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: "grid", placeItems: "center", background: "color-mix(in oklch, var(--accent) 11%, transparent)", color: "var(--accent)" }}><DIcon name={a.icon} size={15} /></span>
                <span style={{ flex: 1, fontSize: 13.5, color: "var(--ink-2)" }}>{a.t}</span>
                <span className="cap" style={{ flexShrink: 0, fontSize: 11.5 }}>{a.time}</span>
              </div>
            ))}
          </div>
        </Card>

        <div className="stack" style={{ gap: 14 }}>
          <Card>
            <PanelHead title="Quick launch" />
            <div style={grid(2, 10)}>
              {[["Viewer Bot", "signal"], ["Chat Bot", "chat"], ["Poll Bot", "poll"], ["Clip Viewbot", "scissors"]].map(([t, ic]) => (
                <div key={t} onClick={() => go(t)} className="tile" style={{ padding: 14, borderRadius: 12, cursor: "pointer", border: "1px solid var(--glass-border-soft)", background: "color-mix(in oklch, white 3%, transparent)" }}>
                  <span style={{ color: "var(--accent)", display: "inline-flex", marginBottom: 10 }}><DIcon name={ic} size={18} /></span>
                  <div style={{ fontSize: 13, fontWeight: 540 }}>{t}</div>
                </div>
              ))}
            </div>
          </Card>
          <Card>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
              <span style={{ fontWeight: 600, fontSize: 14 }}>Pro plan credits</span>
              <span className="cap">1,420 / 1,800</span>
            </div>
            <div style={{ height: 8, borderRadius: 99, background: "var(--glass-border)", overflow: "hidden" }}>
              <div style={{ width: "79%", height: "100%", background: "linear-gradient(90deg, var(--accent), var(--accent-deep))" }} />
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => go("Billing")} style={{ width: "100%", justifyContent: "center", marginTop: 14 }}>Manage billing</button>
          </Card>
        </div>
      </div>
    </div>
  );
}

/* ================= VIEWER BOT ================= */
const C_CONNECTING = "oklch(0.80 0.135 215)";
const C_ERRORS = "oklch(0.83 0.155 82)";
const C_DEAD = "oklch(0.66 0.20 22)";
const CONN_LEGEND = [
  ["connecting", "Connecting", C_CONNECTING],
  ["connected", "Connected", "var(--accent)"],
  ["errors", "Errors", C_ERRORS],
  ["dead", "Dead", C_DEAD],
];
function ConnStatTile({ label, value, dot, accent }) {
  return (
    <div className="glass" style={{ padding: 18, borderRadius: "var(--radius-sm)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
        <span className="cap" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
        <span style={{ width: 9, height: 9, borderRadius: "50%", background: dot, boxShadow: `0 0 8px ${dot}` }} />
      </div>
      <div style={{ fontSize: 27, fontWeight: 680, letterSpacing: "-0.03em", fontVariantNumeric: "tabular-nums", color: accent ? dot : "var(--ink)" }}>{value}</div>
    </div>
  );
}
function ViewerBotScreen() {
  const [running, setRunning] = useT(true);
  const [url, setUrl] = useT("kick.com/yourchannel");
  const [target, setTarget] = useT(1240);
  const [minDelay, setMinDelay] = useT(5);
  const [maxDelay, setMaxDelay] = useT(30);
  const [dynamic, setDynamic] = useT(true);
  const [stats, setStats] = useT({ connected: 1040, connecting: 150, errors: 52, dead: 90 });
  const z = running ? stats : { connected: 0, connecting: 0, errors: 0, dead: 0 };
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div style={grid(4)} className="rg4">
        <ConnStatTile label="Connecting" value={z.connecting.toLocaleString()} dot={C_CONNECTING} accent />
        <ConnStatTile label="Connected" value={z.connected.toLocaleString()} dot="var(--accent)" accent />
        <ConnStatTile label="Errors" value={z.errors.toLocaleString()} dot={C_ERRORS} accent />
        <ConnStatTile label="Dead connections" value={z.dead.toLocaleString()} dot={C_DEAD} accent />
      </div>
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 14 }}>
        <Card strong>
          <PanelHead eyebrow="Viewer bot" title="Launch session" />
          <FieldLabel>STREAM URL</FieldLabel>
          <div style={{ marginBottom: 18 }}><DField icon="globe" value={url} onChange={setUrl} /></div>
          <SliderRow label="VIEWERS" value={target} min={50} max={5000} step={50} onChange={setTarget} />
          <DelayFields label="JOIN DELAY (per viewer)" min={minDelay} max={maxDelay} setMin={setMinDelay} setMax={setMaxDelay} lo={1} hi={120} unit="s" />
          <div style={{ marginBottom: 16 }}><ToggleRow label="Dynamic viewers" sub="Naturally fluctuate the count up & down so it looks organic" on={dynamic} onChange={setDynamic} last /></div>
          <button className={running ? "btn btn-ghost" : "btn btn-primary"} onClick={() => setRunning(r => !r)} style={{ width: "100%", justifyContent: "center" }}>
            {running ? "Stop session" : <><Icon name="play" size={15} fill /> Launch session</>}
          </button>
          <div style={{ marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--glass-border-soft)", display: "flex", justifyContent: "space-between" }}>
            {[["Session peak", "1,312"], ["Delivery time", "28s"], ["Avg. watch", "2h 14m"]].map(([l, v], i) => (
              <div key={l} style={{ paddingLeft: i ? 14 : 0, borderLeft: i ? "1px solid var(--glass-border-soft)" : "none", flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 680, letterSpacing: "-0.02em" }}>{v}</div>
                <div className="cap" style={{ fontSize: 10.5, marginTop: 2 }}>{l}</div>
              </div>
            ))}
          </div>
        </Card>
        <Card style={{ display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
            <div>
              <div className="cap">CONNECTIONS — LIVE</div>
              <div style={{ fontSize: 44, fontWeight: 720, letterSpacing: "-0.04em", color: running ? "var(--accent)" : "var(--ink-3)", fontVariantNumeric: "tabular-nums" }}>{z.connected.toLocaleString()}</div>
            </div>
            <Badge running={running} liveText="Ramping" />
          </div>
          <ConnectionViz running={running} target={target} onStats={setStats} height={264} />
          <div style={{ display: "flex", gap: 16, flexWrap: "wrap", marginTop: 16 }}>
            {CONN_LEGEND.map(([k, lbl, col]) => (
              <div key={k} style={{ display: "flex", alignItems: "center", gap: 7 }}>
                <span style={{ width: 9, height: 9, borderRadius: 3, background: col }} />
                <span className="cap" style={{ fontSize: 11.5 }}>{lbl}</span>
                <span style={{ fontSize: 12.5, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{z[k].toLocaleString()}</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: "auto", paddingTop: 18, display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
            {[
              ["Fill rate", running ? Math.round(z.connected / target * 100) + "%" : "0%"],
              ["Success rate", running ? Math.round(z.connected / Math.max(1, z.connected + z.errors + z.dead) * 100) + "%" : "—"],
              ["Mode", dynamic ? "Dynamic" : "Steady"],
            ].map(([l, v], i) => (
              <div key={l} style={{ paddingLeft: i ? 14 : 0, borderLeft: i ? "1px solid var(--glass-border-soft)" : "none" }}>
                <div style={{ fontSize: 18, fontWeight: 680, letterSpacing: "-0.02em", color: i < 2 ? "var(--accent)" : "var(--ink)" }}>{v}</div>
                <div className="cap" style={{ fontSize: 10.5, marginTop: 2 }}>{l}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>
      <AutoStartSlots />
    </div>
  );
}

/* ================= CHAT BOT ================= */
function ChatBotScreen() {
  const [running, setRunning] = useT(true);
  const [channel, setChannel] = useT("kick.com/yourchannel");
  const [rate, setRate] = useT(180);
  const [tone, setTone] = useT("Hype");
  const [emotes, setEmotes] = useT(true);
  const [minDelay, setMinDelay] = useT(2);
  const [maxDelay, setMaxDelay] = useT(12);
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div style={grid(4)} className="rg4">
        <StatTile label="Messages / min" value={running ? rate : 0} icon="chat" accent />
        <StatTile label="Sent today" value="24,901" icon="signal" />
        <StatTile label="Active chatters" value="146" icon="users" />
        <StatTile label="Tone" value={tone} icon="spark" />
      </div>
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 14 }}>
        <Card strong>
          <PanelHead eyebrow="Chat bot" title="Configure chat" />
          <FieldLabel>CHANNEL</FieldLabel>
          <div style={{ marginBottom: 18 }}><DField icon="chat" value={channel} onChange={setChannel} /></div>
          <SliderRow label="MESSAGES / MIN" value={rate} min={20} max={600} step={10} onChange={setRate} />
          <DelayFields label="DELAY BETWEEN MESSAGES" min={minDelay} max={maxDelay} setMin={setMinDelay} setMax={setMaxDelay} lo={1} hi={60} unit="s" />
          <FieldLabel>PERSONALITY</FieldLabel>
          <div style={{ marginBottom: 18 }}><Seg value={tone} options={["Hype", "Casual", "Support"]} onChange={setTone} /></div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 22 }}>
            <span className="body" style={{ fontSize: 14, color: "var(--ink)" }}>Use emotes &amp; reactions</span>
            <Toggle on={emotes} onChange={setEmotes} />
          </div>
          <button className={running ? "btn btn-ghost" : "btn btn-primary"} onClick={() => setRunning(r => !r)} style={{ width: "100%", justifyContent: "center" }}>
            {running ? "Pause chat" : <><Icon name="play" size={15} fill /> Start chatting</>}
          </button>
        </Card>
        <Card style={{ display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <div className="cap">LIVE CHAT FEED</div>
            <Badge running={running} liveText="Streaming" />
          </div>
          <ChatViz running={running} rate={rate} height={248} />
        </Card>
      </div>
      <ChatExtras />
    </div>
  );
}

/* ================= FOLLOW BOT ================= */
function FollowBotScreen() {
  const [running, setRunning] = useT(true);
  const [channel, setChannel] = useT("kick.com/yourchannel");
  const [rate, setRate] = useT(42);
  const [drip, setDrip] = useT(true);
  const [minDelay, setMinDelay] = useT(3);
  const [maxDelay, setMaxDelay] = useT(20);
  const [total, setTotal] = useT(12840);
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div style={grid(4)} className="rg4">
        <StatTile label="Total followers" value={total.toLocaleString()} icon="users" accent />
        <StatTile label="Gained today" value="+318" icon="chart" />
        <StatTile label="Rate / min" value={running ? rate : 0} icon="bolt" />
        <StatTile label="Retention" value="97.2%" icon="shield" />
      </div>
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 14 }}>
        <Card strong>
          <PanelHead eyebrow="Follow bot" title="Grow followers" />
          <FieldLabel>CHANNEL</FieldLabel>
          <div style={{ marginBottom: 18 }}><DField icon="users" value={channel} onChange={setChannel} /></div>
          <SliderRow label="FOLLOWERS / MIN" value={rate} min={5} max={200} step={1} onChange={setRate} />
          <DelayFields label="DELAY BETWEEN FOLLOWS" min={minDelay} max={maxDelay} setMin={setMinDelay} setMax={setMaxDelay} lo={1} hi={60} unit="s" />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <span className="body" style={{ fontSize: 14, color: "var(--ink)" }}>Natural drip pacing</span>
            <Toggle on={drip} onChange={setDrip} />
          </div>
          <p className="cap" style={{ lineHeight: 1.5, marginBottom: 22 }}>Spreads follows organically so growth never looks artificial.</p>
          <button className={running ? "btn btn-ghost" : "btn btn-primary"} onClick={() => setRunning(r => !r)} style={{ width: "100%", justifyContent: "center" }}>
            {running ? "Stop growth" : <><Icon name="play" size={15} fill /> Start growth</>}
          </button>
        </Card>
        <Card>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
            <div>
              <div className="cap">FOLLOWERS — CUMULATIVE</div>
              <div style={{ fontSize: 44, fontWeight: 720, letterSpacing: "-0.04em", color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>{total.toLocaleString()}</div>
            </div>
            <Badge running={running} liveText="Growing" />
          </div>
          <FollowViz running={running} rate={rate} total0={total} onTotal={setTotal} height={248} />
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12 }}>{["18m ago", "12m", "6m", "now"].map(t => <span key={t} className="cap" style={{ fontSize: 11 }}>{t}</span>)}</div>
        </Card>
      </div>
      <FollowExtras />
    </div>
  );
}

/* ================= AI CHATBOT ================= */
const AI_QA = [
  { q: "yo is this guy actually cracked?", a: "He's been grinding ranked all week — the aim's no accident 👀 stick around for the clutch." },
  { q: "what sens does he use", a: "Running 800 DPI · 0.45 in-game. Full settings are pinned in the panel below!" },
  { q: "how long is stream today", a: "We're live for ~4 hours today — big tournament warmups, then customs at 9pm 🔥" },
  { q: "first time here, what do we play", a: "Welcome in! Mostly FPS ranked + viewer games on weekends. Glad you made it 🙌" },
  { q: "drop a follow?", a: "Appreciate the love! Hit follow so you don't miss the next insane clip 💚" },
];
function AiChatbotScreen() {
  const [running, setRunning] = useT(true);
  const [channel, setChannel] = useT("kick.com/yourchannel");
  const [creativity, setCreativity] = useT(70);
  const [model, setModel] = useT("Balanced");
  const [mentions, setMentions] = useT(true);
  const [minDelay, setMinDelay] = useT(1);
  const [maxDelay, setMaxDelay] = useT(6);
  const feedRef = useTR(null);
  const [items, setItems] = useT(() => AI_QA.slice(0, 2).map((x, i) => ({ ...x, id: i })));
  const idc = useTR(100);
  useTE(() => {
    if (!running) return;
    const id = setInterval(() => {
      const qa = AI_QA[(Math.random() * AI_QA.length) | 0];
      setItems(s => [...s.slice(-5), { ...qa, id: idc.current++ }]);
    }, 2800);
    return () => clearInterval(id);
  }, [running]);
  useTE(() => { const el = feedRef.current; if (el) el.scrollTop = el.scrollHeight; }, [items]);
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div style={grid(4)} className="rg4">
        <StatTile label="AI replies sent" value="9,420" icon="spark" accent />
        <StatTile label="Avg. response" value="0.8s" icon="bolt" />
        <StatTile label="Model" value={model} icon="cpu" />
        <StatTile label="Engagement" value="+34%" icon="chart" />
      </div>
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 14 }}>
        <Card strong>
          <PanelHead eyebrow="Ai Chatbot" title="Configure AI" />
          <FieldLabel>CHANNEL</FieldLabel>
          <div style={{ marginBottom: 18 }}><DField icon="spark" value={channel} onChange={setChannel} /></div>
          <FieldLabel>MODEL</FieldLabel>
          <div style={{ marginBottom: 18 }}><Seg value={model} options={["Fast", "Balanced", "Smart"]} onChange={setModel} /></div>
          <SliderRow label="CREATIVITY" value={creativity} min={0} max={100} onChange={setCreativity} fmt={v => v + "%"} />
          <DelayFields label="REPLY DELAY" min={minDelay} max={maxDelay} setMin={setMinDelay} setMax={setMaxDelay} lo={0} hi={30} unit="s" />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 22 }}>
            <span className="body" style={{ fontSize: 14, color: "var(--ink)" }}>Reply to @mentions</span>
            <Toggle on={mentions} onChange={setMentions} />
          </div>
          <button className={running ? "btn btn-ghost" : "btn btn-primary"} onClick={() => setRunning(r => !r)} style={{ width: "100%", justifyContent: "center" }}>
            {running ? "Pause AI" : <><Icon name="play" size={15} fill /> Start AI</>}
          </button>
        </Card>
        <Card>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <div className="cap">AI CONVERSATION</div>
            <Badge running={running} liveText="Responding" />
          </div>
          <div ref={feedRef} className="feed" style={{ height: 290, overflowY: "auto", display: "flex", flexDirection: "column", gap: 12, paddingRight: 4 }}>
            {items.map(it => (
              <div key={it.id} className="stack" style={{ gap: 8 }}>
                <div style={{ alignSelf: "flex-start", maxWidth: "82%", background: "color-mix(in oklch, white 5%, transparent)", border: "1px solid var(--glass-border-soft)", borderRadius: "12px 12px 12px 3px", padding: "9px 13px", fontSize: 13 }}>
                  <span style={{ color: "var(--ink-3)", fontSize: 11.5, display: "block", marginBottom: 2 }}>viewer</span>
                  <span style={{ color: "var(--ink-2)" }}>{it.q}</span>
                </div>
                <div style={{ alignSelf: "flex-end", maxWidth: "86%", background: "color-mix(in oklch, var(--accent) 14%, transparent)", border: "1px solid color-mix(in oklch, var(--accent) 28%, transparent)", borderRadius: "12px 12px 3px 12px", padding: "9px 13px", fontSize: 13 }}>
                  <span style={{ color: "var(--accent)", fontSize: 11.5, display: "flex", alignItems: "center", gap: 5, marginBottom: 2, fontWeight: 600 }}><Icon name="spark" size={11} /> KVB AI</span>
                  <span style={{ color: "var(--ink)" }}>{it.a}</span>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
      <AiExtras />
    </div>
  );
}

/* ================= POLL BOT ================= */
function PollVizBars({ running, options }) {
  const [vals, setVals] = useT(() => options.map(o => o.base));
  useTE(() => {
    if (!running) return;
    const id = setInterval(() => {
      setVals(vs => vs.map((v, i) => Math.max(3, v + (options[i].lean + (Math.random() - 0.5) * 6))));
    }, 650);
    return () => clearInterval(id);
  }, [running]);
  const sum = vals.reduce((a, b) => a + b, 0) || 1;
  const lead = vals.indexOf(Math.max(...vals));
  return (
    <div className="stack" style={{ gap: 16 }}>
      {options.map((o, i) => {
        const pct = Math.round(vals[i] / sum * 100);
        const on = i === lead;
        return (
          <div key={o.label}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 7 }}>
              <span style={{ fontSize: 13.5, fontWeight: on ? 640 : 500, color: on ? "var(--ink)" : "var(--ink-2)" }}>{o.label}</span>
              <span style={{ fontSize: 13.5, fontWeight: 640, color: on ? "var(--accent)" : "var(--ink-3)", fontVariantNumeric: "tabular-nums" }}>{pct}%</span>
            </div>
            <div style={{ height: 12, borderRadius: 99, background: "color-mix(in oklch, black 30%, transparent)", overflow: "hidden", border: "1px solid var(--glass-border-soft)" }}>
              <div style={{ width: pct + "%", height: "100%", borderRadius: 99, transition: "width .6s cubic-bezier(.2,.7,.3,1)", background: on ? "linear-gradient(90deg, var(--accent), var(--accent-deep))" : "color-mix(in oklch, var(--accent) 30%, transparent)", boxShadow: on ? "0 0 16px -2px var(--accent-glow)" : "none" }} />
            </div>
          </div>
        );
      })}
    </div>
  );
}
function PollbotScreen() {
  const [running, setRunning] = useT(true);
  const [channel, setChannel] = useT("kick.com/yourchannel");
  const [question, setQuestion] = useT("Who takes the 1v1?");
  const [rate, setRate] = useT(120);
  const [lean, setLean] = useT("Option A");
  const [minDelay, setMinDelay] = useT(1);
  const [maxDelay, setMaxDelay] = useT(8);
  const options = [
    { label: "Streamer wins", base: 58, lean: lean === "Option A" ? 2.4 : 0.4 },
    { label: "Chat's champion", base: 30, lean: lean === "Option B" ? 2.4 : 0.4 },
    { label: "It's a draw", base: 12, lean: 0.2 },
  ];
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div style={grid(4)} className="rg4">
        <StatTile label="Votes / min" value={running ? rate : 0} icon="poll" accent />
        <StatTile label="Polls run" value="284" icon="chart" />
        <StatTile label="Total votes" value="61,907" icon="users" />
        <StatTile label="Win rate" value="96%" icon="check" />
      </div>
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 14 }}>
        <Card strong>
          <PanelHead eyebrow="Poll bot" title="Run a poll" />
          <FieldLabel>CHANNEL</FieldLabel>
          <div style={{ marginBottom: 18 }}><DField icon="globe" value={channel} onChange={setChannel} /></div>
          <FieldLabel>QUESTION</FieldLabel>
          <div style={{ marginBottom: 18 }}><DField icon="poll" value={question} onChange={setQuestion} mono={false} /></div>
          <SliderRow label="VOTES / MIN" value={rate} min={10} max={500} step={10} onChange={setRate} />
          <DelayFields label="DELAY BETWEEN VOTES" min={minDelay} max={maxDelay} setMin={setMinDelay} setMax={setMaxDelay} lo={0} hi={30} unit="s" />
          <FieldLabel>BOOST OPTION</FieldLabel>
          <div style={{ marginBottom: 22 }}><Seg value={lean} options={["Option A", "Option B", "Even"]} onChange={setLean} /></div>
          <button className={running ? "btn btn-ghost" : "btn btn-primary"} onClick={() => setRunning(r => !r)} style={{ width: "100%", justifyContent: "center" }}>
            {running ? "Stop poll" : <><Icon name="play" size={15} fill /> Start poll</>}
          </button>
        </Card>
        <Card>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
            <div className="cap">LIVE POLL</div>
            <Badge running={running} liveText="Voting" />
          </div>
          <div className="h3" style={{ fontSize: 18, margin: "4px 0 22px" }}>{question}</div>
          <PollVizBars running={running} options={options} />
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 22, paddingTop: 16, borderTop: "1px solid var(--glass-border-soft)" }}>
            <span style={{ color: "var(--accent)" }}><Icon name="users" size={15} /></span>
            <span className="cap">{running ? "Votes streaming in from distributed accounts" : "Poll paused"}</span>
          </div>
        </Card>
      </div>
      <PollExtras />
    </div>
  );
}

/* ================= CLIP VIEWBOT ================= */
const CLIP_TITLES = ["Insane 1v5 clutch", "He did NOT just hit that", "Chat went crazy 😳", "Fastest ace this season", "Reverse sweep highlight"];
function ClipViewbotScreen() {
  const [running, setRunning] = useT(true);
  const [clipUrl, setClipUrl] = useT("kick.com/yourchannel?clip=8f3a2");
  const [target, setTarget] = useT(2500);
  const [drip, setDrip] = useT(true);
  const [minDelay, setMinDelay] = useT(2);
  const [maxDelay, setMaxDelay] = useT(15);
  const [views, setViews] = useT(0);
  const clipsRef = useTR(null);
  if (!clipsRef.current) clipsRef.current = CLIP_TITLES.slice(0, 4).map((t, i) => ({ id: i, t, v: 1200 + i * 640, done: i === 3 }));
  const [clips, setClips] = useT(clipsRef.current);
  useTE(() => {
    if (!running) return;
    const id = setInterval(() => {
      setClips(cs => cs.map(c => c.done ? c : { ...c, v: c.v + ((Math.random() * 40) | 0) }));
    }, 500);
    return () => clearInterval(id);
  }, [running]);
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div style={grid(4)} className="rg4">
        <StatTile label="Views / min" value={running ? target.toLocaleString() : "0"} icon="signal" accent />
        <StatTile label="Clips boosted" value="48" icon="scissors" />
        <StatTile label="Views added" value="312K" icon="eye" />
        <StatTile label="Avg. completion" value="91%" icon="gauge" />
      </div>
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 14 }}>
        <Card strong>
          <PanelHead eyebrow="Clip viewbot" title="Boost a clip" />
          <FieldLabel>CLIP URL</FieldLabel>
          <div style={{ marginBottom: 18 }}><DField icon="scissors" value={clipUrl} onChange={setClipUrl} /></div>
          <SliderRow label="TARGET VIEWS" value={target} min={100} max={20000} step={100} onChange={setTarget} />
          <DelayFields label="DELAY BETWEEN VIEWS" min={minDelay} max={maxDelay} setMin={setMinDelay} setMax={setMaxDelay} lo={1} hi={60} unit="s" />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <span className="body" style={{ fontSize: 14, color: "var(--ink)" }}>Natural drip pacing</span>
            <Toggle on={drip} onChange={setDrip} />
          </div>
          <p className="cap" style={{ lineHeight: 1.5, marginBottom: 22 }}>Spreads views gradually so clips climb the algorithm naturally.</p>
          <button className={running ? "btn btn-ghost" : "btn btn-primary"} onClick={() => setRunning(r => !r)} style={{ width: "100%", justifyContent: "center" }}>
            {running ? "Stop boost" : <><Icon name="play" size={15} fill /> Boost clip</>}
          </button>
        </Card>
        <Card>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
            <div>
              <div className="cap">VIEWS DELIVERED / MIN</div>
              <div style={{ fontSize: 40, fontWeight: 720, letterSpacing: "-0.035em", color: running ? "var(--accent)" : "var(--ink-3)", fontVariantNumeric: "tabular-nums" }}>{running ? views.toLocaleString() : "0"}</div>
            </div>
            <Badge running={running} liveText="Boosting" />
          </div>
          <ViewerViz running={running} target={target} onValue={setViews} height={150} />
          <div className="stack" style={{ gap: 8, marginTop: 18 }}>
            {clips.map(c => (
              <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: 11, background: "color-mix(in oklch, white 3%, transparent)", border: "1px solid var(--glass-border-soft)" }}>
                <span style={{ width: 28, height: 28, borderRadius: 7, flexShrink: 0, display: "grid", placeItems: "center", background: "color-mix(in oklch, var(--accent) 12%, transparent)", color: "var(--accent)" }}><Icon name="play" size={12} fill /></span>
                <span style={{ flex: 1, fontSize: 13, color: "var(--ink-2)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.t}</span>
                <span className="mono" style={{ fontSize: 12.5, color: "var(--ink)" }}>{c.v.toLocaleString()}</span>
                {c.done
                  ? <span className="status ok" style={{ flexShrink: 0 }}><span className="sd" /> Done</span>
                  : <span className="status warn" style={{ flexShrink: 0 }}><span className="sd live-dot" /> Live</span>}
              </div>
            ))}
          </div>
        </Card>
      </div>
      <ClipExtras />
    </div>
  );
}

/* ================= bottom panels (fill out each bot page) ================= */
function ToggleRow({ label, sub, on, onChange, last }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, padding: "12px 0", borderBottom: last ? "none" : "1px solid var(--glass-border-soft)" }}>
      <div><div style={{ fontSize: 13.5, fontWeight: 540 }}>{label}</div>{sub && <div className="cap" style={{ marginTop: 2, fontSize: 11.5 }}>{sub}</div>}</div>
      <Toggle on={on} onChange={onChange} />
    </div>
  );
}
function Chip({ children }) {
  return <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: 999, background: "color-mix(in oklch, white 5%, transparent)", border: "1px solid var(--glass-border-soft)", fontSize: 12, color: "var(--ink-2)" }}>{children} <span style={{ color: "var(--ink-3)", cursor: "pointer" }}>✕</span></span>;
}

function ChatExtras() {
  const [packs, setPacks] = useT({ hype: true, emotes: true, questions: true, raid: false, compliments: true });
  const tog = k => setPacks(p => ({ ...p, [k]: !p[k] }));
  const triggers = [["!discord", "Join the fam → discord.gg/kvb 💚"], ["!sens", "800 DPI · 0.45 in-game"], ["raid", "Welcome raiders! Make yourselves at home 🔥"], ["!socials", "All links pinned below the stream!"]];
  return (
    <Card>
      <PanelHead title="Message packs & triggers" right={<span className="cap">4 active</span>} />
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 28 }}>
        <div>
          <div className="cap" style={{ marginBottom: 4 }}>ACTIVE PACKS</div>
          <ToggleRow label="Hype reactions" sub="W's, let's go, clip it" on={packs.hype} onChange={() => tog("hype")} />
          <ToggleRow label="Emote spam" sub="KEKW, POG, 🔥" on={packs.emotes} onChange={() => tog("emotes")} />
          <ToggleRow label="Questions" sub="Keeps chat curious" on={packs.questions} onChange={() => tog("questions")} />
          <ToggleRow label="Raid shoutouts" sub="Welcomes incoming raids" on={packs.raid} onChange={() => tog("raid")} />
          <ToggleRow label="Compliments" sub="Gasses up the streamer" on={packs.compliments} onChange={() => tog("compliments")} last />
        </div>
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
            <span className="cap">AUTO-REPLY TRIGGERS</span>
            <button className="btn btn-ghost btn-sm"><Icon name="bolt" size={13} /> Add</button>
          </div>
          <div className="stack" style={{ gap: 8 }}>
            {triggers.map(([k, v]) => (
              <div key={k} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: 11, background: "color-mix(in oklch, white 3%, transparent)", border: "1px solid var(--glass-border-soft)" }}>
                <span className="mono" style={{ flexShrink: 0, color: "var(--accent)", fontSize: 12.5, minWidth: 76 }}>{k}</span>
                <span style={{ color: "var(--ink-3)" }}>→</span>
                <span style={{ flex: 1, fontSize: 13, color: "var(--ink-2)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Card>
  );
}

function AiExtras() {
  const [beh, setBeh] = useT({ safe: true, mod: true, qonly: false, ctx: true });
  const tog = k => setBeh(b => ({ ...b, [k]: !b[k] }));
  const facts = ["Streams FPS ranked + viewer games on weekends", "Sensitivity: 800 DPI · 0.45 in-game", "Live Mon–Fri from 6pm ET", "Community: discord.gg/kvb"];
  return (
    <Card>
      <PanelHead title="Knowledge & behavior" right={<span className="cap">Smart model</span>} />
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 28 }}>
        <div>
          <div className="cap" style={{ marginBottom: 10 }}>KNOWLEDGE BASE</div>
          <div className="stack" style={{ gap: 8, marginBottom: 12 }}>
            {facts.map((f, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", borderRadius: 11, background: "color-mix(in oklch, white 3%, transparent)", border: "1px solid var(--glass-border-soft)" }}>
                <span style={{ color: "var(--accent)", flexShrink: 0 }}><Icon name="spark" size={14} /></span>
                <span style={{ flex: 1, fontSize: 13, color: "var(--ink-2)" }}>{f}</span>
              </div>
            ))}
          </div>
          <DField icon="code" value="" onChange={() => {}} placeholder="Add a fact or link the AI should know…" mono={false} />
        </div>
        <div>
          <div className="cap" style={{ marginBottom: 4 }}>BEHAVIOR</div>
          <ToggleRow label="Safe mode" sub="Family-friendly replies" on={beh.safe} onChange={() => tog("safe")} />
          <ToggleRow label="Auto-moderate chat" sub="Hides spam & scams" on={beh.mod} onChange={() => tog("mod")} />
          <ToggleRow label="Only reply to questions" on={beh.qonly} onChange={() => tog("qonly")} />
          <ToggleRow label="Use live stream context" on={beh.ctx} onChange={() => tog("ctx")} last />
          <div className="cap" style={{ margin: "16px 0 9px" }}>BANNED WORDS</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {["scam", "free vbucks", "dm me", "giveaway"].map(w => <Chip key={w}>{w}</Chip>)}
          </div>
        </div>
      </div>
    </Card>
  );
}

function PollExtras() {
  const templates = ["Who takes the 1v1?", "What game next?", "Rate that play /10", "Should I run it back?", "Pick my loadout"];
  const history = [["Best moment today?", "4,182", "Clip #3", "12m"], ["Face cam on?", "2,933", "Yes", "48m"], ["Next ranked or chill?", "5,401", "Ranked", "2h"]];
  return (
    <Card>
      <PanelHead title="Templates & history" />
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 28 }}>
        <div>
          <div className="cap" style={{ marginBottom: 10 }}>SAVED TEMPLATES</div>
          <div className="stack" style={{ gap: 8 }}>
            {templates.map(t => (
              <div key={t} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 9px 9px 13px", borderRadius: 11, background: "color-mix(in oklch, white 3%, transparent)", border: "1px solid var(--glass-border-soft)" }}>
                <span style={{ color: "var(--accent)", flexShrink: 0 }}><Icon name="poll" size={14} /></span>
                <span style={{ flex: 1, fontSize: 13, color: "var(--ink-2)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t}</span>
                <button className="btn btn-ghost btn-sm" style={{ flexShrink: 0 }}>Launch</button>
              </div>
            ))}
          </div>
        </div>
        <div>
          <div className="cap" style={{ marginBottom: 10 }}>RECENT POLLS</div>
          <table className="dtable">
            <thead><tr><th>Question</th><th>Votes</th><th>Winner</th><th>When</th></tr></thead>
            <tbody>
              {history.map((r, i) => (
                <tr key={i}><td style={{ color: "var(--ink)" }}>{r[0]}</td><td className="mono">{r[1]}</td><td><span style={{ color: "var(--accent)" }}>{r[2]}</span></td><td>{r[3]}</td></tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </Card>
  );
}

function FollowExtras() {
  const [days, setDays] = useT({ M: true, T: true, W: true, Th: true, F: true, Sa: false, Su: false });
  const milestones = [["10,000 followers", 1, "Reached"], ["20,000 followers", 12840 / 20000, "12,840 / 20,000"], ["50,000 followers", 12840 / 50000, "12,840 / 50,000"]];
  return (
    <Card>
      <PanelHead title="Schedule & milestones" />
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 28 }}>
        <div>
          <div className="cap" style={{ marginBottom: 10 }}>WEEKLY SCHEDULE</div>
          <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
            {Object.keys(days).map(d => (
              <button key={d} onClick={() => setDays(s => ({ ...s, [d]: !s[d] }))} style={{
                width: 42, height: 42, borderRadius: 12, border: "1px solid " + (days[d] ? "transparent" : "var(--glass-border)"), cursor: "pointer", fontSize: 13, fontWeight: 600,
                background: days[d] ? "linear-gradient(160deg, var(--accent), var(--accent-deep))" : "transparent",
                color: days[d] ? "var(--accent-ink)" : "var(--ink-3)",
              }}>{d}</button>
            ))}
          </div>
          <p className="cap" style={{ lineHeight: 1.5 }}>Drips ≈ 300 follows/day on active days, paced naturally across each session.</p>
        </div>
        <div>
          <div className="cap" style={{ marginBottom: 14 }}>MILESTONES</div>
          <div className="stack" style={{ gap: 16 }}>
            {milestones.map(([label, frac, note]) => (
              <div key={label}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 7 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 540 }}>{label}</span>
                  <span className="cap" style={{ color: frac >= 1 ? "var(--accent)" : "var(--ink-3)" }}>{note}</span>
                </div>
                <div style={{ height: 8, borderRadius: 99, background: "var(--glass-border)", overflow: "hidden" }}>
                  <div style={{ width: Math.min(100, frac * 100) + "%", height: "100%", background: "linear-gradient(90deg, var(--accent), var(--accent-deep))" }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Card>
  );
}

function ClipExtras() {
  const queue = [["Insane 1v5 clutch", "2,500", "2,500", "done"], ["He did NOT just hit that", "5,000", "3,180", "live"], ["Chat went crazy 😳", "2,000", "1,440", "live"], ["Fastest ace this season", "8,000", "0", "queued"], ["Reverse sweep highlight", "3,000", "0", "queued"]];
  return (
    <Card style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 24px 8px" }}>
        <div className="h3" style={{ fontSize: 17 }}>Clip queue</div>
        <button className="btn btn-ghost btn-sm"><Icon name="scissors" size={13} /> Add clip</button>
      </div>
      <table className="dtable">
        <thead><tr><th>Clip</th><th>Target</th><th>Views delivered</th><th>Status</th></tr></thead>
        <tbody>
          {queue.map((r, i) => (
            <tr key={i}>
              <td style={{ color: "var(--ink)" }}>{r[0]}</td>
              <td className="mono">{r[1]}</td>
              <td className="mono" style={{ color: "var(--accent)" }}>{r[2]}</td>
              <td>{r[3] === "done" ? <span className="status ok"><span className="sd" /> Done</span>
                : r[3] === "live" ? <span className="status warn"><span className="sd live-dot" /> Boosting</span>
                : <span className="status idle"><span className="sd" /> Queued</span>}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

/* ================= BILLING ================= */
const CURRENT_PLAN = { name: "Standard Plan", product: "views" };

function UpgradePlanCard({ plan, isCurrent }) {
  const [h, setH] = useT(false);
  return (
    <div className={plan.highlight ? "glass-strong" : "glass"} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        padding: 18, paddingTop: 24, borderRadius: "var(--radius)", display: "flex", flexDirection: "column", position: "relative",
        borderColor: isCurrent ? "color-mix(in oklch, var(--accent) 60%, transparent)" : plan.highlight ? "color-mix(in oklch, var(--accent) 45%, transparent)" : (h ? "var(--glass-hi)" : "var(--glass-border)"),
        transform: h ? "translateY(-4px)" : "none", transition: "transform .3s, border-color .3s",
        boxShadow: plan.highlight ? "var(--shadow-2), 0 0 44px -20px var(--accent-glow)" : undefined,
      }}>
      {plan.highlight && !isCurrent && (
        <div className="chip" style={{ position: "absolute", top: -11, left: "50%", transform: "translateX(-50%)", background: "var(--accent)", color: "var(--accent-ink)", border: "none", fontWeight: 640, fontSize: 11, padding: "5px 11px", whiteSpace: "nowrap" }}>Most popular</div>
      )}
      {isCurrent && (
        <div className="chip" style={{ position: "absolute", top: -11, left: "50%", transform: "translateX(-50%)", background: "var(--bg-1)", color: "var(--accent)", border: "1px solid color-mix(in oklch, var(--accent) 45%, transparent)", fontWeight: 640, fontSize: 11, padding: "5px 11px", whiteSpace: "nowrap" }}>Your plan</div>
      )}
      <div className="h3" style={{ fontSize: 16, fontWeight: 600 }}>{plan.name}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 4, margin: "8px 0 12px", flexWrap: "wrap" }}>
        <span style={{ fontSize: 30, fontWeight: 720, letterSpacing: "-0.04em" }}>{plan.price}</span>
        <span className="cap">/ {plan.per}</span>
      </div>
      <button className={isCurrent ? "btn btn-ghost btn-sm" : plan.highlight ? "btn btn-primary btn-sm" : "btn btn-ghost btn-sm"}
        disabled={isCurrent}
        style={{ width: "100%", justifyContent: "center", marginBottom: 16, opacity: isCurrent ? 0.6 : 1, cursor: isCurrent ? "default" : "pointer" }}>
        {isCurrent ? "Current plan" : <>Upgrade <Icon name="arrow" size={13} /></>}
      </button>
      <div className="stack" style={{ gap: 9 }}>
        {plan.feats.map(f => (
          <div key={f} style={{ display: "flex", gap: 9, alignItems: "flex-start" }}>
            <span style={{ color: "var(--accent)", flexShrink: 0, marginTop: 1 }}><Icon name="check" size={15} stroke={2.4} /></span>
            <span className="body" style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.4 }}>{f}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function UpgradeSection() {
  const [product, setProduct] = useT("views");
  const plans = product === "views" ? (window.KICK_VIEWS || []) : (window.KICK_AIO || []);
  return (
    <Card strong style={{ overflow: "visible" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 20 }}>
        <div>
          <div className="eyebrow">Upgrade your plan</div>
          <h3 className="h2" style={{ fontSize: 22, marginTop: 9 }}>Choose the plan that fits your stream</h3>
          <p className="cap" style={{ marginTop: 6 }}>Same pricing as our site · cancel anytime · upgrade or downgrade whenever you want.</p>
        </div>
        <div className="seg" style={{ flexShrink: 0 }}>
          {[["Kick Views", "views"], ["All-in-One", "aio"]].map(([l, v]) => (
            <button key={v} data-on={product === v} onClick={() => setProduct(v)}>{l}</button>
          ))}
        </div>
      </div>
      <div className="upgrade-grid" style={{ display: "grid", gridTemplateColumns: `repeat(${plans.length}, minmax(0, 1fr))`, gap: 12 }}>
        {plans.map(p => (
          <UpgradePlanCard key={p.name} plan={p}
            isCurrent={product === CURRENT_PLAN.product && p.name === CURRENT_PLAN.name} />
        ))}
      </div>
      <p className="cap" style={{ textAlign: "center", marginTop: 20, lineHeight: 1.5 }}>
        We accept Stripe &amp; Crypto. Holiday discounts drop in our support chat.
      </p>
      <style>{`
        @media (max-width: 1180px){ .upgrade-grid{ grid-template-columns: repeat(3, minmax(0,1fr)) !important; } }
        @media (max-width: 820px){ .upgrade-grid{ grid-template-columns: repeat(2, minmax(0,1fr)) !important; } }
        @media (max-width: 520px){ .upgrade-grid{ grid-template-columns: 1fr !important; } }
      `}</style>
    </Card>
  );
}

const CREDIT_TYPES = [
  { key: "views", label: "Live Views", sub: "Concurrent stream viewers", cost: 0.10, step: 100, icon: "signal" },
  { key: "followers", label: "Followers", sub: "Channel followers", cost: 0.015, step: 100, icon: "users" },
  { key: "chatters", label: "Chatters", sub: "Chat bot messages", cost: 0.10, step: 50, icon: "chat" },
  { key: "ai", label: "AI Chatbot", sub: "AI-generated replies", cost: 0.005, step: 500, icon: "spark" },
  { key: "polls", label: "Polls", sub: "Poll bot votes", cost: 0.10, step: 10, icon: "poll" },
  { key: "clips", label: "Clip Views", sub: "Clip view boosts", cost: 0.030, step: 100, icon: "scissors" },
  { key: "slots", label: "Auto-Start Slot", sub: "Extra automation slot", cost: 10.00, step: 1, icon: "zap" },
];
const QUICK_ADD = [
  { label: "Starter pack", qty: { views: 500, ai: 2000, followers: 200 } },
  { label: "Growth pack", qty: { views: 1500, chatters: 500, clips: 500, ai: 5000 } },
  { label: "Pro pack", qty: { views: 5000, followers: 1000, clips: 1000, polls: 200, ai: 10000 } },
];

function CreditStepper({ value, step, onChange }) {
  const btn = {
    width: 30, height: 30, borderRadius: 8, flexShrink: 0, display: "grid", placeItems: "center",
    background: "color-mix(in oklch, white 6%, transparent)", border: "1px solid var(--glass-border)",
    color: "var(--ink)", cursor: "pointer", fontSize: 16, fontWeight: 600, lineHeight: 0,
  };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <button style={btn} onClick={() => onChange(Math.max(0, value - step))}>−</button>
      <input value={value} onChange={e => onChange(Math.max(0, parseInt(e.target.value.replace(/\D/g, "")) || 0))}
        style={{ width: 72, textAlign: "center", background: "color-mix(in oklch, black 26%, transparent)", border: "1px solid var(--glass-border)", borderRadius: 9, color: "var(--ink)", fontSize: 14, fontWeight: 600, padding: "7px 4px", fontFamily: "var(--font)", fontVariantNumeric: "tabular-nums" }} />
      <button style={btn} onClick={() => onChange(value + step)}>+</button>
    </div>
  );
}

function PurchaseCredits() {
  const [qty, setQty] = useT(() => Object.fromEntries(CREDIT_TYPES.map(c => [c.key, 0])));
  const set = (key, v) => setQty(q => ({ ...q, [key]: v }));
  const lineTotal = (c) => qty[c.key] * c.cost;
  const total = CREDIT_TYPES.reduce((s, c) => s + lineTotal(c), 0);
  const items = CREDIT_TYPES.filter(c => qty[c.key] > 0).length;
  const applyPack = (pack) => setQty(q => {
    const next = Object.fromEntries(CREDIT_TYPES.map(c => [c.key, 0]));
    return { ...next, ...pack };
  });
  const fmt = (n) => "$" + n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return (
    <Card strong style={{ overflow: "visible" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 18 }}>
        <div>
          <div className="eyebrow">Top up</div>
          <h3 className="h2" style={{ fontSize: 22, marginTop: 9 }}>Purchase credits</h3>
          <p className="cap" style={{ marginTop: 6 }}>Pay only for what you need — à la carte, no subscription. Credits never expire.</p>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {QUICK_ADD.map(p => (
            <button key={p.label} className="btn btn-ghost btn-sm" onClick={() => applyPack(p.qty)}>{p.label}</button>
          ))}
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 12 }}>
        {CREDIT_TYPES.map(c => {
          const active = qty[c.key] > 0;
          return (
            <div key={c.key} className="glass" style={{ borderRadius: "var(--radius-sm)", padding: 16, borderColor: active ? "color-mix(in oklch, var(--accent) 38%, transparent)" : "var(--glass-border)", transition: "border-color .2s" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
                <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, display: "grid", placeItems: "center", color: "var(--accent)", background: "color-mix(in oklch, var(--accent) 12%, transparent)", border: "1px solid color-mix(in oklch, var(--accent) 28%, transparent)" }}><DIcon name={c.icon} size={19} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 560 }}>{c.label}</div>
                  <div className="cap" style={{ fontSize: 11 }}>{c.sub}</div>
                </div>
                <div style={{ textAlign: "right", flexShrink: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 640, color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>${c.cost.toFixed(3)}</div>
                  <div className="cap" style={{ fontSize: 10 }}>per {c.key === "slots" ? "slot" : "credit"}</div>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
                <CreditStepper value={qty[c.key]} step={c.step} onChange={v => set(c.key, v)} />
                <span style={{ fontSize: 15, fontWeight: 680, letterSpacing: "-0.02em", color: active ? "var(--ink)" : "var(--ink-3)", fontVariantNumeric: "tabular-nums" }}>{fmt(lineTotal(c))}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap", marginTop: 20, paddingTop: 18, borderTop: "1px solid var(--glass-border-soft)" }}>
        <div>
          <div className="cap">Total{items ? ` · ${items} ${items === 1 ? "item" : "items"}` : ""}</div>
          <div style={{ fontSize: 34, fontWeight: 720, letterSpacing: "-0.04em", color: total > 0 ? "var(--accent)" : "var(--ink-3)", fontVariantNumeric: "tabular-nums" }}>{fmt(total)}</div>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
          {total > 0 && <button className="btn btn-ghost" onClick={() => setQty(Object.fromEntries(CREDIT_TYPES.map(c => [c.key, 0])))}>Clear</button>}
          <button className="btn btn-primary btn-lg" disabled={total <= 0} style={{ opacity: total > 0 ? 1 : 0.55, cursor: total > 0 ? "pointer" : "not-allowed" }}>
            <Icon name="card" size={16} /> Purchase credits
          </button>
        </div>
      </div>
    </Card>
  );
}

function BillingScreen() {
  const pays = ["Stripe", "Square", "Zelle", "Cash App", "Venmo", "Crypto"];
  const invoices = [["Jun 1, 2026", "Standard — Monthly", "$50.00", "Paid"], ["May 1, 2026", "Standard — Monthly", "$50.00", "Paid"], ["Apr 1, 2026", "Standard — Monthly", "$50.00", "Paid"], ["Mar 1, 2026", "Starter — Monthly", "$10.00", "Paid"]];
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Card strong>
          <PanelHead eyebrow="Current plan" title="Standard Plan" right={<span className="status ok"><span className="sd" /> Active</span>} />
          <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginBottom: 18 }}>
            <span style={{ fontSize: 38, fontWeight: 720, letterSpacing: "-0.04em" }}>$50</span><span className="cap">/ month · renews Jul 1</span>
          </div>
          {[["AI Chatbot", 1980, 3750], ["Followers", 318, 500], ["Clip Views", 640, 1000], ["Auto-Start Slots", 2, 5]].map(([l, a, b]) => (
            <div key={l} style={{ marginBottom: 14 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 7 }}><span className="cap">{l}</span><span className="cap">{a.toLocaleString()} / {b.toLocaleString()}</span></div>
              <div style={{ height: 7, borderRadius: 99, background: "var(--glass-border)", overflow: "hidden" }}><div style={{ width: (a / b * 100) + "%", height: "100%", background: "linear-gradient(90deg, var(--accent), var(--accent-deep))" }} /></div>
            </div>
          ))}
          <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
            <button className="btn btn-primary" style={{ flex: 1, justifyContent: "center" }}>Upgrade</button>
            <button className="btn btn-ghost" style={{ flex: 1, justifyContent: "center" }}>Manage</button>
          </div>
        </Card>
        <Card>
          <PanelHead eyebrow="Payment methods" title="How you pay" />
          <div style={{ display: "flex", flexWrap: "wrap", gap: 9, marginBottom: 18 }}>
            {pays.map(p => <span key={p} className="chip">{p}</span>)}
          </div>
          <div className="glass" style={{ borderRadius: 14, padding: 16, display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ color: "var(--accent)" }}><Icon name="card" size={22} /></span>
            <div style={{ flex: 1 }}><div style={{ fontWeight: 560 }}>Visa ···· 4242</div><div className="cap">Expires 09 / 28</div></div>
            <span className="status ok"><span className="sd" /> Default</span>
          </div>
          <p className="cap" style={{ marginTop: 16, lineHeight: 1.5 }}>Holiday discounts drop in our Discord around Christmas &amp; Halloween.</p>
        </Card>
      </div>

      <UpgradeSection />

      <PurchaseCredits />

      <Card style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "18px 24px 4px" }}><div className="eyebrow">Invoices</div></div>
        <table className="dtable">
          <thead><tr><th>Date</th><th>Plan</th><th>Amount</th><th>Status</th></tr></thead>
          <tbody>{invoices.map((iv, i) => (
            <tr key={i}><td style={{ color: "var(--ink)" }}>{iv[0]}</td><td>{iv[1]}</td><td className="mono">{iv[2]}</td><td><span className="status ok"><span className="sd" /> {iv[3]}</span></td></tr>
          ))}</tbody>
        </table>
      </Card>
    </div>
  );
}

/* ================= SETTINGS ================= */
function SettingsScreen() {
  const [name, setName] = useT("yourname");
  const [email, setEmail] = useT("you@email.com");
  const [twofa, setTwofa] = useT(true);
  const [notif, setNotif] = useT({ updates: true, security: true, marketing: false });
  return (
    <div className="dash-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, alignItems: "start" }}>
      <Card strong>
        <PanelHead eyebrow="Account" title="Profile" />
        <FieldLabel>USERNAME</FieldLabel><div style={{ marginBottom: 16 }}><DField icon="users" value={name} onChange={setName} /></div>
        <FieldLabel>EMAIL</FieldLabel><div style={{ marginBottom: 20 }}><DField icon="globe" value={email} onChange={setEmail} /></div>
        <button className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }}>Save changes</button>
      </Card>
      <div className="stack" style={{ gap: 14 }}>
        <Card>
          <PanelHead eyebrow="Security" title="Protection" />
          <Row label="Two-factor authentication" sub="Extra layer on every login"><Toggle on={twofa} onChange={setTwofa} /></Row>
          <hr className="divider" style={{ margin: "14px 0" }} />
          <Row label="AES-256 encryption" sub="Always on for all sessions"><span className="status ok"><span className="sd" /> Enabled</span></Row>
        </Card>
        <Card>
          <PanelHead eyebrow="Notifications" title="What we tell you" />
          {[["updates", "Product updates"], ["security", "Security alerts"], ["marketing", "Promotions & discounts"]].map(([k, l], i) => (
            <React.Fragment key={k}>
              {i > 0 && <hr className="divider" style={{ margin: "12px 0" }} />}
              <Row label={l}><Toggle on={notif[k]} onChange={v => setNotif(n => ({ ...n, [k]: v }))} /></Row>
            </React.Fragment>
          ))}
        </Card>
        <Card style={{ borderColor: "color-mix(in oklch, oklch(0.65 0.2 25) 40%, transparent)" }}>
          <Row label="Delete account" sub="Permanently remove all data"><button className="btn btn-ghost" style={{ color: "oklch(0.78 0.18 25)", borderColor: "color-mix(in oklch, oklch(0.65 0.2 25) 40%, transparent)" }}>Delete</button></Row>
        </Card>
      </div>
    </div>
  );
}
function Row({ label, sub, children }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16 }}>
      <div><div style={{ fontWeight: 540, fontSize: 14.5 }}>{label}</div>{sub && <div className="cap" style={{ marginTop: 2 }}>{sub}</div>}</div>
      {children}
    </div>
  );
}

const SCREENS = {
  "Overview": OverviewScreen, "Viewer Bot": ViewerBotScreen, "Chat Bot": ChatBotScreen,
  "Ai Chatbot": AiChatbotScreen, "Poll Bot": PollbotScreen, "Follow Bot": FollowBotScreen,
  "Clip Viewbot": ClipViewbotScreen,
  "Billing": BillingScreen, "Settings": SettingsScreen,
};
Object.assign(window, { SCREENS });
