/* global React, I, S */
/* Pamp — Admin portal */

const A_NAV = [
  { key: "dashboard", label: "Dashboard", icon: I.dashboard },
  { key: "users", label: "User management", icon: I.users },
  { key: "bookings", label: "Bookings", icon: I.bookings, badge: "84" },
  { key: "notifications", label: "Notifications", icon: I.bell },
  { key: "coupons", label: "Coupons", icon: I.coupon },
  { section: "Money" },
  { key: "payments", label: "Payment center", icon: I.card },
  { key: "wallets", label: "Wallets & payouts", icon: I.wallet },
  { key: "subscriptions", label: "Subscriptions", icon: I.crown },
  { section: "Insight" },
  { key: "reports", label: "Reports & analytics", icon: I.chart },
  { key: "support", label: "Support & help", icon: I.help, badge: "12" },
  { section: "System" },
  { key: "settings", label: "Settings", icon: I.settings },
];

function AdminApp({ collapsed, onToggle, onTheme, theme, onExit, session, onNavigate, currentPage }) {
  const page = currentPage || "dashboard";
  const setPage = onNavigate;
  const tok = session?.accessToken;

  return (
    <div className="shell" data-sidebar={collapsed ? "collapsed" : "expanded"}>
      <S.Sidebar
        items={A_NAV}
        current={page}
        onNav={setPage}
        collapsed={collapsed}
        footer={
          <button className="nav-item" onClick={onExit} style={{ width: "100%" }} data-tip="Sign out">
            <span className="ni-icon"><I.logout size={18} /></span>
            <span className="ni-label">Sign out</span>
          </button>
        }
      />
      <div className="main-col">
        <S.Topbar
          onToggleSidebar={onToggle}
          onTheme={onTheme}
          theme={theme}
          search="Search users, bookings, transactions…"
        />
        <main className="main-scroll">
          {page === "dashboard"     && <AdminDashboard tok={tok} session={session} />}
          {page === "users"         && <AdminUsers tok={tok} />}
          {page === "bookings"      && <AdminBookings tok={tok} />}
          {page === "wallets"       && <AdminWallets tok={tok} />}
          {page === "subscriptions" && <AdminSubscriptions tok={tok} />}
          {page === "payments"      && <AdminPayments tok={tok} />}
          {page === "reports"       && <AdminReports tok={tok} />}
          {page === "support"       && <AdminSupport tok={tok} />}
          {page === "coupons"       && <AdminCoupons tok={tok} />}
          {page === "notifications" && <AdminNotifications tok={tok} />}
          {page === "settings"      && <AdminSettings tok={tok} />}
        </main>
      </div>
    </div>
  );
}

/* ====================================================================
   ADMIN — DASHBOARD
   ==================================================================== */
function AdminDashboard({ tok, session }) {
  const [stats, setStats] = React.useState(null);
  const firstName = (session?.profile?.full_name || "").split(" ")[0] || "there";

  React.useEffect(() => {
    let alive = true;
    SB.adminGetBookingStats(tok).then((s) => { if (alive) setStats(s); });
    return () => { alive = false; };
  }, [tok]);

  if (!stats) return <window.LoadingState />;

  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return "Good morning";
    if (h < 18) return "Good afternoon";
    return "Good evening";
  })();

  return (
    <div className="page-enter">
      <S.PageHead
        eyebrow="Overview · live data"
        title={`${greeting}, ${firstName}`}
        sub={`${stats.pending} pending bookings · ${stats.totalUsers} users on the platform.`}
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.calendar size={14} />}>This month</S.Btn>
          <S.Btn variant="outline" size="sm" icon={<I.download size={14} />}>Export</S.Btn>
        </>}
      />

      {/* hero metric grid */}
      <div className="grid-4" style={{ marginBottom: 20 }}>
        <S.Metric
          hero
          label="Total revenue"
          value={window.fmtMoney(stats.revenue)}
          delta={`${stats.completed} completed bookings`}
          spark={<S.Spark data={[8, 10, 9, 12, 14, 13, 16, 18, 17, 19, 22, 24]} color="oklch(80% 0.08 290)" width={120} height={36} />}
        />
        <S.Metric label="Active users" value={stats.totalUsers.toLocaleString()} delta={`${stats.recentBookings} recent`} deltaTone="pos" />
        <S.Metric label="Vendors" value={stats.totalVendors.toLocaleString()} delta="Active" deltaTone="pos" />
        <S.Metric label="Bookings" value={stats.totalBookings.toLocaleString()} delta={`${stats.pending} pending`} deltaTone={stats.pending > 0 ? "warn" : "pos"} />
      </div>

      {/* main grid */}
      <div className="grid-12" style={{ gap: 20 }}>
        {/* revenue chart */}
        <div className="card" style={{ gridColumn: "span 8" }}>
          <div className="row between" style={{ marginBottom: 8 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 6 }}>Revenue</div>
              <div className="display" style={{ fontSize: 32, lineHeight: 1 }}>$1,424,820</div>
              <div className="row-tight" style={{ marginTop: 6 }}>
                <S.Chip tone="pos">+24.4%</S.Chip>
                <span className="muted tiny">vs Dec · $1.14M</span>
              </div>
            </div>
            <div className="row" style={{ gap: 6 }}>
              <div className="row-tight"><span className="dot" style={{ background: "var(--accent)" }} /> <span className="tiny muted">Gross</span></div>
              <div className="row-tight" style={{ marginLeft: 12 }}><span className="dot" style={{ background: "var(--ink-3)" }} /> <span className="tiny muted">Net</span></div>
              <span style={{ width: 1, height: 16, background: "var(--border)", margin: "0 8px" }} />
              <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Daily</S.Btn>
            </div>
          </div>
          <S.LineChart
            height={260}
            currency
            labels={["1 Jan", "5", "10", "15", "20", "25", "30 Jan"]}
            series={[
              { color: "var(--accent)", data: [42000, 51000, 48000, 62000, 58000, 71000, 84000] },
              { color: "var(--ink-3)", data: [38000, 44000, 41000, 52000, 49000, 58000, 67000], dashed: true },
            ]}
          />
        </div>

        {/* booking mix */}
        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="row between" style={{ marginBottom: 4 }}>
            <div className="h3">Booking mix</div>
            <S.IconBtn><I.ellipsis size={16} /></S.IconBtn>
          </div>
          <div className="muted tiny" style={{ marginBottom: 18 }}>By category, this month</div>

          <div className="row" style={{ justifyContent: "center", marginBottom: 18 }}>
            <S.Ring value={68} size={150} label="62.1k" sub="total bookings" stroke={14} />
          </div>

          <div className="col" style={{ gap: 10 }}>
            {[
              { label: "Hair & color", v: 38, n: "23.6k", c: "var(--accent)" },
              { label: "Nails", v: 24, n: "14.9k", c: "var(--ink)" },
              { label: "Spa & massage", v: 19, n: "11.8k", c: "var(--info)" },
              { label: "Barber", v: 12, n: "7.4k", c: "var(--warn)" },
              { label: "Other", v: 7, n: "4.4k", c: "var(--ink-3)" },
            ].map((r, i) => (
              <div key={i} className="row" style={{ gap: 10 }}>
                <span className="dot" style={{ background: r.c }} />
                <span style={{ flex: 1, fontSize: 13 }}>{r.label}</span>
                <span className="mono tiny muted">{r.v}%</span>
                <span className="mono" style={{ fontSize: 12, width: 50, textAlign: "right" }}>{r.n}</span>
              </div>
            ))}
          </div>
        </div>

        {/* vendor leaderboard */}
        <div className="card card-flush" style={{ gridColumn: "span 8" }}>
          <div className="row between" style={{ padding: "22px 22px 14px" }}>
            <div>
              <div className="h3">Top vendors</div>
              <div className="muted tiny" style={{ marginTop: 4 }}>Ranked by net revenue, last 30 days</div>
            </div>
            <div className="row" style={{ gap: 8 }}>
              <S.Btn variant="ghost" size="sm" icon={<I.filter size={12} />}>Filter</S.Btn>
              <S.Btn variant="outline" size="sm">View all</S.Btn>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 36 }}>#</th>
                <th>Vendor</th>
                <th>Bookings</th>
                <th>Rating</th>
                <th>Capacity</th>
                <th className="col-num">Net</th>
                <th style={{ width: 60 }} />
              </tr>
            </thead>
            <tbody>
              {VENDORS.map((v, i) => (
                <tr key={v.name}>
                  <td className="mono muted">{String(i + 1).padStart(2, "0")}</td>
                  <td>
                    <div className="row-tight">
                      <S.Avatar name={v.name} size="sm" />
                      <div>
                        <div style={{ fontWeight: 500 }}>{v.name}</div>
                        <div className="muted tiny">{v.city} · {v.cat}</div>
                      </div>
                    </div>
                  </td>
                  <td className="mono">{v.bookings.toLocaleString()}</td>
                  <td><div className="row-tight"><I.star size={12} color="var(--warn)" /> {v.rating}</div></td>
                  <td style={{ width: 140 }}>
                    <div className="row-tight" style={{ gap: 8 }}>
                      <div className="bar" style={{ flex: 1 }}><span style={{ width: `${v.cap}%`, background: v.cap > 90 ? "var(--neg)" : v.cap > 70 ? "var(--warn)" : "var(--pos)" }} /></div>
                      <span className="mono tiny" style={{ width: 32 }}>{v.cap}%</span>
                    </div>
                  </td>
                  <td className="col-num mono" style={{ fontWeight: 500 }}>${v.net.toLocaleString()}</td>
                  <td><S.IconBtn><I.chevR size={14} /></S.IconBtn></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* activity feed */}
        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div className="h3">Live activity</div>
            <S.Chip tone="pos" icon={<span className="dot dot-pos" style={{ animation: "pulse 1.6s infinite" }} />}>live</S.Chip>
          </div>
          <div className="col" style={{ gap: 14 }}>
            {ACTIVITY.map((a, i) => (
              <div key={i} className="row-tight" style={{ alignItems: "flex-start" }}>
                <span style={{
                  width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                  background: a.tone === "pos" ? "var(--pos-soft)" : a.tone === "warn" ? "var(--warn-soft)" : "var(--accent-soft)",
                  color: a.tone === "pos" ? "var(--pos)" : a.tone === "warn" ? "var(--warn)" : "var(--accent-ink)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>{a.icon}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13 }}>{a.text}</div>
                  <div className="muted tiny" style={{ marginTop: 2 }}>{a.time}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* payouts queue */}
        <div className="card" style={{ gridColumn: "span 5" }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div>
              <div className="h3">Payout queue</div>
              <div className="muted tiny" style={{ marginTop: 4 }}>84 vendors · clears tonight 11:00 PM UTC</div>
            </div>
            <S.Btn variant="outline" size="sm">Review all</S.Btn>
          </div>
          <div className="display" style={{ fontSize: 40, letterSpacing: "-0.03em", marginBottom: 4 }}>$284,910</div>
          <div className="muted tiny" style={{ marginBottom: 18 }}>Total amount staged</div>

          <div className="col" style={{ gap: 10 }}>
            {[
              { name: "Maison Color & Co.", amount: 8420, ago: "Queued 12m ago", tone: "ready" },
              { name: "Atelier Nails", amount: 6210, ago: "Queued 38m ago", tone: "ready" },
              { name: "Forest Spa", amount: 14820, ago: "Manual review", tone: "review" },
              { name: "Cut & Co Barber", amount: 3920, ago: "Queued 1h ago", tone: "ready" },
            ].map((p, i) => (
              <div key={i} className="row" style={{ padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 10 }}>
                <S.Avatar name={p.name} size="sm" />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
                  <div className="muted tiny">{p.ago}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="mono" style={{ fontSize: 13, fontWeight: 500 }}>${p.amount.toLocaleString()}</div>
                  <S.Chip tone={p.tone === "review" ? "warn" : "pos"}>{p.tone === "review" ? "Review" : "Ready"}</S.Chip>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* health */}
        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div className="h3">Platform health</div>
            <S.Chip tone="pos">All systems go</S.Chip>
          </div>
          <div className="row" style={{ justifyContent: "center", marginBottom: 14 }}>
            <S.Gauge value={94} size={170} label="94%" sub="composite SLO" />
          </div>
          <div className="col" style={{ gap: 10 }}>
            {[
              { l: "API latency p99", v: "182 ms", t: "pos" },
              { l: "Payments success", v: "99.97%", t: "pos" },
              { l: "Search index lag", v: "1.2s", t: "warn" },
              { l: "Webhook delivery", v: "99.84%", t: "pos" },
            ].map((h) => (
              <div key={h.l} className="row between">
                <span className="muted tiny">{h.l}</span>
                <span className="row-tight"><span className={`dot dot-${h.t}`} /><span className="mono tiny">{h.v}</span></span>
              </div>
            ))}
          </div>
        </div>

        {/* support */}
        <div className="card" style={{ gridColumn: "span 3" }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div className="h3">Support</div>
            <S.IconBtn><I.arrowR size={14} /></S.IconBtn>
          </div>
          <div className="display" style={{ fontSize: 40 }}>12</div>
          <div className="muted tiny">Open tickets</div>
          <div className="divider" style={{ margin: "16px 0" }} />
          <div className="col" style={{ gap: 8 }}>
            <div className="row between"><span className="tiny">Urgent</span><span className="row-tight"><span className="dot dot-neg" /><span className="mono tiny">2</span></span></div>
            <div className="row between"><span className="tiny">In progress</span><span className="row-tight"><span className="dot dot-warn" /><span className="mono tiny">7</span></span></div>
            <div className="row between"><span className="tiny">Waiting</span><span className="row-tight"><span className="dot" style={{ background: "var(--ink-4)" }} /><span className="mono tiny">3</span></span></div>
          </div>
          <div className="muted tiny" style={{ marginTop: 14, lineHeight: 1.5 }}>
            Median first response <strong style={{ color: "var(--ink)" }}>4m 12s</strong>
          </div>
        </div>
      </div>

      <style dangerouslySetInnerHTML={{ __html: "@keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}" }} />
    </div>
  );
}

const VENDORS = [
  { name: "Maison Color & Co.", city: "Paris", cat: "Hair & color", bookings: 1840, rating: 4.9, cap: 92, net: 84210 },
  { name: "Atelier Nails", city: "Brooklyn", cat: "Nails", bookings: 1420, rating: 4.8, cap: 88, net: 62180 },
  { name: "Forest Spa", city: "Reykjavík", cat: "Spa", bookings: 980, rating: 4.9, cap: 76, net: 58420 },
  { name: "Cut & Co Barber", city: "Berlin", cat: "Barber", bookings: 2100, rating: 4.7, cap: 95, net: 38210 },
  { name: "Glow Skin Studio", city: "Lisbon", cat: "Facials", bookings: 820, rating: 4.9, cap: 71, net: 34180 },
];

const ACTIVITY = [
  { tone: "pos", icon: <I.check size={14} />, text: "New vendor Maison Color & Co. approved", time: "2m ago" },
  { tone: "accent", icon: <I.card size={14} />, text: "Payout batch #2418 queued · $284,910 across 84 vendors", time: "12m ago" },
  { tone: "pos", icon: <I.users size={14} />, text: "1,420 new client accounts in the last hour", time: "34m ago" },
  { tone: "warn", icon: <I.help size={14} />, text: "Urgent ticket from Forest Spa — payout review", time: "1h ago" },
  { tone: "accent", icon: <I.coupon size={14} />, text: "Coupon WELLNESS25 redeemed 218 times today", time: "2h ago" },
];

/* ====================================================================
   ADMIN — USERS
   ==================================================================== */
function AdminUsers() {
  const [tab, setTab] = React.useState("clients");
  const [selected, setSelected] = React.useState(null);
  const [inviteOpen, setInviteOpen] = React.useState(false);
  const data = tab === "clients" ? CLIENTS : tab === "vendors" ? STAFF_USERS_VENDORS : STAFF_USERS_PLATFORM;

  return (
    <div className="page-enter">
      <window.DemoBanner feature="user management (live wiring next phase)" />
      <S.PageHead
        eyebrow="People · 30,273 total"
        title="User management"
        sub="Clients, vendors, and platform staff in one place."
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.filter size={14} />}>Filter</S.Btn>
          <S.Btn variant="outline" size="sm" icon={<I.download size={14} />}>Export CSV</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.plus size={14} />} onClick={() => setInviteOpen(true)}>Invite user</S.Btn>
        </>}
      />

      <div className="row" style={{ gap: 0, borderBottom: "1px solid var(--border)", marginBottom: 20 }}>
        {[{ k: "clients", l: "Clients", n: 28431 }, { k: "vendors", l: "Vendors", n: 1842 }, { k: "staff", l: "Platform staff", n: 12 }].map(t => (
          <button key={t.k} onClick={() => setTab(t.k)}
            style={{
              padding: "12px 18px", fontSize: 13, fontWeight: 500,
              color: tab === t.k ? "var(--ink)" : "var(--ink-3)",
              borderBottom: `2px solid ${tab === t.k ? "var(--ink)" : "transparent"}`,
              marginBottom: -1,
            }}>
            {t.l} <span className="mono tiny muted" style={{ marginLeft: 4 }}>{t.n.toLocaleString()}</span>
          </button>
        ))}
      </div>

      <div className="card card-flush">
        <div className="row" style={{ padding: 16, gap: 10 }}>
          <S.Input icon={<I.search size={15} />} placeholder="Search by name, email, ID…" style={{ flex: 1, maxWidth: 360 }} />
          <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Country: All</S.Btn>
          <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Status: All</S.Btn>
          <div className="spacer" />
          <span className="muted tiny">{data.length} results · sorted by signup ↓</span>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 30 }}><input type="checkbox" /></th>
              <th>{tab === "vendors" ? "Vendor" : tab === "staff" ? "Staff member" : "Client"}</th>
              {tab === "vendors" ? <>
                <th>Category</th>
                <th>Plan</th>
                <th>Bookings</th>
                <th>Net (mtd)</th>
              </> : tab === "staff" ? <>
                <th>Role</th>
                <th>Email</th>
                <th>Last active</th>
                <th />
              </> : <>
                <th>City</th>
                <th>Bookings</th>
                <th>Lifetime value</th>
              </>}
              <th>Status</th>
              <th>Joined</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {data.map((u) => (
              <tr key={u.id} onClick={() => setSelected({ ...u, _kind: tab })} style={{ cursor: "pointer" }}>
                <td onClick={(e) => e.stopPropagation()}><input type="checkbox" /></td>
                <td>
                  <div className="row-tight">
                    <S.Avatar name={u.name} size="sm" />
                    <div>
                      <div style={{ fontWeight: 500 }}>{u.name}</div>
                      <div className="muted tiny">{u.email}</div>
                    </div>
                  </div>
                </td>
                {tab === "vendors" ? <>
                  <td>{u.category}</td>
                  <td><S.Chip tone={u.plan === "Atelier" ? "accent" : u.plan === "Studio" ? "info" : ""}>{u.plan}</S.Chip></td>
                  <td className="mono">{u.bookings.toLocaleString()}</td>
                  <td className="mono">${u.netMtd.toLocaleString()}</td>
                </> : tab === "staff" ? <>
                  <td><S.Chip tone="accent">{u.role}</S.Chip></td>
                  <td className="mono muted tiny">{u.email}</td>
                  <td className="muted tiny">{u.lastActive}</td>
                  <td />
                </> : <>
                  <td>{u.city}</td>
                  <td className="mono">{u.bookings}</td>
                  <td className="mono">${u.ltv.toLocaleString()}</td>
                </>}
                <td><S.Chip tone={u.status === "Active" ? "pos" : u.status === "Dormant" ? "warn" : u.status === "Banned" || u.status === "Suspended" ? "neg" : "info"}>{u.status}</S.Chip></td>
                <td className="mono muted">{u.joined}</td>
                <td><S.IconBtn><I.chevR size={14} /></S.IconBtn></td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="row between" style={{ padding: 16, borderTop: "1px solid var(--border)" }}>
          <span className="muted tiny">Showing 1–{data.length}</span>
          <div className="row-tight">
            <S.Btn variant="outline" size="sm">Prev</S.Btn>
            <S.Btn variant="outline" size="sm" iconRight={<I.chevR size={12} />}>Next</S.Btn>
          </div>
        </div>
      </div>

      <UserDetailModal user={selected} onClose={() => setSelected(null)} />
      <InviteUserModal open={inviteOpen} onClose={() => setInviteOpen(false)} defaultRole={tab === "vendors" ? "vendor" : "client"} />
    </div>
  );
}

/* ----------------------------- INVITE USER MODAL ------------------- */
function InviteUserModal({ open, onClose, defaultRole = "client" }) {
  const [data, setData] = React.useState({ name: "", email: "", phone: "", role: defaultRole, message: "" });
  const [errors, setErrors] = React.useState({});
  React.useEffect(() => { if (open) setData(d => ({ ...d, role: defaultRole })); }, [open, defaultRole]);
  const set = (k, v) => { setData(d => ({ ...d, [k]: v })); setErrors(e => ({ ...e, [k]: undefined })); };
  const reset = () => { setData({ name: "", email: "", phone: "", role: defaultRole, message: "" }); setErrors({}); };

  const submit = () => {
    const e = {};
    if (!data.name.trim()) e.name = "Full name is required.";
    if (!data.email.trim()) e.email = "Email is required.";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = "Enter a valid email address.";
    if (data.phone && !/^[+\d\s()-]{7,}$/.test(data.phone)) e.phone = "Enter a valid phone number.";
    setErrors(e);
    if (Object.keys(e).length === 0) { onClose(); reset(); }
  };

  return (
    <window.M.Modal open={open} onClose={() => { onClose(); reset(); }} size="lg"
      icon={<I.users />} title="Invite a new user"
      subtitle="Send a private invitation. They'll receive an email with a secure sign-up link."
      footer={<>
        <S.Btn variant="ghost" onClick={() => { onClose(); reset(); }}>Cancel</S.Btn>
        <S.Btn variant="primary" iconRight={<I.arrowR size={14} />} onClick={submit}>Send invite</S.Btn>
      </>}
    >
      <window.M.FormGrid>
        <window.M.Field full label="Account type">
          <window.M.RadioCards value={data.role} onChange={(v) => set("role", v)}
            options={[
              { value: "client", label: "Client", desc: "Books and pays for services" },
              { value: "vendor", label: "Vendor", desc: "Runs a studio on Pamp" },
            ]} />
        </window.M.Field>
        <window.M.Field full label="Full name" error={errors.name}>
          <window.M.TextField value={data.name} onChange={(v) => set("name", v)} placeholder="Jordan Lee" />
        </window.M.Field>
        <window.M.Field label="Email" error={errors.email}>
          <window.M.TextField icon={<I.mail size={14} />} value={data.email} onChange={(v) => set("email", v)} placeholder="jordan@example.com" />
        </window.M.Field>
        <window.M.Field label="Phone number" hint="Optional but recommended." error={errors.phone}>
          <window.M.TextField icon={<I.phone size={14} />} value={data.phone} onChange={(v) => set("phone", v)} placeholder="+1 555 0142" />
        </window.M.Field>
        <window.M.Field full label="Optional message" hint="Shown in the invitation email.">
          <window.M.Textarea value={data.message} onChange={(v) => set("message", v)} placeholder="Hey — welcoming you to the Pamp platform. Let me know if anything's unclear." />
        </window.M.Field>
      </window.M.FormGrid>
    </window.M.Modal>
  );
}

const CLIENTS = [
  { id: 1, name: "Amelia Brooks", email: "amelia@hey.com", city: "London", phone: "+44 7700 900 142", bookings: 24, ltv: 1820, status: "Active", joined: "Jan 14, 2024", verified: true, tier: "Gold" },
  { id: 2, name: "Marcus Chen", email: "marcus.c@gmail.com", city: "New York", phone: "+1 917 555 0142", bookings: 18, ltv: 1240, status: "Active", joined: "Mar 02, 2024", verified: true, tier: "Silver" },
  { id: 3, name: "Priya Shah", email: "priya@studio.io", city: "Mumbai", phone: "+91 98201 12390", bookings: 9, ltv: 680, status: "Dormant", joined: "Aug 21, 2024", verified: true, tier: "Silver" },
  { id: 4, name: "Sofia Romano", email: "sofia.r@proton.me", city: "Milan", phone: "+39 348 211 9920", bookings: 41, ltv: 3120, status: "Active", joined: "Nov 04, 2023", verified: true, tier: "Platinum" },
  { id: 5, name: "Daniel Park", email: "dpark@fastmail.com", city: "Seoul", phone: "+82 10 4218 2210", bookings: 12, ltv: 920, status: "Active", joined: "Dec 19, 2024", verified: true, tier: "Silver" },
  { id: 6, name: "Olivia Wright", email: "olivia.w@hey.com", city: "Sydney", phone: "+61 412 339 821", bookings: 6, ltv: 410, status: "Banned", joined: "Feb 28, 2025", verified: false, tier: "Silver" },
  { id: 7, name: "Idris Ahmed", email: "idris.a@gmail.com", city: "Dubai", phone: "+971 50 449 1820", bookings: 32, ltv: 2480, status: "Active", joined: "Oct 11, 2024", verified: true, tier: "Gold" },
];
const STAFF_USERS_VENDORS = [
  { id: 101, name: "Maison Color & Co.", email: "hello@maisoncolor.fr", city: "Paris", category: "Hair & color", plan: "Atelier", bookings: 1840, netMtd: 84210, status: "Active", joined: "Jul 02, 2023", verified: true },
  { id: 102, name: "Atelier Nails", email: "team@ateliernails.com", city: "Brooklyn", category: "Nails", plan: "Studio", bookings: 1420, netMtd: 62180, status: "Active", joined: "Mar 18, 2024", verified: true },
  { id: 103, name: "Forest Spa", email: "front@forestspa.is", city: "Reykjavík", category: "Spa", plan: "Atelier", bookings: 980, netMtd: 58420, status: "Active", joined: "Aug 12, 2023", verified: true },
  { id: 104, name: "Cut & Co Barber", email: "shop@cutandco.de", city: "Berlin", category: "Barber", plan: "Studio", bookings: 2100, netMtd: 38210, status: "Active", joined: "Jan 04, 2024", verified: true },
  { id: 105, name: "Glow Skin Studio", email: "hi@glow.pt", city: "Lisbon", category: "Facials", plan: "Starter", bookings: 820, netMtd: 14180, status: "Dormant", joined: "Oct 19, 2024", verified: false },
];
const STAFF_USERS_PLATFORM = [
  { id: 201, name: "Mira Johnson", email: "mira.j@pamp.app", role: "Owner", lastActive: "Online now", status: "Active", joined: "May 04, 2022" },
  { id: 202, name: "Eli Rosenberg", email: "eli.r@pamp.app", role: "Support lead", lastActive: "12m ago", status: "Active", joined: "Aug 11, 2022" },
  { id: 203, name: "Olu Adeyemi", email: "olu.a@pamp.app", role: "Finance", lastActive: "1h ago", status: "Active", joined: "Feb 18, 2024" },
  { id: 204, name: "Sasha Ivanov", email: "sasha.i@pamp.app", role: "Trust & safety", lastActive: "Yesterday", status: "Suspended", joined: "Jun 02, 2024" },
];

/* ----------------------------- USER DETAIL MODAL ------------------- */
function UserDetailModal({ user, onClose }) {
  if (!user) return null;
  const isVendor = user._kind === "vendors";
  const isStaff = user._kind === "staff";
  return (
    <window.M.Modal open={!!user} onClose={onClose} size="lg">
      <div style={{ padding: 28, paddingTop: 8 }}>
        <div className="row" style={{ gap: 18, marginBottom: 22 }}>
          <S.Avatar name={user.name} size="xl" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="row-tight">
              <div className="display" style={{ fontSize: 24, letterSpacing: "-0.02em" }}>{user.name}</div>
              {user.verified && <span style={{ width: 16, height: 16, borderRadius: 999, background: "var(--accent)", color: "oklch(20% 0.10 145)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><I.check size={10} /></span>}
            </div>
            <div className="muted tiny" style={{ marginTop: 4 }}>{user.email} · ID #{user.id}</div>
            <div className="row-tight" style={{ marginTop: 10, gap: 6 }}>
              <S.Chip tone={user.status === "Active" ? "pos" : user.status === "Dormant" ? "warn" : "neg"}>{user.status}</S.Chip>
              {isVendor && <S.Chip tone={user.plan === "Atelier" ? "accent" : "info"}>{user.plan} plan</S.Chip>}
              {!isVendor && !isStaff && user.tier && <S.Chip tone={user.tier === "Platinum" ? "accent" : user.tier === "Gold" ? "warn" : ""}>{user.tier} tier</S.Chip>}
              {isStaff && <S.Chip tone="accent">{user.role}</S.Chip>}
            </div>
          </div>
          <button onClick={onClose} className="icon-btn"><I.x size={18} /></button>
        </div>

        {!isStaff && (
          <div className="grid-3" style={{ marginBottom: 20 }}>
            <ClientStat label={isVendor ? "Bookings (life)" : "Bookings"} value={isVendor ? user.bookings.toLocaleString() : user.bookings} />
            <ClientStat label={isVendor ? "Net MTD" : "Lifetime spend"} value={`$${(isVendor ? user.netMtd : user.ltv).toLocaleString()}`} />
            <ClientStat label="Joined" value={user.joined.split(",")[0]} />
          </div>
        )}

        <div className="card" style={{ padding: 18, marginBottom: 14 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Contact</div>
          <div className="grid-2" style={{ gap: 14 }}>
            <ClientField icon={<I.mail size={14} />} label="Email" value={user.email} />
            {user.phone && <ClientField icon={<I.phone size={14} />} label="Phone" value={user.phone} />}
            {user.city && <ClientField icon={<I.location size={14} />} label="Location" value={user.city} />}
            {isVendor && <ClientField icon={<I.store size={14} />} label="Category" value={user.category} />}
            {isStaff && <ClientField icon={<I.clock size={14} />} label="Last active" value={user.lastActive} />}
          </div>
        </div>

        {!isStaff && (
          <div className="card" style={{ padding: 18, marginBottom: 14 }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Recent activity</div>
            <div className="col" style={{ gap: 8 }}>
              {[
                { d: "Today", t: isVendor ? "Payout queued · $4,820" : "Booked Maison Color · $184", tone: "pos" },
                { d: "Yesterday", t: isVendor ? "3 new bookings" : "Top-up · $100", tone: "info" },
                { d: "Jan 28", t: isVendor ? "Subscription renewed (Atelier)" : "Forest Spa · $142", tone: "info" },
              ].map((r, i) => (
                <div key={i} className="row between" style={{ padding: "8px 0" }}>
                  <span className="row-tight"><span className={`dot dot-${r.tone}`} /><span style={{ fontSize: 13 }}>{r.t}</span></span>
                  <span className="muted tiny">{r.d}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="card" style={{ padding: 18 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Admin actions</div>
          <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
            <S.Btn variant="outline" size="sm" icon={<I.mail size={12} />}>Send message</S.Btn>
            <S.Btn variant="outline" size="sm" icon={<I.coupon size={12} />}>Issue credit</S.Btn>
            {!isStaff && <S.Btn variant="outline" size="sm" icon={<I.export size={12} />}>Impersonate</S.Btn>}
            {isVendor && <S.Btn variant="outline" size="sm" icon={<I.check size={12} />}>Force verify</S.Btn>}
            <S.Btn variant="outline" size="sm" icon={<I.clock size={12} />}>Reset password</S.Btn>
            <S.Btn variant="outline" size="sm" style={{ color: "var(--warn)", borderColor: "var(--warn)" }}>Suspend</S.Btn>
            <S.Btn variant="outline" size="sm" style={{ color: "var(--neg)", borderColor: "var(--neg)" }}>Ban</S.Btn>
          </div>
        </div>
      </div>

      <div className="modal-foot">
        <span className="muted tiny">{isVendor ? `Vendor · ${user.plan}` : isStaff ? `Platform staff · ${user.role}` : "Client"} · joined {user.joined}</span>
        <div className="spacer" />
        <S.Btn variant="ghost" onClick={onClose}>Close</S.Btn>
        <S.Btn variant="primary" iconRight={<I.arrowR size={14} />}>Open profile</S.Btn>
      </div>
    </window.M.Modal>
  );
}

function ClientStat({ label, value }) {
  return (
    <div style={{ padding: 16, background: "var(--surface-2)", borderRadius: 12 }}>
      <div className="muted tiny">{label}</div>
      <div className="display" style={{ fontSize: 22, marginTop: 4 }}>{value}</div>
    </div>
  );
}
function ClientField({ icon, label, value }) {
  return (
    <div>
      <div className="muted tiny row-tight" style={{ marginBottom: 4 }}>{icon}{label}</div>
      <div style={{ fontSize: 13.5 }}>{value}</div>
    </div>
  );
}

/* ====================================================================
   ADMIN — BOOKINGS
   ==================================================================== */
function AdminBookings() {
  const [scheduleOpen, setScheduleOpen] = React.useState(false);
  return (
    <div className="page-enter">
      <window.DemoBanner feature="bookings list (live wiring next phase)" />
      <S.PageHead
        eyebrow="62,108 bookings · last 30 days"
        title="Bookings"
        sub="Every appointment across the network, in real time."
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.filter size={14} />}>Filter</S.Btn>
          <S.Btn variant="outline" size="sm" icon={<I.export size={14} />}>Export</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.plus size={14} />} onClick={() => setScheduleOpen(true)}>Schedule</S.Btn>
        </>}
      />

      <div className="grid-4" style={{ marginBottom: 24 }}>
        <S.Metric label="Scheduled" value="2,401" delta="+12%" />
        <S.Metric label="Completed today" value="1,820" delta="+4%" />
        <S.Metric label="Cancellations" value="124" delta="−18%" deltaTone="pos" />
        <S.Metric label="No-shows" value="62" delta="+8%" deltaTone="neg" />
      </div>

      <div className="card card-flush">
        <div className="row" style={{ padding: 16, gap: 10 }}>
          <S.Input icon={<I.search size={15} />} placeholder="Search by client, vendor, ID…" style={{ flex: 1, maxWidth: 360 }} />
          <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Status: All</S.Btn>
          <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Today</S.Btn>
          <div className="spacer" />
          <div className="row-tight" style={{ background: "var(--surface-3)", padding: 2, borderRadius: 999 }}>
            <button className="btn btn-ghost btn-sm" style={{ background: "var(--surface)", color: "var(--ink)" }}><I.list size={13} /></button>
            <button className="btn btn-ghost btn-sm"><I.calendar size={13} /></button>
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>ID</th>
              <th>Client</th>
              <th>Vendor</th>
              <th>Service</th>
              <th>When</th>
              <th>Status</th>
              <th className="col-num">Total</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {BOOKINGS.map((b) => (
              <tr key={b.id}>
                <td className="mono muted">#{b.id}</td>
                <td><div className="row-tight"><S.Avatar name={b.client} size="sm" />{b.client}</div></td>
                <td>{b.vendor}</td>
                <td>{b.service}</td>
                <td><div className="mono tiny">{b.date}</div><div className="muted tiny">{b.time}</div></td>
                <td><S.Chip tone={b.statusTone}>{b.status}</S.Chip></td>
                <td className="col-num mono">${b.total}</td>
                <td><S.IconBtn><I.chevR size={14} /></S.IconBtn></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <ScheduleBookingModal open={scheduleOpen} onClose={() => setScheduleOpen(false)} />
    </div>
  );
}

function ScheduleBookingModal({ open, onClose }) {
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({ client: "", vendor: "", service: "", date: "", time: "", staff: "any", notes: "" });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const reset = () => { setStep(1); setData({ client: "", vendor: "", service: "", date: "", time: "", staff: "any", notes: "" }); };

  return (
    <window.M.Modal open={open} onClose={() => { onClose(); reset(); }} size="lg"
      icon={<I.calendar />} title="Schedule appointment"
      subtitle="Book on behalf of a client. They’ll get a confirmation email."
      footer={<>
        <div className="row-tight" style={{ flex: 1 }}>
          {[1, 2, 3].map(s => (
            <div key={s} style={{ flex: 1, height: 4, borderRadius: 999, background: step >= s ? "var(--accent)" : "var(--surface-3)" }} />
          ))}
        </div>
        {step > 1 && <S.Btn variant="ghost" onClick={() => setStep(step - 1)}>Back</S.Btn>}
        {step < 3 ? (
          <S.Btn variant="primary" iconRight={<I.arrowR size={14} />} onClick={() => setStep(step + 1)}>Continue</S.Btn>
        ) : (
          <S.Btn variant="primary" iconRight={<I.check size={14} />} onClick={() => { onClose(); reset(); }}>Confirm booking</S.Btn>
        )}
      </>}
    >
      {step === 1 && <window.M.FormGrid>
        <window.M.Field full label="Client" hint="Existing client account or add new.">
          <window.M.TextField icon={<I.search size={14} />} value={data.client} onChange={(v) => set("client", v)} placeholder="Search by name or email" />
        </window.M.Field>
        <window.M.Field full label="Vendor">
          <window.M.TextField icon={<I.store size={14} />} value={data.vendor} onChange={(v) => set("vendor", v)} placeholder="Search vendor" />
        </window.M.Field>
        <window.M.Field full label="Service">
          <window.M.RadioCards value={data.service} onChange={(v) => set("service", v)}
            options={[
              { value: "color", label: "Full color & cut", desc: "90 min · from $145", right: <span className="mono tiny muted">$145</span> },
              { value: "balayage", label: "Balayage", desc: "180 min · from $285", right: <span className="mono tiny muted">$285</span> },
              { value: "touchup", label: "Root touch-up", desc: "60 min · from $95", right: <span className="mono tiny muted">$95</span> },
              { value: "cut", label: "Cut & style", desc: "75 min · from $110", right: <span className="mono tiny muted">$110</span> },
            ]} />
        </window.M.Field>
      </window.M.FormGrid>}

      {step === 2 && <window.M.FormGrid>
        <window.M.Field label="Date">
          <window.M.TextField icon={<I.calendar size={14} />} value={data.date} onChange={(v) => set("date", v)} placeholder="Feb 14, 2026" />
        </window.M.Field>
        <window.M.Field label="Time">
          <window.M.TextField icon={<I.clock size={14} />} value={data.time} onChange={(v) => set("time", v)} placeholder="2:30 PM" />
        </window.M.Field>
        <window.M.Field full label="Stylist">
          <window.M.Segmented value={data.staff} onChange={(v) => set("staff", v)}
            options={[
              { value: "any", label: "Any available" },
              { value: "lea", label: "Léa M." },
              { value: "camille", label: "Camille R." },
              { value: "ines", label: "Inès K." },
            ]} />
        </window.M.Field>
        <window.M.Field full label="Notes for vendor (optional)">
          <window.M.Textarea value={data.notes} onChange={(v) => set("notes", v)} placeholder="Allergies, preferences, anything they should know…" />
        </window.M.Field>
      </window.M.FormGrid>}

      {step === 3 && <div>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Review &amp; confirm</div>
        <div className="card" style={{ padding: 18, background: "var(--surface-2)" }}>
          <ReviewRow label="Client" value={data.client || "—"} />
          <ReviewRow label="Vendor" value={data.vendor || "—"} />
          <ReviewRow label="Service" value={data.service || "—"} />
          <ReviewRow label="When" value={`${data.date || "—"} · ${data.time || "—"}`} />
          <ReviewRow label="Stylist" value={data.staff} />
          {data.notes && <ReviewRow label="Notes" value={data.notes} />}
        </div>
        <div className="row-tight" style={{ marginTop: 16, padding: 14, background: "var(--accent-soft)", color: "var(--accent-ink)", borderRadius: 10, fontSize: 13 }}>
          <I.mail size={14} /> The client will receive a confirmation email and an SMS reminder 24 hours before.
        </div>
      </div>}
    </window.M.Modal>
  );
}

function ReviewRow({ label, value }) {
  return (
    <div className="row between" style={{ padding: "8px 0", borderTop: "1px solid var(--border)" }}>
      <span className="muted tiny">{label}</span>
      <span style={{ fontSize: 13, fontWeight: 500, textAlign: "right", maxWidth: "60%" }}>{value}</span>
    </div>
  );
}

const BOOKINGS = [
  { id: "PB-28401", client: "Amelia Brooks", vendor: "Maison Color & Co.", service: "Full color · 90 min", date: "Feb 02", time: "14:30", status: "Confirmed", statusTone: "pos", total: 184 },
  { id: "PB-28402", client: "Marcus Chen", vendor: "Cut & Co Barber", service: "Beard trim", date: "Feb 02", time: "15:00", status: "In progress", statusTone: "info", total: 38 },
  { id: "PB-28403", client: "Priya Shah", vendor: "Atelier Nails", service: "Gel manicure", date: "Feb 02", time: "16:15", status: "Pending", statusTone: "warn", total: 64 },
  { id: "PB-28404", client: "Sofia Romano", vendor: "Forest Spa", service: "Deep tissue · 60 min", date: "Feb 03", time: "10:00", status: "Confirmed", statusTone: "pos", total: 142 },
  { id: "PB-28405", client: "Idris Ahmed", vendor: "Glow Skin Studio", service: "HydraFacial", date: "Feb 03", time: "11:30", status: "Cancelled", statusTone: "neg", total: 0 },
  { id: "PB-28406", client: "Daniel Park", vendor: "Maison Color & Co.", service: "Cut + style", date: "Feb 03", time: "13:00", status: "Confirmed", statusTone: "pos", total: 96 },
];

/* ====================================================================
   ADMIN — WALLETS & PAYOUTS
   ==================================================================== */
function AdminWallets() {
  const [payouts, setPayouts] = React.useState(PAYOUT_REQUESTS);
  const updatePayout = (id, status) => setPayouts(payouts.map(p => p.id === id ? { ...p, status } : p));

  return (
    <div className="page-enter">
      <window.DemoBanner feature="wallets & payouts (live wiring next phase)" />
      <S.PageHead eyebrow="Money · 30-day window" title="Wallets & payouts"
        sub="Gross volume, take rate, vendor balances, payout pipeline."
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.download size={14} />}>Export ledger</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.card size={14} />}>Run payout batch</S.Btn>
        </>}
      />

      <div className="grid-4" style={{ marginBottom: 24 }}>
        <S.Metric hero label="Gross volume" value="$4.82M" delta="+24.4%" />
        <S.Metric label="Pamp net" value="$382k" delta="+22.1%" />
        <S.Metric label="Take rate" value="7.92%" delta="+0.2pp" />
        <S.Metric label="Refunds" value="$18.4k" delta="−12%" deltaTone="pos" />
      </div>

      <div className="grid-12" style={{ marginBottom: 24 }}>
        <div className="card" style={{ gridColumn: "span 8" }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div className="h3">Volume vs. payouts</div>
            <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Last 12 weeks</S.Btn>
          </div>
          <S.LineChart
            height={260}
            currency
            labels={["W1", "W2", "W3", "W4", "W5", "W6", "W7", "W8", "W9", "W10", "W11", "W12"]}
            series={[
              { color: "var(--accent)", data: [320, 380, 420, 410, 450, 480, 520, 560, 580, 620, 690, 720].map(v => v * 1000) },
              { color: "var(--ink-3)", data: [290, 350, 380, 380, 410, 440, 470, 510, 530, 580, 640, 670].map(v => v * 1000), dashed: true },
            ]}
          />
        </div>

        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="h3" style={{ marginBottom: 4 }}>Pending payouts</div>
          <div className="muted tiny" style={{ marginBottom: 18 }}>Next batch: tonight 11:00 UTC</div>
          <div className="display" style={{ fontSize: 44, letterSpacing: "-0.03em" }}>$284,910</div>
          <div className="muted tiny" style={{ marginBottom: 18 }}>across 84 vendors</div>
          <div className="row" style={{ height: 8, background: "var(--surface-3)", borderRadius: 999, overflow: "hidden" }}>
            <span style={{ width: "64%", background: "var(--accent)" }} />
            <span style={{ width: "22%", background: "var(--ink-3)" }} />
            <span style={{ width: "14%", background: "var(--warn)" }} />
          </div>
          <div className="row" style={{ marginTop: 12, gap: 14, fontSize: 11, flexWrap: "wrap" }}>
            <span className="row-tight"><span className="dot" style={{ background: "var(--accent)" }} /> Ready 64%</span>
            <span className="row-tight"><span className="dot" style={{ background: "var(--ink-3)" }} /> Holding 22%</span>
            <span className="row-tight"><span className="dot dot-warn" /> Review 14%</span>
          </div>
        </div>
      </div>

      {/* PAYOUT REQUESTS */}
      <div className="card card-flush" style={{ marginBottom: 24 }}>
        <div className="row between" style={{ padding: "22px 22px 14px" }}>
          <div>
            <div className="h3">Payout requests</div>
            <div className="muted tiny" style={{ marginTop: 4 }}>Approve or decline manual payout requests from vendors.</div>
          </div>
          <div className="row-tight">
            <S.Chip tone="warn">{payouts.filter(p => p.status === "pending").length} pending</S.Chip>
            <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Pending only</S.Btn>
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Vendor</th>
              <th>Requested</th>
              <th>Method</th>
              <th>Balance</th>
              <th className="col-num">Amount</th>
              <th>Status</th>
              <th style={{ width: 200 }} />
            </tr>
          </thead>
          <tbody>
            {payouts.map((p) => (
              <tr key={p.id}>
                <td>
                  <div className="row-tight">
                    <S.Avatar name={p.vendor} size="sm" />
                    <div>
                      <div style={{ fontWeight: 500 }}>{p.vendor}</div>
                      <div className="muted tiny">{p.id} · {p.city}</div>
                    </div>
                  </div>
                </td>
                <td className="mono muted">{p.requested}</td>
                <td><div className="row-tight tiny"><I.card size={12} />{p.method}</div></td>
                <td className="mono">${p.balance.toLocaleString()}</td>
                <td className="col-num mono" style={{ fontWeight: 500 }}>${p.amount.toLocaleString()}</td>
                <td>
                  <S.Chip tone={
                    p.status === "approved" ? "pos" :
                      p.status === "declined" ? "neg" :
                        p.status === "review" ? "warn" : "info"
                  }>{p.status === "pending" ? "Pending" : p.status === "approved" ? "Approved" : p.status === "declined" ? "Declined" : "Review"}</S.Chip>
                </td>
                <td>
                  {p.status === "pending" || p.status === "review" ? (
                    <div className="row-tight">
                      <S.Btn variant="outline" size="sm" style={{ borderColor: "var(--pos)", color: "var(--pos)" }} icon={<I.check size={12} />} onClick={() => updatePayout(p.id, "approved")}>Approve</S.Btn>
                      <S.Btn variant="ghost" size="sm" style={{ color: "var(--neg)" }} onClick={() => updatePayout(p.id, "declined")}>Decline</S.Btn>
                    </div>
                  ) : (
                    <S.Btn variant="ghost" size="sm" onClick={() => updatePayout(p.id, "pending")}>Revert</S.Btn>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* recent transactions kept */}
      <div className="card card-flush">
        <div className="row between" style={{ padding: "22px 22px 14px" }}>
          <div className="h3">Recent transactions</div>
          <S.Btn variant="outline" size="sm">View ledger</S.Btn>
        </div>
        <table className="tbl">
          <thead>
            <tr><th>ID</th><th>Type</th><th>Counterparty</th><th>Reference</th><th>Method</th><th>Status</th><th className="col-num">Amount</th></tr>
          </thead>
          <tbody>
            {TXNS.map((t) => (
              <tr key={t.id}>
                <td className="mono muted">{t.id}</td>
                <td><S.Chip tone={t.tone}>{t.type}</S.Chip></td>
                <td>{t.party}</td>
                <td className="mono tiny muted">{t.ref}</td>
                <td><div className="row-tight tiny"><I.card size={12} /> {t.method}</div></td>
                <td><span className="row-tight"><span className={`dot dot-${t.statusTone}`} />{t.status}</span></td>
                <td className={`col-num mono`} style={{ color: t.amount < 0 ? "var(--neg)" : undefined, fontWeight: 500 }}>
                  {t.amount < 0 ? "−" : "+"}${Math.abs(t.amount).toLocaleString()}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

const PAYOUT_REQUESTS = [
  { id: "PR-9241", vendor: "Maison Color & Co.", city: "Paris", requested: "12m ago", method: "ACH ····4821", balance: 8420.18, amount: 8000, status: "pending" },
  { id: "PR-9240", vendor: "Forest Spa", city: "Reykjavík", requested: "1h ago", method: "Wire ····0019", balance: 14820, amount: 14820, status: "review" },
  { id: "PR-9239", vendor: "Atelier Nails", city: "Brooklyn", requested: "2h ago", method: "ACH ····0019", balance: 6210, amount: 6210, status: "approved" },
  { id: "PR-9238", vendor: "Cut & Co Barber", city: "Berlin", requested: "Yesterday", method: "SEPA ····7710", balance: 3920, amount: 3500, status: "pending" },
  { id: "PR-9237", vendor: "Glow Skin Studio", city: "Lisbon", requested: "2d ago", method: "ACH ····2218", balance: 2180, amount: 2180, status: "declined" },
];

const TXNS = [
  { id: "TX-9241", type: "Payout", tone: "accent", party: "Maison Color & Co.", ref: "PO-2418-001", method: "ACH ····4821", status: "Sent", statusTone: "pos", amount: -8420 },
  { id: "TX-9240", type: "Charge", tone: "pos", party: "Amelia Brooks", ref: "PB-28401", method: "Visa ····2118", status: "Captured", statusTone: "pos", amount: 184 },
  { id: "TX-9239", type: "Refund", tone: "warn", party: "Idris Ahmed", ref: "PB-28405", method: "Visa ····7710", status: "Issued", statusTone: "warn", amount: -142 },
  { id: "TX-9238", type: "Fee", tone: "info", party: "Pamp Net", ref: "PB-28401", method: "Internal", status: "Booked", statusTone: "pos", amount: 14.72 },
  { id: "TX-9237", type: "Payout", tone: "accent", party: "Atelier Nails", ref: "PO-2418-002", method: "ACH ····0019", status: "Pending", statusTone: "warn", amount: -6210 },
];

/* ====================================================================
   ADMIN — SUBSCRIPTIONS
   ==================================================================== */
const CLIENT_PLANS = [
  { id: "c-free", name: "Free", price: 0, period: "mo", duration: "—", subs: 18420, status: "Active",
    features: ["Browse and book any vendor", "Wallet & history", "Standard support"] },
  { id: "c-silver", name: "Silver", price: 9, period: "mo", duration: "Monthly", subs: 6240, status: "Active",
    features: ["5% off every booking", "Priority slots", "$2 monthly credit"] },
  { id: "c-gold", name: "Gold", price: 24, period: "mo", duration: "Monthly", subs: 3210, status: "Active", featured: true,
    features: ["10% off every booking", "Priority slots · 24h early", "$5 monthly credit", "Gold concierge"] },
  { id: "c-platinum", name: "Platinum", price: 49, period: "mo", duration: "Monthly", subs: 561, status: "Active",
    features: ["20% off every booking", "Same-day reschedule free", "$25 monthly credit", "Member events"] },
];

const VENDOR_PLANS = [
  { id: "v-starter", name: "Starter", price: 0, period: "mo", duration: "—", subs: 421, status: "Active",
    features: ["1 location", "30 bookings/mo", "Pamp fees only"] },
  { id: "v-studio", name: "Studio", price: 49, period: "mo", duration: "Monthly", subs: 824, status: "Active", featured: true,
    features: ["3 locations", "Unlimited bookings", "Reduced fees · 3.5%", "Custom branding"] },
  { id: "v-atelier", name: "Atelier", price: 149, period: "mo", duration: "Monthly", subs: 312, status: "Active",
    features: ["Unlimited locations", "Lowest fees · 2.4%", "API access", "Dedicated support"] },
  { id: "v-enterprise", name: "Enterprise", price: null, period: "mo", duration: "Annual contract", subs: 127, status: "Active",
    features: ["Custom contract", "SSO + SAML", "Audit logs", "SLA"] },
];

function AdminSubscriptions() {
  const [tab, setTab] = React.useState("clients");
  const [planFormOpen, setPlanFormOpen] = React.useState(false);
  const [editingPlan, setEditingPlan] = React.useState(null);
  const [confirmDelete, setConfirmDelete] = React.useState(null);
  const [clientPlans, setClientPlans] = React.useState(CLIENT_PLANS);
  const [vendorPlans, setVendorPlans] = React.useState(VENDOR_PLANS);

  const plans = tab === "clients" ? clientPlans : vendorPlans;
  const setPlans = tab === "clients" ? setClientPlans : setVendorPlans;

  const openNew = () => { setEditingPlan(null); setPlanFormOpen(true); };
  const openEdit = (p) => { setEditingPlan(p); setPlanFormOpen(true); };
  const toggleStatus = (id) => setPlans(plans.map(p => p.id === id ? { ...p, status: p.status === "Active" ? "Inactive" : "Active" } : p));
  const removePlan = (id) => { setPlans(plans.map(p => p)); setPlans(plans.filter(p => p.id !== id)); setConfirmDelete(null); };
  const savePlan = (next) => {
    if (editingPlan) setPlans(plans.map(p => p.id === editingPlan.id ? { ...p, ...next } : p));
    else setPlans([...plans, { ...next, id: tab[0] + "-" + Date.now(), subs: 0, status: "Active" }]);
    setPlanFormOpen(false);
  };

  const totalSubs = plans.reduce((s, p) => s + p.subs, 0);
  const totalRev = plans.reduce((s, p) => s + (p.price || 0) * p.subs, 0);

  return (
    <div className="page-enter">
      <window.DemoBanner feature="subscription plans (live wiring next phase)" />
      <S.PageHead
        eyebrow={`${tab === "clients" ? "Client" : "Vendor"} plans · ${plans.length} active`}
        title="Subscriptions"
        sub="Manage Pamp plans for clients and vendors — pricing, features, and lifecycle."
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.download size={14} />}>Export</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.plus size={14} />} onClick={openNew}>New plan</S.Btn>
        </>}
      />

      <div className="grid-4" style={{ marginBottom: 20 }}>
        <S.Metric hero label={tab === "clients" ? "Member MRR" : "Vendor MRR"} value={`$${(totalRev / 1000).toFixed(1)}k`} delta="+8.2%" />
        <S.Metric label="Active subscribers" value={totalSubs.toLocaleString()} delta="+1.2k" />
        <S.Metric label="Trial → paid" value={tab === "clients" ? "38.4%" : "42.1%"} delta="+3.4pp" />
        <S.Metric label="Churn" value="2.1%" delta="−0.4pp" deltaTone="pos" />
      </div>

      {/* Segmented tabs */}
      <div className="row" style={{ marginBottom: 20 }}>
        <div className="segmented">
          <button className={tab === "clients" ? "active" : ""} onClick={() => setTab("clients")}>
            Clients <span className="muted" style={{ marginLeft: 6, fontSize: 11 }}>{clientPlans.length}</span>
          </button>
          <button className={tab === "vendors" ? "active" : ""} onClick={() => setTab("vendors")}>
            Vendors <span className="muted" style={{ marginLeft: 6, fontSize: 11 }}>{vendorPlans.length}</span>
          </button>
        </div>
      </div>

      {/* Plans table */}
      <div className="card card-flush">
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: "22%" }}>Plan</th>
              <th>Price</th>
              <th>Duration</th>
              <th style={{ width: "32%" }}>Features</th>
              <th>Active subs</th>
              <th>Status</th>
              <th style={{ width: 140 }} />
            </tr>
          </thead>
          <tbody>
            {plans.map((p) => (
              <tr key={p.id}>
                <td>
                  <div className="row-tight" style={{ gap: 10 }}>
                    <span style={{
                      width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                      background: p.featured ? "var(--accent-soft)" : "var(--surface-3)",
                      color: p.featured ? "var(--accent-ink)" : "var(--ink-2)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}>
                      {tab === "clients" ? <I.crown size={16} /> : <I.store size={16} />}
                    </span>
                    <div>
                      <div className="row-tight" style={{ gap: 6 }}>
                        <span style={{ fontWeight: 500 }}>{p.name}</span>
                        {p.featured && <S.Chip tone="accent">Featured</S.Chip>}
                      </div>
                      <div className="muted tiny" style={{ marginTop: 2 }}>ID · {p.id}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <div style={{ fontWeight: 500 }}>
                    {p.price === null ? "Custom" : p.price === 0 ? "Free" : `$${p.price}`}
                    {p.price ? <span className="muted" style={{ fontWeight: 400 }}> /{p.period}</span> : null}
                  </div>
                </td>
                <td className="muted">{p.duration}</td>
                <td>
                  <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
                    {p.features.slice(0, 3).map((f, i) => (
                      <span key={i} className="chip" style={{ height: 22, fontSize: 11 }}>{f}</span>
                    ))}
                    {p.features.length > 3 && <span className="muted tiny">+{p.features.length - 3} more</span>}
                  </div>
                </td>
                <td><span style={{ fontWeight: 500 }}>{p.subs.toLocaleString()}</span></td>
                <td><S.Chip tone={p.status === "Active" ? "pos" : ""}>{p.status}</S.Chip></td>
                <td>
                  <div className="row-tight" style={{ gap: 4, justifyContent: "flex-end" }}>
                    <S.IconBtn title="Edit" onClick={() => openEdit(p)}><I.settings size={15} /></S.IconBtn>
                    <S.IconBtn title={p.status === "Active" ? "Deactivate" : "Activate"} onClick={() => toggleStatus(p.id)}>
                      {p.status === "Active" ? <I.eyeOff size={15} /> : <I.eye size={15} />}
                    </S.IconBtn>
                    <S.IconBtn title="Delete" onClick={() => setConfirmDelete(p)}><I.x size={15} /></S.IconBtn>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <PlanFormModal
        open={planFormOpen}
        plan={editingPlan}
        audience={tab}
        onClose={() => setPlanFormOpen(false)}
        onSave={savePlan}
      />
      <window.M.ConfirmModal
        open={!!confirmDelete}
        onClose={() => setConfirmDelete(null)}
        onConfirm={() => removePlan(confirmDelete?.id)}
        title={`Delete ${confirmDelete?.name}?`}
        body="Subscribers on this plan will be moved to the closest equivalent. This cannot be undone."
        confirmLabel="Delete plan"
        danger
        icon={<I.x />}
      />
    </div>
  );
}

function PlanFormModal({ open, plan, audience, onClose, onSave }) {
  const [data, setData] = React.useState({ name: "", price: "", duration: "Monthly", features: "" });
  React.useEffect(() => {
    if (open) setData(plan ? {
      name: plan.name, price: plan.price === null ? "" : String(plan.price),
      duration: plan.duration || "Monthly", features: plan.features.join("\n"),
    } : { name: "", price: "", duration: "Monthly", features: "" });
  }, [open, plan]);
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const submit = () => {
    onSave({
      name: data.name || "Untitled",
      price: data.price === "" ? null : Number(data.price),
      period: "mo",
      duration: data.duration,
      features: data.features.split("\n").map(s => s.trim()).filter(Boolean),
    });
  };
  return (
    <window.M.Modal open={open} onClose={onClose} size="lg"
      icon={<I.crown />} title={plan ? `Edit ${plan.name}` : `Create ${audience === "clients" ? "client" : "vendor"} plan`}
      subtitle={plan ? "Changes apply to new subscribers immediately." : "Define pricing, duration, and what's included."}
      footer={<>
        <S.Btn variant="ghost" onClick={onClose}>Cancel</S.Btn>
        <S.Btn variant="primary" iconRight={<I.check size={14} />} onClick={submit}>{plan ? "Save changes" : "Create plan"}</S.Btn>
      </>}
    >
      <window.M.FormGrid>
        <window.M.Field label="Plan name">
          <window.M.TextField value={data.name} onChange={(v) => set("name", v)} placeholder="e.g. Gold" />
        </window.M.Field>
        <window.M.Field label="Price (USD)" hint="Leave blank for custom pricing.">
          <window.M.TextField value={data.price} onChange={(v) => set("price", v)} placeholder="49" />
        </window.M.Field>
        <window.M.Field full label="Duration">
          <window.M.Segmented value={data.duration} onChange={(v) => set("duration", v)}
            options={[
              { value: "Monthly", label: "Monthly" },
              { value: "Annual", label: "Annual" },
              { value: "Annual contract", label: "Custom contract" },
            ]} />
        </window.M.Field>
        <window.M.Field full label="Features" hint="One feature per line.">
          <window.M.Textarea rows={6} value={data.features} onChange={(v) => set("features", v)} placeholder={"Reduced fees · 3.5%\nCustom branding\nPriority support"} />
        </window.M.Field>
      </window.M.FormGrid>
    </window.M.Modal>
  );
}

/* ====================================================================
   STUBS — payments / reports / support / coupons / notifs / settings
   ==================================================================== */
function StubScreen({ title, eyebrow, sub, children }) {
  return (
    <div className="page-enter">
      <S.PageHead eyebrow={eyebrow} title={title} sub={sub} />
      {children}
    </div>
  );
}

function AdminPayments() {
  const [transferOpen, setTransferOpen] = React.useState(false);
  return (
    <div className="page-enter">
      <window.DemoBanner feature="payments & transactions (live wiring next phase)" />
      <S.PageHead
        eyebrow="Payment center · all rails"
        title="Payment center"
        sub="Audit every transaction and move funds between platform accounts."
        right={<S.Btn variant="primary" size="sm" icon={<I.export size={14} />} onClick={() => setTransferOpen(true)}>Transfer funds</S.Btn>}
      />

      <div className="grid-4" style={{ marginBottom: 24 }}>
        <S.Metric hero label="Captures (today)" value="$182k" delta="+4%" />
        <S.Metric label="Success rate" value="99.6%" delta="+0.1pp" />
        <S.Metric label="Disputes open" value="14" delta="−2" deltaTone="pos" />
        <S.Metric label="Avg. ticket" value="$78" delta="+2.4%" />
      </div>

      <PaymentsTransactions />

      <TransferFundsModal open={transferOpen} onClose={() => setTransferOpen(false)} />
    </div>
  );
}

function PaymentsPayroll_REMOVED() {
  return (
    <>
      <div className="grid-12" style={{ marginBottom: 24 }}>
        <div className="card" style={{ gridColumn: "span 6", background: "var(--ink)", color: "var(--bg)", borderColor: "transparent", position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", inset: 0, opacity: 0.4, background: "radial-gradient(circle at 80% 20%, var(--accent) 0%, transparent 50%)" }} />
          <div style={{ position: "relative" }}>
            <div className="eyebrow" style={{ color: "oklch(75% 0.02 145)" }}>Next payroll run</div>
            <div className="display" style={{ fontSize: 44, color: "var(--bg)", marginTop: 8 }}>$148,420</div>
            <div className="muted tiny" style={{ color: "oklch(75% 0.02 145)" }}>12 staff · scheduled Feb 15 · ACH</div>
            <div className="row" style={{ marginTop: 24, gap: 8 }}>
              <S.Btn variant="primary" icon={<I.card size={14} />}>Run payroll</S.Btn>
              <S.Btn variant="ghost" style={{ color: "var(--bg)", background: "oklch(100% 0 0 / 0.10)" }}>Edit schedule</S.Btn>
            </div>
          </div>
        </div>
        <div className="card" style={{ gridColumn: "span 3" }}>
          <div className="eyebrow">YTD payroll</div>
          <div className="display" style={{ fontSize: 32, marginTop: 8 }}>$1.62M</div>
          <div className="row-tight" style={{ marginTop: 10 }}>
            <S.Chip tone="pos">+18%</S.Chip>
            <span className="muted tiny">vs 2024</span>
          </div>
        </div>
        <div className="card" style={{ gridColumn: "span 3" }}>
          <div className="eyebrow">Headcount</div>
          <div className="display" style={{ fontSize: 32, marginTop: 8 }}>12</div>
          <div className="row-tight" style={{ marginTop: 10 }}>
            <S.Chip>4 contract · 8 full-time</S.Chip>
          </div>
        </div>
      </div>

      <div className="card card-flush">
        <div className="row between" style={{ padding: "22px 22px 14px" }}>
          <div className="h3">Payroll history</div>
          <S.Btn variant="outline" size="sm" icon={<I.download size={12} />}>Statements</S.Btn>
        </div>
        <table className="tbl">
          <thead><tr><th>Run date</th><th>Period</th><th>Staff</th><th>Gross</th><th>Taxes</th><th className="col-num">Net</th><th>Status</th></tr></thead>
          <tbody>
            {[
              { d: "Feb 1, 2026", p: "Jan 15 – Jan 31", s: 12, g: 142_180, t: 38_420, n: 103_760, st: "Paid", tone: "pos" },
              { d: "Jan 15, 2026", p: "Jan 1 – Jan 14", s: 12, g: 138_920, t: 37_540, n: 101_380, st: "Paid", tone: "pos" },
              { d: "Jan 1, 2026", p: "Dec 15 – Dec 31", s: 11, g: 132_410, t: 35_710, n: 96_700, st: "Paid", tone: "pos" },
              { d: "Dec 15, 2025", p: "Dec 1 – Dec 14", s: 11, g: 128_640, t: 34_730, n: 93_910, st: "Paid", tone: "pos" },
            ].map((r, i) => (
              <tr key={i}>
                <td className="mono">{r.d}</td>
                <td className="muted tiny">{r.p}</td>
                <td className="mono">{r.s}</td>
                <td className="mono">${r.g.toLocaleString()}</td>
                <td className="mono muted">${r.t.toLocaleString()}</td>
                <td className="col-num mono" style={{ fontWeight: 500 }}>${r.n.toLocaleString()}</td>
                <td><S.Chip tone={r.tone}>{r.st}</S.Chip></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function PaymentsTransactions() {
  return (
    <div className="card card-flush">
      <div className="row" style={{ padding: 16, gap: 10 }}>
        <S.Input icon={<I.search size={15} />} placeholder="Search by ID, vendor, or amount…" style={{ flex: 1, maxWidth: 360 }} />
        <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Type: All</S.Btn>
        <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Last 24h</S.Btn>
        <div className="spacer" />
        <S.Btn variant="outline" size="sm" icon={<I.download size={12} />}>Export</S.Btn>
      </div>
      <table className="tbl">
        <thead>
          <tr><th>ID</th><th>Type</th><th>Counterparty</th><th>Reference</th><th>Method</th><th>Status</th><th className="col-num">Amount</th></tr>
        </thead>
        <tbody>
          {TXNS.concat(TXNS.map((t, i) => ({ ...t, id: t.id + "-" + i }))).slice(0, 12).map((t, i) => (
            <tr key={t.id + i}>
              <td className="mono muted">{t.id}</td>
              <td><S.Chip tone={t.tone}>{t.type}</S.Chip></td>
              <td>{t.party}</td>
              <td className="mono tiny muted">{t.ref}</td>
              <td><div className="row-tight tiny"><I.card size={12} /> {t.method}</div></td>
              <td><span className="row-tight"><span className={`dot dot-${t.statusTone}`} />{t.status}</span></td>
              <td className={`col-num mono`} style={{ color: t.amount < 0 ? "var(--neg)" : undefined, fontWeight: 500 }}>
                {t.amount < 0 ? "−" : "+"}${Math.abs(t.amount).toLocaleString()}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function TransferFundsModal({ open, onClose }) {
  const [data, setData] = React.useState({ from: "operating", to: "reserve", amount: "", reason: "", schedule: "now" });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  return (
    <window.M.Modal open={open} onClose={onClose} size="lg"
      icon={<I.export />} title="Transfer funds"
      subtitle="Move money between platform accounts. Audit logged automatically."
      footer={<>
        <S.Btn variant="ghost" onClick={onClose}>Cancel</S.Btn>
        <S.Btn variant="primary" iconRight={<I.check size={14} />} onClick={onClose}>Authorize transfer</S.Btn>
      </>}
    >
      <window.M.FormGrid>
        <window.M.Field label="From account">
          <window.M.RadioCards value={data.from} onChange={(v) => set("from", v)}
            options={[
              { value: "operating", label: "Operating", desc: "Balance $1.24M" },
              { value: "reserve", label: "Reserve", desc: "Balance $4.82M" },
              { value: "escrow", label: "Escrow", desc: "Balance $284k" },
            ]} />
        </window.M.Field>
        <window.M.Field label="To account">
          <window.M.RadioCards value={data.to} onChange={(v) => set("to", v)}
            options={[
              { value: "operating", label: "Operating", desc: "Balance $1.24M" },
              { value: "reserve", label: "Reserve", desc: "Balance $4.82M" },
              { value: "payroll", label: "Payroll", desc: "Balance $148k" },
            ]} />
        </window.M.Field>
        <window.M.Field full label="Amount">
          <window.M.TextField icon={<span style={{ fontFamily: "var(--font-mono)" }}>$</span>} value={data.amount} onChange={(v) => set("amount", v)} placeholder="0.00" />
        </window.M.Field>
        <window.M.Field full label="Reason / memo" hint="Visible in the audit log.">
          <window.M.Textarea value={data.reason} onChange={(v) => set("reason", v)} placeholder="e.g. Top up payroll account for Feb run" />
        </window.M.Field>
        <window.M.Field full label="When">
          <window.M.Segmented value={data.schedule} onChange={(v) => set("schedule", v)}
            options={[{ value: "now", label: "Immediately" }, { value: "later", label: "Schedule" }]} />
        </window.M.Field>
      </window.M.FormGrid>
    </window.M.Modal>
  );
}

function AdminReports() {
  const [range, setRange] = React.useState("90d");
  return (
    <div className="page-enter">
      <window.DemoBanner feature="reports & analytics (live wiring next phase)" />
      <S.PageHead
        eyebrow="Last 90 days · all regions"
        title="Reports & analytics"
        sub="Health, growth, and risk across users, vendors, and money."
        right={<>
          <div className="row-tight" style={{ background: "var(--surface-3)", padding: 3, borderRadius: 999 }}>
            {[{ k: "7d", l: "7d" }, { k: "30d", l: "30d" }, { k: "90d", l: "90d" }, { k: "ytd", l: "YTD" }].map(r => (
              <button key={r.k} onClick={() => setRange(r.k)}
                className={`btn btn-sm ${range === r.k ? "btn-primary" : "btn-ghost"}`}>{r.l}</button>
            ))}
          </div>
          <S.Btn variant="outline" size="sm" icon={<I.download size={14} />}>Export PDF</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.plus size={14} />}>New report</S.Btn>
        </>}
      />

      {/* hero KPI strip */}
      <div className="grid-4" style={{ marginBottom: 24 }}>
        <S.Metric hero label="Gross volume" value="$8.4M" delta="+34% YoY" />
        <S.Metric label="Net revenue (Pamp)" value="$662k" delta="+38%" />
        <S.Metric label="Take rate" value="7.92%" delta="+0.2pp" />
        <S.Metric label="Active vendors" value="1,842" delta="+162" />
      </div>

      <div className="grid-12" style={{ marginBottom: 24 }}>
        {/* Revenue trend */}
        <div className="card" style={{ gridColumn: "span 8" }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div>
              <div className="eyebrow">Revenue trend</div>
              <div className="h3" style={{ marginTop: 4 }}>GMV vs Pamp net · last 12 months</div>
            </div>
            <div className="row" style={{ gap: 14 }}>
              <div className="row-tight"><span className="dot" style={{ background: "var(--accent)" }} /><span className="tiny muted">GMV</span></div>
              <div className="row-tight"><span className="dot" style={{ background: "var(--ink-3)" }} /><span className="tiny muted">Pamp net</span></div>
            </div>
          </div>
          <S.LineChart
            height={260}
            currency
            labels={["Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan"]}
            series={[
              { color: "var(--accent)", data: [420, 480, 520, 540, 620, 640, 700, 740, 760, 800, 820, 870].map(v => v * 1000) },
              { color: "var(--ink-3)", data: [32, 38, 41, 43, 49, 51, 56, 59, 60, 64, 65, 68].map(v => v * 1000), dashed: true },
            ]}
          />
        </div>

        {/* Booking mix by region */}
        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Revenue by region</div>
          <div className="h3" style={{ marginBottom: 18 }}>Where the money is</div>
          <div className="row" style={{ justifyContent: "center", marginBottom: 18 }}>
            <S.Ring value={68} size={150} stroke={14} label="42" sub="countries" />
          </div>
          <div className="col" style={{ gap: 10 }}>
            {[
              { l: "Europe", v: 42, n: "$3.5M", c: "var(--accent)" },
              { l: "North America", v: 31, n: "$2.6M", c: "var(--ink)" },
              { l: "Asia & Pacific", v: 16, n: "$1.3M", c: "var(--info)" },
              { l: "LATAM", v: 7, n: "$582k", c: "var(--warn)" },
              { l: "Other", v: 4, n: "$308k", c: "var(--ink-3)" },
            ].map((r) => (
              <div key={r.l} className="row" style={{ gap: 10 }}>
                <span className="dot" style={{ background: r.c }} />
                <span style={{ flex: 1, fontSize: 13 }}>{r.l}</span>
                <span className="mono tiny muted">{r.v}%</span>
                <span className="mono" style={{ fontSize: 12, width: 60, textAlign: "right" }}>{r.n}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Cohort retention */}
        <div className="card" style={{ gridColumn: "span 12" }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div>
              <div className="eyebrow">Retention</div>
              <div className="h3" style={{ marginTop: 4 }}>Cohort retention · clients</div>
            </div>
            <div className="row-tight">
              <S.Chip>Average M3 retention: 56%</S.Chip>
              <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>By acquisition channel</S.Btn>
            </div>
          </div>
          <CohortGrid />
        </div>

        {/* Funnels */}
        <div className="card" style={{ gridColumn: "span 6" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Funnel</div>
          <div className="h3" style={{ marginBottom: 18 }}>Client signup → first booking</div>
          <FunnelChart steps={[
            { label: "Discover view", count: 184_280, rate: 100 },
            { label: "Vendor profile open", count: 98_420, rate: 53.4 },
            { label: "Booking flow start", count: 42_180, rate: 22.9 },
            { label: "Booking confirmed", count: 18_640, rate: 10.1 },
          ]} />
        </div>

        <div className="card" style={{ gridColumn: "span 6" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Funnel</div>
          <div className="h3" style={{ marginBottom: 18 }}>Vendor onboarding → first payout</div>
          <FunnelChart steps={[
            { label: "Vendor sign-ups", count: 2_840, rate: 100 },
            { label: "Profile completed", count: 2_180, rate: 76.8 },
            { label: "First service listed", count: 1_920, rate: 67.6 },
            { label: "First booking", count: 1_640, rate: 57.7 },
            { label: "First payout", count: 1_580, rate: 55.6 },
          ]} />
        </div>

        {/* Operational */}
        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Operational</div>
          <div className="h3" style={{ marginBottom: 18 }}>No-show rate</div>
          <div className="display" style={{ fontSize: 44, letterSpacing: "-0.03em" }}>2.8%</div>
          <div className="row-tight" style={{ marginTop: 8, marginBottom: 24 }}>
            <S.Chip tone="pos">−0.4pp</S.Chip>
            <span className="muted tiny">vs Q4</span>
          </div>
          <S.BarChart
            data={[3.4, 3.2, 2.9, 2.8, 2.7, 2.6]}
            labels={["Sep", "Oct", "Nov", "Dec", "Jan", "Feb"]}
            activeIndex={5}
            height={120}
          />
        </div>

        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Risk</div>
          <div className="h3" style={{ marginBottom: 18 }}>Dispute rate</div>
          <div className="display" style={{ fontSize: 44, letterSpacing: "-0.03em" }}>0.14%</div>
          <div className="row-tight" style={{ marginTop: 8, marginBottom: 24 }}>
            <S.Chip tone="pos">Within target</S.Chip>
          </div>
          <div className="col" style={{ gap: 8 }}>
            <DistRow label="Service quality" pct={48} c="var(--accent)" />
            <DistRow label="No-show by vendor" pct={28} c="var(--ink)" />
            <DistRow label="Wrong charge" pct={14} c="var(--warn)" />
            <DistRow label="Other" pct={10} c="var(--ink-3)" />
          </div>
        </div>

        <div className="card" style={{ gridColumn: "span 4" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Marketing</div>
          <div className="h3" style={{ marginBottom: 18 }}>CAC / LTV</div>
          <div className="row" style={{ gap: 28 }}>
            <div>
              <div className="display" style={{ fontSize: 32 }}>$18</div>
              <div className="muted tiny">Client CAC</div>
            </div>
            <div>
              <div className="display" style={{ fontSize: 32 }}>$248</div>
              <div className="muted tiny">12-mo LTV</div>
            </div>
            <div>
              <div className="display" style={{ fontSize: 32, color: "var(--pos)" }}>13.8×</div>
              <div className="muted tiny">Ratio</div>
            </div>
          </div>
          <div className="divider" style={{ margin: "20px 0" }} />
          <div className="col" style={{ gap: 8 }}>
            <DistRow label="Referral / influencer" pct={42} c="var(--accent)" />
            <DistRow label="Organic" pct={28} c="var(--ink)" />
            <DistRow label="Paid social" pct={18} c="var(--info)" />
            <DistRow label="Partnerships" pct={12} c="var(--warn)" />
          </div>
        </div>

        {/* Saved reports */}
        <div className="card card-flush" style={{ gridColumn: "span 12" }}>
          <div className="row between" style={{ padding: "22px 22px 14px" }}>
            <div>
              <div className="h3">Saved reports</div>
              <div className="muted tiny" style={{ marginTop: 4 }}>Pinned and scheduled reports your team subscribes to.</div>
            </div>
            <S.Btn variant="outline" size="sm" icon={<I.plus size={12} />}>Add report</S.Btn>
          </div>
          <table className="tbl">
            <thead><tr><th>Name</th><th>Type</th><th>Schedule</th><th>Recipients</th><th>Last run</th><th /></tr></thead>
            <tbody>
              {[
                { n: "Weekly executive summary", t: "Cross-functional", s: "Mon 09:00 UTC", r: "Leadership (8)", l: "2d ago" },
                { n: "Vendor risk watchlist", t: "Risk", s: "Daily", r: "Trust & safety (3)", l: "12h ago" },
                { n: "Marketing channel ROI", t: "Marketing", s: "Bi-weekly", r: "Growth (4)", l: "1w ago" },
                { n: "Refund & dispute deep dive", t: "Finance", s: "Monthly", r: "Finance (2)", l: "3w ago" },
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 500 }}>{r.n}</td>
                  <td><S.Chip>{r.t}</S.Chip></td>
                  <td className="muted">{r.s}</td>
                  <td className="muted">{r.r}</td>
                  <td className="muted tiny">{r.l}</td>
                  <td><S.IconBtn><I.ellipsis size={16} /></S.IconBtn></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function FunnelChart({ steps }) {
  const max = steps[0].count;
  return (
    <div className="col" style={{ gap: 10 }}>
      {steps.map((s, i) => (
        <div key={i}>
          <div className="row between" style={{ marginBottom: 4 }}>
            <span style={{ fontSize: 13 }}>{s.label}</span>
            <span className="row-tight">
              <span className="mono tiny" style={{ fontWeight: 500 }}>{s.count.toLocaleString()}</span>
              <span className="mono tiny muted">· {s.rate.toFixed(1)}%</span>
            </span>
          </div>
          <div style={{ height: 10, background: "var(--surface-3)", borderRadius: 6, overflow: "hidden" }}>
            <div style={{
              width: `${(s.count / max) * 100}%`, height: "100%",
              background: i === 0 ? "var(--accent)" : i === steps.length - 1 ? "var(--ink)" : "var(--accent-soft)",
              transition: "width 0.5s ease",
            }} />
          </div>
        </div>
      ))}
    </div>
  );
}

function DistRow({ label, pct, c }) {
  return (
    <div>
      <div className="row between" style={{ marginBottom: 4 }}>
        <span className="tiny">{label}</span>
        <span className="mono tiny">{pct}%</span>
      </div>
      <div className="bar"><span style={{ width: `${pct}%`, background: c }} /></div>
    </div>
  );
}

function CohortGrid() {
  const months = ["Aug", "Sep", "Oct", "Nov", "Dec", "Jan"];
  const data = [
    [100, 64, 52, 44, 38, 34],
    [100, 68, 56, 48, 42, null],
    [100, 70, 58, 50, null, null],
    [100, 72, 60, null, null, null],
    [100, 74, null, null, null, null],
    [100, null, null, null, null, null],
  ];
  return (
    <div>
      <div className="row" style={{ gap: 4, marginBottom: 4 }}>
        <div style={{ width: 80 }} />
        {months.map((m, i) => <div key={m} style={{ flex: 1, textAlign: "center" }} className="mono tiny muted">M{i}</div>)}
      </div>
      {data.map((row, i) => (
        <div key={i} className="row" style={{ gap: 4, marginBottom: 4 }}>
          <div style={{ width: 80 }} className="mono tiny muted">{months[i]} ’25</div>
          {row.map((v, j) => (
            <div key={j} style={{
              flex: 1, height: 40, borderRadius: 6, display: "flex", alignItems: "center", justifyContent: "center",
              background: v == null ? "var(--surface-3)" : `oklch(${95 - v * 0.5}% ${0.04 + v * 0.001} 290)`,
              color: v == null ? "var(--ink-4)" : v > 60 ? "white" : "var(--ink)",
              fontSize: 12, fontFamily: "var(--font-mono)",
            }}>{v == null ? "—" : `${v}%`}</div>
          ))}
        </div>
      ))}
    </div>
  );
}

function AdminSupport() {
  const [filter, setFilter] = React.useState("all");
  const [selected, setSelected] = React.useState(null);
  const filtered = filter === "all" ? SUPPORT_TICKETS :
    filter === "urgent" ? SUPPORT_TICKETS.filter(t => t.priority === "Urgent") :
      filter === "mine" ? SUPPORT_TICKETS.filter(t => t.agent === "Mira J.") :
        SUPPORT_TICKETS.filter(t => t.status === filter);

  return (
    <div className="page-enter">
      <window.DemoBanner feature="support tickets (live wiring next phase)" />
      <S.PageHead
        eyebrow="Inbox · 12 open · 2 urgent"
        title="Support & help"
        sub="Tickets from clients and vendors. Knowledge base. Agent performance."
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.help size={14} />}>Knowledge base</S.Btn>
        </>}
      />

      <div className="grid-4" style={{ marginBottom: 24 }}>
        <S.Metric hero label="Open tickets" value="12" delta="−4" deltaTone="pos" />
        <S.Metric label="Median first response" value="4m 12s" delta="−42s" deltaTone="pos" />
        <S.Metric label="SLA met" value="98.4%" delta="+0.6pp" />
        <S.Metric label="CSAT" value="4.78" delta="+0.04" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: selected ? "1fr 400px" : "1fr", gap: 20, alignItems: "flex-start" }}>
        <div className="card card-flush">
          <div className="row" style={{ padding: 16, gap: 8, borderBottom: "1px solid var(--border)", flexWrap: "wrap" }}>
            {[
              { k: "all", l: "All", n: SUPPORT_TICKETS.length },
              { k: "Open", l: "Open", n: SUPPORT_TICKETS.filter(t => t.status === "Open").length },
              { k: "In progress", l: "In progress", n: SUPPORT_TICKETS.filter(t => t.status === "In progress").length },
              { k: "Waiting", l: "Waiting", n: SUPPORT_TICKETS.filter(t => t.status === "Waiting").length },
              { k: "Resolved", l: "Resolved", n: SUPPORT_TICKETS.filter(t => t.status === "Resolved").length },
              { k: "urgent", l: "Urgent", n: SUPPORT_TICKETS.filter(t => t.priority === "Urgent").length },
            ].map(f => (
              <button key={f.k} onClick={() => setFilter(f.k)}
                className={`btn btn-sm ${filter === f.k ? "btn-primary" : "btn-outline"}`}>
                {f.l} <span className="mono tiny" style={{ marginLeft: 4, opacity: 0.6 }}>{f.n}</span>
              </button>
            ))}
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Ticket</th>
                <th>From</th>
                <th>Subject</th>
                <th>Priority</th>
                <th>Agent</th>
                <th>Updated</th>
                <th />
              </tr>
            </thead>
            <tbody>
              {filtered.map((t) => (
                <tr key={t.id} onClick={() => setSelected(t)} style={{ cursor: "pointer", background: selected?.id === t.id ? "var(--accent-soft)" : undefined }}>
                  <td className="mono muted">{t.id}</td>
                  <td>
                    <div className="row-tight">
                      <S.Avatar name={t.from} size="sm" />
                      <div>
                        <div style={{ fontWeight: 500, fontSize: 13 }}>{t.from}</div>
                        <div className="muted tiny">{t.fromKind}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div style={{ fontWeight: 500 }}>{t.subject}</div>
                    <div className="muted tiny" style={{ maxWidth: 280, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.preview}</div>
                  </td>
                  <td><S.Chip tone={t.priority === "Urgent" ? "neg" : t.priority === "Normal" ? "info" : "warn"}>{t.priority}</S.Chip></td>
                  <td>{t.agent === "—" ? <span className="muted tiny">Unassigned</span> : t.agent}</td>
                  <td className="muted tiny">{t.updated}</td>
                  <td><S.IconBtn><I.chevR size={14} /></S.IconBtn></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {selected && <TicketDetail t={selected} onClose={() => setSelected(null)} />}
      </div>
    </div>
  );
}

const SUPPORT_TICKETS = [
  { id: "T-8201", from: "Forest Spa", fromKind: "Vendor · Atelier plan", subject: "Payout not received for Feb 1 batch", preview: "We expected $14,820 from PR-9240. ACH says pending but the bank has nothing yet.", priority: "Urgent", agent: "Mira J.", updated: "12m ago", status: "Open", channel: "Email", messages: 3 },
  { id: "T-8198", from: "Amelia Brooks", fromKind: "Client · Gold tier", subject: "Refund for cancelled appointment", preview: "Hi, Maison Color cancelled last minute and I was charged.", priority: "Normal", agent: "Eli R.", updated: "1h ago", status: "In progress", channel: "In-app", messages: 4 },
  { id: "T-8195", from: "Cut & Co Barber", fromKind: "Vendor · Studio plan", subject: "Staff invite email not arriving", preview: "Invited two stylists yesterday, neither got the email. Spam isn’t the issue.", priority: "Normal", agent: "—", updated: "2h ago", status: "Open", channel: "Email", messages: 1 },
  { id: "T-8191", from: "Glow Skin Studio", fromKind: "Vendor · Starter plan", subject: "Cannot upload service photos > 5MB", preview: "I’m trying to add new photos to my gallery and they keep failing.", priority: "Low", agent: "Mira J.", updated: "4h ago", status: "Waiting", channel: "In-app", messages: 2 },
  { id: "T-8188", from: "Sofia Romano", fromKind: "Client · Platinum tier", subject: "Loyalty points missing after last booking", preview: "Spent $285 at Maison Color but my balance didn’t move.", priority: "Normal", agent: "Eli R.", updated: "Yesterday", status: "In progress", channel: "Email", messages: 2 },
  { id: "T-8184", from: "Atelier Nails", fromKind: "Vendor · Studio plan", subject: "Tax export for accountant", preview: "I need the 2025 statement in CSV format.", priority: "Low", agent: "Olu A.", updated: "2d ago", status: "Resolved", channel: "Email", messages: 6 },
];

function TicketDetail({ t, onClose }) {
  return (
    <div className="card" style={{ padding: 0, position: "sticky", top: 0 }}>
      <div style={{ padding: 22, borderBottom: "1px solid var(--border)" }}>
        <div className="row between">
          <div className="eyebrow">{t.id} · {t.channel}</div>
          <S.IconBtn onClick={onClose}><I.x size={14} /></S.IconBtn>
        </div>
        <div className="display" style={{ fontSize: 18, marginTop: 8, letterSpacing: "-0.015em", lineHeight: 1.25 }}>{t.subject}</div>
        <div className="row" style={{ marginTop: 12, gap: 6 }}>
          <S.Chip tone={t.priority === "Urgent" ? "neg" : t.priority === "Normal" ? "info" : "warn"}>{t.priority}</S.Chip>
          <S.Chip>{t.status}</S.Chip>
        </div>
      </div>

      <div style={{ padding: 22, borderBottom: "1px solid var(--border)" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>From</div>
        <div className="row" style={{ gap: 12 }}>
          <S.Avatar name={t.from} size="lg" />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 500 }}>{t.from}</div>
            <div className="muted tiny">{t.fromKind}</div>
          </div>
        </div>
        <div className="row" style={{ marginTop: 12, gap: 6 }}>
          <S.Btn variant="outline" size="sm" icon={<I.users size={12} />} style={{ flex: 1 }}>Profile</S.Btn>
          <S.Btn variant="outline" size="sm" icon={<I.mail size={12} />} style={{ flex: 1 }}>Email</S.Btn>
        </div>
      </div>

      <div style={{ padding: 22, borderBottom: "1px solid var(--border)" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>Thread · {t.messages} messages</div>
        <div className="col" style={{ gap: 10 }}>
          <div style={{ padding: 12, background: "var(--surface-2)", borderRadius: 10, fontSize: 13, lineHeight: 1.5 }}>
            <div className="row between" style={{ marginBottom: 4 }}>
              <span style={{ fontSize: 12, fontWeight: 500 }}>{t.from}</span>
              <span className="muted tiny">{t.updated}</span>
            </div>
            {t.preview}
          </div>
          {t.messages > 1 && <div className="muted tiny" style={{ textAlign: "center" }}>+ {t.messages - 1} earlier message{t.messages > 2 ? "s" : ""}</div>}
        </div>
      </div>

      <div style={{ padding: 22 }}>
        <textarea className="text-input" rows={4} placeholder="Reply to this ticket… Markdown supported." />
        <div className="row" style={{ marginTop: 10, gap: 6 }}>
          <S.Btn variant="ghost" size="sm" icon={<I.export size={12} />}>Attach</S.Btn>
          <S.Btn variant="ghost" size="sm" iconRight={<I.chevD size={12} />}>Template</S.Btn>
          <div className="spacer" />
          <S.Btn variant="outline" size="sm">Mark resolved</S.Btn>
          <S.Btn variant="primary" size="sm" iconRight={<I.arrowR size={12} />}>Send reply</S.Btn>
        </div>
      </div>
    </div>
  );
}

function AdminCoupons() {
  const [open, setOpen] = React.useState(false);
  return (
    <div className="page-enter">
      <window.DemoBanner feature="coupons (live wiring next phase)" />
      <S.PageHead eyebrow="14 active campaigns" title="Coupons" sub="Promo codes, gift cards, referral incentives."
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.filter size={14} />}>Filter</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.plus size={14} />} onClick={() => setOpen(true)}>Create coupon</S.Btn>
        </>}
      />

      <div className="grid-4" style={{ marginBottom: 24 }}>
        <S.Metric hero label="Redemptions · 30d" value="14,820" delta="+18%" />
        <S.Metric label="Avg discount" value="$11.20" />
        <S.Metric label="Active campaigns" value="14" delta="+2" />
        <S.Metric label="Cost to platform" value="$166k" delta="+12%" deltaTone="neg" />
      </div>

      <div className="grid-3">
        {[
          { code: "WELLNESS25", desc: "25% off first spa booking", uses: 1820, cap: 5000, tone: "accent", type: "percent", value: 25 },
          { code: "PAMP10", desc: "$10 off any service", uses: 4210, cap: 10000, tone: "pos", type: "fixed", value: 10 },
          { code: "VIP-PARIS", desc: "Vendor exclusive · Maison Color", uses: 312, cap: 500, tone: "info", type: "percent", value: 20 },
          { code: "FRIENDS15", desc: "Friend referral · $15 credit", uses: 8420, cap: 99999, tone: "warn", type: "fixed", value: 15 },
          { code: "SUMMER", desc: "Summer 2025 (expired)", uses: 12420, cap: 12420, tone: "", type: "percent", value: 15 },
          { code: "RESTART", desc: "Win-back · 30% off", uses: 142, cap: 1000, tone: "neg", type: "percent", value: 30 },
        ].map((c) => (
          <div key={c.code} className="card" style={{ padding: 22 }}>
            <div className="row between">
              <S.Chip tone={c.tone}>{c.code}</S.Chip>
              <S.IconBtn><I.ellipsis size={16} /></S.IconBtn>
            </div>
            <div className="display" style={{ fontSize: 36, marginTop: 16, letterSpacing: "-0.03em" }}>
              {c.type === "percent" ? `${c.value}%` : `$${c.value}`}
              <span className="muted" style={{ fontSize: 12, fontWeight: 400, marginLeft: 8 }}>off</span>
            </div>
            <div style={{ fontSize: 13, marginTop: 6, color: "var(--ink-2)" }}>{c.desc}</div>
            <div className="divider" style={{ margin: "16px 0" }} />
            <div className="row between mono tiny muted" style={{ marginBottom: 6 }}>
              <span>{c.uses.toLocaleString()} redeemed</span>
              <span>of {c.cap === 99999 ? "∞" : c.cap.toLocaleString()}</span>
            </div>
            <div className="bar"><span style={{ width: `${Math.min(100, (c.uses / c.cap) * 100)}%` }} /></div>
          </div>
        ))}
      </div>

      <CreateCouponModal open={open} onClose={() => setOpen(false)} />
    </div>
  );
}

function CreateCouponModal({ open, onClose }) {
  const [data, setData] = React.useState({
    code: "", desc: "", type: "percent", value: "",
    applies: "all", limit: "", expires: "", oncePerUser: true,
  });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  return (
    <window.M.Modal open={open} onClose={onClose} size="lg"
      icon={<I.coupon />} title="Create coupon"
      subtitle="Define the discount, audience, and limits."
      footer={<>
        <S.Btn variant="ghost" onClick={onClose}>Cancel</S.Btn>
        <S.Btn variant="outline">Save as draft</S.Btn>
        <S.Btn variant="primary" iconRight={<I.check size={14} />} onClick={onClose}>Create & activate</S.Btn>
      </>}
    >
      <window.M.FormGrid>
        <window.M.Field label="Code" hint="Letters and numbers. Will be uppercased.">
          <window.M.TextField value={data.code} onChange={(v) => set("code", v.toUpperCase())} placeholder="e.g. SPRING25" />
        </window.M.Field>
        <window.M.Field label="Description" hint="Shown to clients at checkout.">
          <window.M.TextField value={data.desc} onChange={(v) => set("desc", v)} placeholder="e.g. 25% off your first booking" />
        </window.M.Field>

        <window.M.Field full label="Discount type">
          <window.M.Segmented value={data.type} onChange={(v) => set("type", v)}
            options={[{ value: "percent", label: "Percentage off" }, { value: "fixed", label: "Fixed amount off" }, { value: "free", label: "Free service" }]} />
        </window.M.Field>

        <window.M.Field label="Value">
          <window.M.TextField
            value={data.value} onChange={(v) => set("value", v)}
            placeholder={data.type === "percent" ? "25" : "10.00"}
            suffix={<span className="mono tiny muted">{data.type === "percent" ? "%" : "$"}</span>}
          />
        </window.M.Field>
        <window.M.Field label="Usage limit" hint="Total redemptions across all users.">
          <window.M.TextField value={data.limit} onChange={(v) => set("limit", v)} placeholder="e.g. 1000 (blank = unlimited)" />
        </window.M.Field>

        <window.M.Field full label="Applies to">
          <window.M.RadioCards value={data.applies} onChange={(v) => set("applies", v)}
            options={[
              { value: "all", label: "All services", desc: "Use on anything available on Pamp" },
              { value: "category", label: "Specific category", desc: "e.g. Hair, Spa, Nails" },
              { value: "vendor", label: "Specific vendor(s)", desc: "Pick one or more vendors" },
            ]} />
        </window.M.Field>

        <window.M.Field label="Expires on">
          <window.M.TextField icon={<I.calendar size={14} />} value={data.expires} onChange={(v) => set("expires", v)} placeholder="Mar 31, 2026" />
        </window.M.Field>
        <window.M.Field label="Rules">
          <window.M.Checkbox checked={data.oncePerUser} onChange={(v) => set("oncePerUser", v)} label="Once per user" />
        </window.M.Field>
      </window.M.FormGrid>
    </window.M.Modal>
  );
}

function AdminNotifications() {
  const [tab, setTab] = React.useState("history");
  const [open, setOpen] = React.useState(false);
  const [scheduleMode, setScheduleMode] = React.useState(false);
  return (
    <div className="page-enter">
      <window.DemoBanner feature="notification broadcast (live wiring next phase)" />
      <S.PageHead
        eyebrow="Broadcast & automated"
        title="Notifications"
        sub="Reach users and vendors with in-app, email, and push messages."
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.clock size={14} />} onClick={() => { setScheduleMode(true); setOpen(true); }}>Schedule notification</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.plus size={14} />} onClick={() => { setScheduleMode(false); setOpen(true); }}>Send notification</S.Btn>
        </>}
      />

      <div className="grid-4" style={{ marginBottom: 24 }}>
        <S.Metric hero label="Sent · 30 days" value="184k" delta="+22%" />
        <S.Metric label="Open rate" value="42.1%" delta="+1.8pp" />
        <S.Metric label="Click rate" value="14.8%" delta="+0.6pp" />
        <S.Metric label="Unsubscribes" value="0.18%" delta="−0.04pp" deltaTone="pos" />
      </div>

      <div className="row" style={{ gap: 0, borderBottom: "1px solid var(--border)", marginBottom: 20 }}>
        {[{ k: "history", l: "Sent" }, { k: "scheduled", l: "Scheduled" }, { k: "automated", l: "Automated" }].map(t => (
          <button key={t.k} onClick={() => setTab(t.k)}
            style={{
              padding: "12px 18px", fontSize: 13, fontWeight: 500,
              color: tab === t.k ? "var(--ink)" : "var(--ink-3)",
              borderBottom: `2px solid ${tab === t.k ? "var(--ink)" : "transparent"}`,
              marginBottom: -1,
            }}>{t.l}</button>
        ))}
      </div>

      <div className="card card-flush">
        <table className="tbl">
          <thead>
            <tr>
              <th>Title</th>
              <th>Audience</th>
              <th>Channels</th>
              <th>Performance</th>
              <th>Status</th>
              <th>When</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {NOTIF_HISTORY.filter(n => tab === "history" ? n.kind === "sent" : tab === "scheduled" ? n.kind === "scheduled" : n.kind === "automated").map((n) => (
              <tr key={n.id}>
                <td>
                  <div style={{ fontWeight: 500 }}>{n.title}</div>
                  <div className="muted tiny" style={{ marginTop: 2 }}>{n.subtitle}</div>
                </td>
                <td>
                  <S.Chip>{n.audience}</S.Chip>
                  <div className="muted tiny" style={{ marginTop: 4 }}>{n.audienceCount.toLocaleString()} recipients</div>
                </td>
                <td>
                  <div className="row-tight" style={{ gap: 4 }}>
                    {n.channels.map((c) => (
                      <span key={c} title={c} style={{
                        width: 26, height: 26, borderRadius: 7, fontSize: 10, fontWeight: 600,
                        background: "var(--surface-3)", color: "var(--ink-2)",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                      }}>
                        {c === "in-app" ? <I.bell size={12} /> : c === "email" ? <I.mail size={12} /> : <I.phone size={12} />}
                      </span>
                    ))}
                  </div>
                </td>
                <td>
                  {n.openRate != null ? (
                    <div className="row-tight">
                      <span className="mono tiny">{n.openRate}%</span>
                      <span className="muted tiny">open · {n.clickRate}% click</span>
                    </div>
                  ) : <span className="muted tiny">—</span>}
                </td>
                <td><S.Chip tone={n.status === "Sent" ? "pos" : n.status === "Scheduled" ? "warn" : n.status === "Live" ? "info" : ""}>{n.status}</S.Chip></td>
                <td className="muted tiny">{n.when}</td>
                <td><S.IconBtn><I.ellipsis size={16} /></S.IconBtn></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <SendNotificationModal open={open} schedule={scheduleMode} onClose={() => setOpen(false)} />
    </div>
  );
}

const NOTIF_HISTORY = [
  { id: 1, kind: "sent", title: "February perks — 10% off all spa bookings", subtitle: "Promo · expires Feb 28", audience: "All clients", audienceCount: 28431, channels: ["in-app", "email"], openRate: 42, clickRate: 14, status: "Sent", when: "Feb 1, 09:00 UTC" },
  { id: 2, kind: "sent", title: "Payout method update required", subtitle: "Compliance · ACH routing change", audience: "Specific vendors", audienceCount: 84, channels: ["email", "in-app"], openRate: 88, clickRate: 64, status: "Sent", when: "Today, 06:00 UTC" },
  { id: 3, kind: "scheduled", title: "Holiday weekend reminder", subtitle: "Operational · stock up tips", audience: "All vendors", audienceCount: 1842, channels: ["in-app", "email"], openRate: null, clickRate: null, status: "Scheduled", when: "Feb 15, 09:00 UTC" },
  { id: 4, kind: "scheduled", title: "New feature: smart promo", subtitle: "Product launch · Studio plan only", audience: "Studio vendors", audienceCount: 824, channels: ["in-app"], openRate: null, clickRate: null, status: "Scheduled", when: "Feb 20, 10:00 UTC" },
  { id: 5, kind: "automated", title: "Welcome — new clients", subtitle: "Triggered on signup", audience: "Trigger", audienceCount: 1420, channels: ["email"], openRate: 64, clickRate: 22, status: "Live", when: "Always-on" },
  { id: 6, kind: "automated", title: "Booking confirmation", subtitle: "Triggered on booking confirmed", audience: "Trigger", audienceCount: 184_280, channels: ["email", "sms"], openRate: 92, clickRate: 38, status: "Live", when: "Always-on" },
  { id: 7, kind: "automated", title: "Payout sent", subtitle: "Triggered when payout clears", audience: "Trigger", audienceCount: 84_000, channels: ["email"], openRate: 78, clickRate: 14, status: "Live", when: "Always-on" },
];

function SendNotificationModal({ open, schedule, onClose }) {
  const [data, setData] = React.useState({
    audience: "all-clients", title: "", body: "",
    channels: { inapp: true, email: true, sms: false },
    when: "now", date: "", time: "",
  });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const toggleChannel = (c) => setData(d => ({ ...d, channels: { ...d.channels, [c]: !d.channels[c] } }));
  return (
    <window.M.Modal open={open} onClose={onClose} size="lg"
      icon={<I.bell />} title={schedule ? "Schedule notification" : "Send notification"}
      subtitle={schedule ? "Compose now, deliver later. You can edit until it sends." : "Compose and send to a segment immediately."}
      footer={<>
        <S.Btn variant="ghost" onClick={onClose}>Cancel</S.Btn>
        <S.Btn variant="outline">Send test to me</S.Btn>
        <S.Btn variant="primary" iconRight={schedule ? <I.clock size={14} /> : <I.arrowR size={14} />} onClick={onClose}>
          {schedule ? "Schedule" : "Send now"}
        </S.Btn>
      </>}
    >
      <window.M.FormGrid>
        <window.M.Field full label="Audience" hint="Who should receive this notification?">
          <window.M.RadioCards value={data.audience} onChange={(v) => set("audience", v)}
            options={[
              { value: "all-clients", label: "All clients", desc: "28,431 recipients", right: <S.Chip>28.4k</S.Chip> },
              { value: "all-vendors", label: "All vendors", desc: "1,842 recipients", right: <S.Chip>1.8k</S.Chip> },
              { value: "vendor-segment", label: "Vendor segment", desc: "Filter by plan, country, category", right: <I.filter size={14} /> },
              { value: "specific-users", label: "Specific users", desc: "Pick 1 – 200 users individually" },
            ]} />
        </window.M.Field>

        <window.M.Field full label="Channels" hint="Choose one or more delivery channels.">
          <div className="row" style={{ gap: 10 }}>
            <ChannelTile checked={data.channels.inapp} onClick={() => toggleChannel("inapp")} icon={<I.bell />} label="In-app" hint="Bell + inbox" />
            <ChannelTile checked={data.channels.email} onClick={() => toggleChannel("email")} icon={<I.mail />} label="Email" hint="With templated layout" />
            <ChannelTile checked={data.channels.sms} onClick={() => toggleChannel("sms")} icon={<I.phone />} label="SMS" hint="Short message" />
          </div>
        </window.M.Field>

        <window.M.Field full label="Title">
          <window.M.TextField value={data.title} onChange={(v) => set("title", v)} placeholder="Short, scannable headline" />
        </window.M.Field>
        <window.M.Field full label="Body">
          <window.M.Textarea value={data.body} onChange={(v) => set("body", v)} placeholder="Write what you want them to know. Avoid all-caps. Personalize with {{first_name}}." rows={5} />
        </window.M.Field>

        {schedule && <>
          <window.M.Field label="Date">
            <window.M.TextField icon={<I.calendar size={14} />} value={data.date} onChange={(v) => set("date", v)} placeholder="Feb 15, 2026" />
          </window.M.Field>
          <window.M.Field label="Time (UTC)">
            <window.M.TextField icon={<I.clock size={14} />} value={data.time} onChange={(v) => set("time", v)} placeholder="09:00" />
          </window.M.Field>
        </>}
      </window.M.FormGrid>
    </window.M.Modal>
  );
}

function ChannelTile({ checked, onClick, icon, label, hint }) {
  return (
    <button type="button" onClick={onClick} className="radio-card" data-checked={checked}
      style={{ flex: 1, flexDirection: "column", alignItems: "flex-start", padding: 14 }}>
      <div className="row between" style={{ width: "100%", marginBottom: 6 }}>
        <span style={{ color: checked ? "var(--accent-ink)" : "var(--ink-3)", display: "inline-flex" }}>{React.cloneElement(icon, { size: 16 })}</span>
        <span className="cb-box" data-checked={checked}>{checked && <I.check size={12} />}</span>
      </div>
      <div style={{ fontSize: 13, fontWeight: 500 }}>{label}</div>
      <div className="muted tiny">{hint}</div>
    </button>
  );
}

function AdminSettings() {
  const [tab, setTab] = React.useState("general");

  return (
    <div className="page-enter">
      <window.DemoBanner feature="platform settings (live wiring next phase)" />
      <S.PageHead
        eyebrow="Platform · global settings"
        title="Settings"
        sub="Branding, regions, security, billing, integrations & audit."
        right={<>
          <S.Btn variant="ghost" size="sm">Discard</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.check size={14} />}>Save changes</S.Btn>
        </>}
      />

      <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 28, alignItems: "flex-start" }}>
        <aside className="card" style={{ padding: 8, position: "sticky", top: 0 }}>
          <nav className="col" style={{ gap: 2 }}>
            {[
              { section: "Platform" },
              { k: "general", l: "General", ic: I.settings },
              { k: "branding", l: "Branding", ic: I.sparkle },
              { k: "regions", l: "Regions & taxes", ic: I.location },
              { k: "fees", l: "Fees & pricing", ic: I.coupon },
              { section: "People" },
              { k: "team", l: "Admin team", ic: I.staff },
              { k: "roles", l: "Roles & permissions", ic: I.users },
              { section: "Security" },
              { k: "security", l: "Security policies", ic: I.help },
              { k: "session", l: "Sessions & devices", ic: I.panel },
              { k: "audit", l: "Audit log", ic: I.list },
              { section: "Billing" },
              { k: "billing", l: "Billing & invoices", ic: I.card },
              { section: "Developer" },
              { k: "integrations", l: "Integrations", ic: I.export },
              { k: "api", l: "API & webhooks", ic: I.chart },
            ].map((s, i) => {
              if (s.section) return <div key={`s${i}`} style={{
                fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em",
                textTransform: "uppercase", color: "var(--ink-4)",
                padding: "14px 12px 6px",
              }}>{s.section}</div>;
              const Ic = s.ic;
              const active = tab === s.k;
              return (
                <button key={s.k} onClick={() => setTab(s.k)}
                  className={`nav-item${active ? " active" : ""}`}
                  style={{ width: "100%", justifyContent: "flex-start" }}>
                  <span className="ni-icon"><Ic size={16} /></span>
                  <span className="ni-label">{s.l}</span>
                </button>
              );
            })}
          </nav>
        </aside>

        <div>
          {tab === "general" && <SettingsGeneral />}
          {tab === "branding" && <SettingsBranding />}
          {tab === "regions" && <SettingsRegions />}
          {tab === "fees" && <SettingsFees />}
          {tab === "team" && <SettingsTeam />}
          {tab === "roles" && <SettingsRoles />}
          {tab === "security" && <SettingsSecurity />}
          {tab === "session" && <SettingsSessions />}
          {tab === "audit" && <SettingsAudit />}
          {tab === "billing" && <SettingsBilling />}
          {tab === "integrations" && <SettingsIntegrations />}
          {tab === "api" && <SettingsApi />}
        </div>
      </div>
    </div>
  );
}

function ASCard({ title, sub, children, action }) {
  return (
    <div className="card" style={{ padding: 28, marginBottom: 18 }}>
      <div className="row between" style={{ marginBottom: 20 }}>
        <div>
          <div className="h2" style={{ fontSize: 22 }}>{title}</div>
          {sub && <div className="muted" style={{ fontSize: 13, marginTop: 6 }}>{sub}</div>}
        </div>
        {action}
      </div>
      {children}
    </div>
  );
}

function ASRow({ label, hint, children, full }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: full ? "1fr" : "220px 1fr",
      gap: 18, alignItems: "flex-start",
      padding: "14px 0", borderTop: "1px solid var(--border)",
    }}>
      <div>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{label}</div>
        {hint && <div className="muted tiny" style={{ marginTop: 4 }}>{hint}</div>}
      </div>
      <div>{children}</div>
    </div>
  );
}

function ASToggle({ defaultOn, hint }) {
  const [on, setOn] = React.useState(!!defaultOn);
  return (
    <div className="row" style={{ gap: 14 }}>
      <button onClick={() => setOn(!on)} style={{
        width: 38, height: 22, borderRadius: 999,
        background: on ? "var(--accent)" : "var(--surface-3)",
        position: "relative", transition: "background 0.2s",
        border: "1px solid var(--border)",
      }}>
        <span style={{
          position: "absolute", top: 1, left: on ? 17 : 1, width: 18, height: 18, borderRadius: 999,
          background: "white", transition: "left 0.2s", boxShadow: "0 1px 3px rgba(0,0,0,0.20)",
        }} />
      </button>
      {hint && <span className="muted tiny">{hint}</span>}
    </div>
  );
}

function SettingsGeneral() {
  return (
    <ASCard title="General" sub="Core platform settings every page inherits from.">
      <ASRow label="Platform name">
        <S.Input value="Pamp" onChange={() => { }} style={{ maxWidth: 320 }} />
      </ASRow>
      <ASRow label="Public website" hint="Used in footer links and outbound emails.">
        <S.Input value="pamp.app" onChange={() => { }} style={{ maxWidth: 320 }} />
      </ASRow>
      <ASRow label="Support email" hint="Replies to this address surface in the Support inbox.">
        <S.Input icon={<I.mail size={14} />} value="hello@pamp.app" onChange={() => { }} style={{ maxWidth: 320 }} />
      </ASRow>
      <ASRow label="Default timezone">
        <button className="select-pill" style={{ maxWidth: 320 }}>UTC · Coordinated <I.chevD size={14} className="chev" /></button>
      </ASRow>
      <ASRow label="Default locale">
        <button className="select-pill" style={{ maxWidth: 320 }}>English (US) <I.chevD size={14} className="chev" /></button>
      </ASRow>
      <ASRow label="Maintenance mode" hint="Shows a maintenance page to clients & vendors. Admin access stays open.">
        <ASToggle hint="Off · platform is live" />
      </ASRow>
    </ASCard>
  );
}

function SettingsBranding() {
  return (
    <>
      <ASCard title="Brand identity" sub="What appears across the app, emails and receipts.">
        <ASRow label="Logo">
          <div className="row" style={{ gap: 12, alignItems: "center" }}>
            <div className="brand-mark" style={{ width: 56, height: 56, borderRadius: 14 }}><span style={{ fontSize: 24 }}>P</span></div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>pamp_logo.svg</div>
              <div className="muted tiny">2.4 KB · Updated Jan 12</div>
            </div>
            <div className="spacer" />
            <S.Btn variant="outline" size="sm" icon={<I.export size={12} />}>Upload</S.Btn>
            <S.Btn variant="ghost" size="sm">Reset</S.Btn>
          </div>
        </ASRow>
        <ASRow label="Favicon" hint="32×32 PNG · shown in browser tabs.">
          <S.Btn variant="outline" size="sm" icon={<I.export size={12} />}>Upload favicon</S.Btn>
        </ASRow>
        <ASRow label="Primary accent">
          <div className="row" style={{ gap: 8 }}>
            {["#86D694", "#7062b0", "#3a6cd3", "#b59555", "#d97757"].map(c => (
              <button key={c} style={{
                width: 32, height: 32, borderRadius: 8, background: c,
                border: c === "#86D694" ? "2px solid var(--ink)" : "1px solid var(--border)",
              }} />
            ))}
            <S.Btn variant="ghost" size="sm">Custom hex</S.Btn>
          </div>
        </ASRow>
        <ASRow label="Email signature" hint="Appended to every transactional email.">
          <textarea className="text-input" rows={3} defaultValue="— The Pamp team · pamp.app · unsubscribe" />
        </ASRow>
      </ASCard>
    </>
  );
}

function SettingsRegions() {
  return (
    <ASCard
      title="Regions & taxes"
      sub="Where Pamp operates and how money is collected."
      action={<S.Btn variant="primary" size="sm" icon={<I.plus size={14} />}>Add region</S.Btn>}
    >
      <table className="tbl" style={{ marginTop: -10 }}>
        <thead>
          <tr>
            <th>Region</th>
            <th>Currency</th>
            <th>Tax rate</th>
            <th>Tax authority</th>
            <th>Status</th>
            <th />
          </tr>
        </thead>
        <tbody>
          {[
            { r: "United States", c: "USD", t: "Pass-through", a: "State sales tax", s: "Live", st: "pos" },
            { r: "United Kingdom", c: "GBP", t: "20% VAT", a: "HMRC · GB142180", s: "Live", st: "pos" },
            { r: "European Union", c: "EUR", t: "21% VAT (avg)", a: "Per country · OSS", s: "Live", st: "pos" },
            { r: "Canada", c: "CAD", t: "5% GST + HST", a: "CRA", s: "Live", st: "pos" },
            { r: "Australia", c: "AUD", t: "10% GST", a: "ATO", s: "Pending", st: "warn" },
            { r: "Japan", c: "JPY", t: "10% consumption", a: "NTA", s: "Draft", st: "info" },
          ].map((r) => (
            <tr key={r.r}>
              <td style={{ fontWeight: 500 }}>{r.r}</td>
              <td className="mono">{r.c}</td>
              <td>{r.t}</td>
              <td className="muted tiny">{r.a}</td>
              <td><S.Chip tone={r.st}>{r.s}</S.Chip></td>
              <td><S.IconBtn><I.ellipsis size={16} /></S.IconBtn></td>
            </tr>
          ))}
        </tbody>
      </table>
    </ASCard>
  );
}

function SettingsFees() {
  return (
    <ASCard title="Fees & pricing" sub="Default platform fees per vendor plan.">
      {[
        { plan: "Starter", fee: "5.0%", subs: "Free" },
        { plan: "Studio", fee: "3.5%", subs: "$49 /mo" },
        { plan: "Atelier", fee: "2.4%", subs: "$149 /mo" },
        { plan: "Enterprise", fee: "Custom", subs: "Custom" },
      ].map((p) => (
        <ASRow key={p.plan} label={p.plan} hint={`Subscription · ${p.subs}`}>
          <div className="row" style={{ gap: 12 }}>
            <S.Input value={p.fee} onChange={() => { }} style={{ maxWidth: 140 }} />
            <span className="muted tiny" style={{ alignSelf: "center" }}>per booking · taken from vendor net</span>
          </div>
        </ASRow>
      ))}
      <ASRow label="Refund handling" hint="What happens to platform fees when bookings are refunded.">
        <window.M.RadioCards value="prorate" onChange={() => { }} options={[
          { value: "prorate", label: "Pro-rate fees", desc: "Refund a proportional slice of the fee with each refund." },
          { value: "keep", label: "Keep fees", desc: "Vendor absorbs the platform fee on refund." },
          { value: "release", label: "Release fees", desc: "Pamp returns the fee in full." },
        ]} />
      </ASRow>
    </ASCard>
  );
}

function SettingsTeam() {
  return (
    <ASCard
      title="Admin team"
      sub="People with access to this dashboard."
      action={<S.Btn variant="primary" size="sm" icon={<I.plus size={14} />}>Invite admin</S.Btn>}
    >
      <table className="tbl" style={{ marginTop: -10 }}>
        <thead>
          <tr><th>Member</th><th>Role</th><th>2FA</th><th>Last active</th><th /></tr>
        </thead>
        <tbody>
          {[
            { n: "Mira Johnson", e: "mira.j@pamp.app", r: "Owner", t: true, l: "Online now" },
            { n: "Eli Rosenberg", e: "eli.r@pamp.app", r: "Support lead", t: true, l: "12m ago" },
            { n: "Olu Adeyemi", e: "olu.a@pamp.app", r: "Finance", t: true, l: "1h ago" },
            { n: "Sasha Ivanov", e: "sasha.i@pamp.app", r: "Trust & safety", t: false, l: "Yesterday" },
          ].map((m) => (
            <tr key={m.e}>
              <td>
                <div className="row-tight">
                  <S.Avatar name={m.n} size="sm" />
                  <div>
                    <div style={{ fontWeight: 500 }}>{m.n}</div>
                    <div className="muted tiny">{m.e}</div>
                  </div>
                </div>
              </td>
              <td><S.Chip tone="accent">{m.r}</S.Chip></td>
              <td>{m.t ? <S.Chip tone="pos">Enabled</S.Chip> : <S.Chip tone="warn">Not set</S.Chip>}</td>
              <td className="muted tiny">{m.l}</td>
              <td><S.IconBtn><I.ellipsis size={16} /></S.IconBtn></td>
            </tr>
          ))}
        </tbody>
      </table>
    </ASCard>
  );
}

function SettingsRoles() {
  const matrix = [
    { area: "Users", o: true, s: true, f: false, t: true },
    { area: "Bookings", o: true, s: true, f: true, t: true },
    { area: "Payments", o: true, s: false, f: true, t: false },
    { area: "Payouts", o: true, s: false, f: true, t: false },
    { area: "Coupons", o: true, s: true, f: false, t: false },
    { area: "Support", o: true, s: true, f: false, t: true },
    { area: "Reports", o: true, s: true, f: true, t: true },
    { area: "Settings", o: true, s: false, f: false, t: false },
  ];
  const Cell = ({ v }) => v ? <I.check size={14} color="var(--pos)" /> : <I.x size={14} color="var(--ink-4)" />;
  return (
    <ASCard title="Roles & permissions" sub="What each admin role can see and change.">
      <table className="tbl" style={{ marginTop: -10 }}>
        <thead>
          <tr><th>Area</th><th>Owner</th><th>Support</th><th>Finance</th><th>Trust & safety</th></tr>
        </thead>
        <tbody>
          {matrix.map(r => (
            <tr key={r.area}>
              <td style={{ fontWeight: 500 }}>{r.area}</td>
              <td><Cell v={r.o} /></td>
              <td><Cell v={r.s} /></td>
              <td><Cell v={r.f} /></td>
              <td><Cell v={r.t} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </ASCard>
  );
}

function SettingsSecurity() {
  return (
    <ASCard title="Security policies" sub="How admins log in and stay safe.">
      <ASRow label="Require 2FA for admins" hint="All admins must enable an authenticator app.">
        <ASToggle defaultOn />
      </ASRow>
      <ASRow label="Single sign-on (SAML)" hint="Use your identity provider for admin login.">
        <ASToggle defaultOn />
      </ASRow>
      <ASRow label="IP allowlist" hint="Only requests from listed CIDR ranges can sign in.">
        <ASToggle />
      </ASRow>
      <ASRow label="Session timeout">
        <window.M.Segmented value="30" onChange={() => { }}
          options={[{ value: "15", label: "15 min" }, { value: "30", label: "30 min" }, { value: "60", label: "1 hr" }, { value: "8h", label: "8 hrs" }]} />
      </ASRow>
      <ASRow label="Password policy" hint="Minimum strength for new admin passwords.">
        <window.M.Segmented value="strong" onChange={() => { }}
          options={[{ value: "basic", label: "Basic" }, { value: "strong", label: "Strong" }, { value: "fips", label: "FIPS" }]} />
      </ASRow>
      <ASRow label="Auto-lock dormant admins" hint="Disable accounts inactive for over 60 days.">
        <ASToggle defaultOn />
      </ASRow>
    </ASCard>
  );
}

function SettingsSessions() {
  return (
    <ASCard title="Active admin sessions" sub="Sign anyone out if a device looks unfamiliar.">
      <table className="tbl" style={{ marginTop: -10 }}>
        <thead><tr><th>Member</th><th>Device</th><th>Location</th><th>Last seen</th><th /></tr></thead>
        <tbody>
          {[
            { n: "Mira Johnson", d: "MacBook Pro · Chrome", l: "San Francisco, US", t: "Online now" },
            { n: "Mira Johnson", d: "iPhone 15 · Safari", l: "San Francisco, US", t: "4h ago" },
            { n: "Eli Rosenberg", d: "MacBook Air · Safari", l: "Berlin, DE", t: "12m ago" },
            { n: "Olu Adeyemi", d: "Linux · Firefox", l: "Lagos, NG", t: "1h ago" },
          ].map((s, i) => (
            <tr key={i}>
              <td>{s.n}</td>
              <td className="muted">{s.d}</td>
              <td className="muted tiny">{s.l}</td>
              <td className="mono tiny">{s.t}</td>
              <td><S.Btn variant="ghost" size="sm" style={{ color: "var(--neg)" }}>Sign out</S.Btn></td>
            </tr>
          ))}
        </tbody>
      </table>
      <div className="row" style={{ marginTop: 16 }}>
        <div className="spacer" />
        <S.Btn variant="outline" size="sm" style={{ color: "var(--neg)", borderColor: "var(--neg)" }}>Sign out all other sessions</S.Btn>
      </div>
    </ASCard>
  );
}

function SettingsAudit() {
  return (
    <ASCard
      title="Audit log"
      sub="Every sensitive admin action, with who and when."
      action={<S.Btn variant="outline" size="sm" icon={<I.download size={12} />}>Export CSV</S.Btn>}
    >
      <table className="tbl" style={{ marginTop: -10 }}>
        <thead><tr><th>When</th><th>Member</th><th>Action</th><th>Target</th><th>IP</th></tr></thead>
        <tbody>
          {[
            { t: "2m ago", n: "Mira Johnson", a: "Authorized transfer", o: "Operating → Payroll · $148,420", ip: "73.118.221.42" },
            { t: "12m ago", n: "Olu Adeyemi", a: "Approved payout", o: "PR-9239 · Atelier Nails", ip: "102.89.10.18" },
            { t: "1h ago", n: "Eli Rosenberg", a: "Refund issued", o: "PB-28405 · $142", ip: "82.220.190.4" },
            { t: "3h ago", n: "Sasha Ivanov", a: "Suspended user", o: "Client #6 · Olivia Wright", ip: "203.0.113.42" },
            { t: "Yesterday", n: "Mira Johnson", a: "Updated branding", o: "Primary accent · #86D694", ip: "73.118.221.42" },
            { t: "Yesterday", n: "Olu Adeyemi", a: "Created coupon", o: "WELLNESS25", ip: "102.89.10.18" },
          ].map((r, i) => (
            <tr key={i}>
              <td className="mono tiny">{r.t}</td>
              <td>{r.n}</td>
              <td><S.Chip>{r.a}</S.Chip></td>
              <td className="muted tiny">{r.o}</td>
              <td className="mono tiny muted">{r.ip}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </ASCard>
  );
}

function SettingsBilling() {
  return (
    <>
      <ASCard title="Billing" sub="How you pay for Pamp infrastructure & services.">
        <div className="grid-3" style={{ gap: 14, marginBottom: 8 }}>
          <div style={{ padding: 18, borderRadius: 14, background: "var(--ink)", color: "var(--bg)", position: "relative", overflow: "hidden", minHeight: 130 }}>
            <div style={{ position: "absolute", inset: 0, opacity: 0.4, background: "radial-gradient(circle at 90% 20%, var(--accent), transparent 60%)" }} />
            <div style={{ position: "relative" }}>
              <div className="eyebrow" style={{ color: "oklch(75% 0.02 145)" }}>Plan</div>
              <div className="display" style={{ fontSize: 28, marginTop: 6 }}>Enterprise</div>
              <div className="muted tiny" style={{ color: "oklch(75% 0.02 145)", marginTop: 4 }}>Renews Jan 1, 2027</div>
            </div>
          </div>
          <div style={{ padding: 18, borderRadius: 14, border: "1px solid var(--border)", minHeight: 130 }}>
            <div className="eyebrow">Monthly cost</div>
            <div className="display" style={{ fontSize: 28, marginTop: 6 }}>$4,800</div>
            <div className="muted tiny">Includes 50k MAU</div>
          </div>
          <div style={{ padding: 18, borderRadius: 14, border: "1px solid var(--border)", minHeight: 130 }}>
            <div className="eyebrow">Card on file</div>
            <div style={{ fontSize: 18, marginTop: 6, fontWeight: 500 }}>Visa ····4218</div>
            <div className="muted tiny">Expires 11/27</div>
          </div>
        </div>
      </ASCard>
      <ASCard title="Invoices" sub="Receipts from your last twelve months.">
        <table className="tbl" style={{ marginTop: -10 }}>
          <thead><tr><th>Date</th><th>Period</th><th>Amount</th><th>Status</th><th /></tr></thead>
          <tbody>
            {[
              { d: "Feb 1, 2026", p: "Jan 2026", a: 4800, s: "Paid", st: "pos" },
              { d: "Jan 1, 2026", p: "Dec 2025", a: 4800, s: "Paid", st: "pos" },
              { d: "Dec 1, 2025", p: "Nov 2025", a: 4800, s: "Paid", st: "pos" },
              { d: "Nov 1, 2025", p: "Oct 2025", a: 4800, s: "Paid", st: "pos" },
            ].map(r => (
              <tr key={r.d}>
                <td className="mono">{r.d}</td>
                <td className="muted">{r.p}</td>
                <td className="mono">${r.a.toLocaleString()}</td>
                <td><S.Chip tone={r.st}>{r.s}</S.Chip></td>
                <td><S.IconBtn><I.download size={14} /></S.IconBtn></td>
              </tr>
            ))}
          </tbody>
        </table>
      </ASCard>
    </>
  );
}

function SettingsIntegrations() {
  const items = [
    { n: "Stripe", d: "Payments, payouts, disputes", on: true, c: "var(--info)" },
    { n: "Twilio", d: "SMS reminders & confirmations", on: true, c: "var(--neg)" },
    { n: "SendGrid", d: "Transactional email delivery", on: true, c: "var(--ink)" },
    { n: "Segment", d: "Event pipeline to analytics tools", on: true, c: "var(--accent)" },
    { n: "Slack", d: "Ops alerts to #pamp-ops", on: true, c: "var(--warn)" },
    { n: "Zendesk", d: "Mirror support tickets", on: false, c: "var(--info)" },
    { n: "Google Calendar", d: "Sync appointments to calendars", on: true, c: "var(--pos)" },
    { n: "Datadog", d: "Logs & traces from API", on: true, c: "var(--accent-ink)" },
  ];
  return (
    <ASCard
      title="Integrations"
      sub="Third-party services connected to Pamp."
      action={<S.Btn variant="primary" size="sm" icon={<I.plus size={14} />}>Add integration</S.Btn>}
    >
      <div className="grid-2" style={{ gap: 12 }}>
        {items.map(i => (
          <div key={i.n} className="row" style={{ padding: 16, borderRadius: 12, border: "1px solid var(--border)", gap: 14 }}>
            <div style={{
              width: 40, height: 40, borderRadius: 10, background: "var(--surface-2)",
              display: "flex", alignItems: "center", justifyContent: "center",
              color: i.c, fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 600,
            }}>{i.n[0]}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{i.n}</div>
              <div className="muted tiny">{i.d}</div>
            </div>
            <div className="row-tight">
              <S.Chip tone={i.on ? "pos" : ""}>{i.on ? "Connected" : "Off"}</S.Chip>
              <S.IconBtn><I.chevR size={14} /></S.IconBtn>
            </div>
          </div>
        ))}
      </div>
    </ASCard>
  );
}

function SettingsApi() {
  return (
    <>
      <ASCard
        title="API keys"
        sub="Server-to-server credentials. Treat like passwords."
        action={<S.Btn variant="primary" size="sm" icon={<I.plus size={14} />}>Create key</S.Btn>}
      >
        <table className="tbl" style={{ marginTop: -10 }}>
          <thead><tr><th>Label</th><th>Token</th><th>Scopes</th><th>Created</th><th>Last used</th><th /></tr></thead>
          <tbody>
            {[
              { n: "Production · core", t: "sk_live_•••••••••2418", s: "All", c: "Jan 14, 2024", l: "12m ago" },
              { n: "Mobile read-only", t: "pk_live_•••••••••8210", s: "Read", c: "Mar 02, 2024", l: "2m ago" },
              { n: "Internal · CI", t: "sk_test_•••••••••4218", s: "Sandbox", c: "Aug 11, 2024", l: "1h ago" },
            ].map((k, i) => (
              <tr key={i}>
                <td style={{ fontWeight: 500 }}>{k.n}</td>
                <td className="mono tiny muted">{k.t}</td>
                <td><S.Chip>{k.s}</S.Chip></td>
                <td className="mono tiny muted">{k.c}</td>
                <td className="muted tiny">{k.l}</td>
                <td><S.IconBtn><I.ellipsis size={16} /></S.IconBtn></td>
              </tr>
            ))}
          </tbody>
        </table>
      </ASCard>

      <ASCard
        title="Webhooks"
        sub="Where Pamp posts realtime events."
        action={<S.Btn variant="primary" size="sm" icon={<I.plus size={14} />}>Add endpoint</S.Btn>}
      >
        <div className="col" style={{ gap: 10 }}>
          {[
            { u: "https://api.maisoncolor.fr/pamp/hook", ev: ["booking.created", "booking.cancelled"], s: "Live", st: "pos" },
            { u: "https://hooks.zapier.com/hooks/catch/12/pamp", ev: ["payout.sent"], s: "Live", st: "pos" },
            { u: "https://internal.pamp.app/webhook/audit", ev: ["audit.*"], s: "Failing", st: "neg" },
          ].map((w, i) => (
            <div key={i} className="row" style={{ padding: 14, border: "1px solid var(--border)", borderRadius: 12, gap: 14 }}>
              <I.chart size={16} color="var(--ink-3)" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="mono tiny" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{w.u}</div>
                <div className="row-tight" style={{ marginTop: 4 }}>
                  {w.ev.map(e => <span key={e} className="chip" style={{ height: 20, fontSize: 10.5 }}>{e}</span>)}
                </div>
              </div>
              <S.Chip tone={w.st}>{w.s}</S.Chip>
              <S.IconBtn><I.ellipsis size={16} /></S.IconBtn>
            </div>
          ))}
        </div>
      </ASCard>
    </>
  );
}

window.AdminApp = AdminApp;
