// creator.jsx — Creator Studio: dashboard for skill publishers
//
// Covers what an indie publisher actually does day-to-day:
//   • Sign in (gated state for first-time visitors)
//   • Overview: install/activation/revenue trends + open todos
//   • My Skills: table of published + draft + in-review skills, per-row actions
//   • Skill detail: versions, reviews, analytics, permissions audit
//   • Submit new skill (the old wizard, now reachable from a button)
//   • Payouts + Identity verification

// Inline pill/underline tab bar — matches the existing style used in detail.jsx.
function CTabs({ value, options, onChange }) {
  return (
    <div className="row" style={{ borderBottom: "1px solid var(--line)", gap: 4, marginTop: -4 }}>
      {options.map(o => (
        <button key={o.id} className="unstyled" onClick={() => onChange(o.id)}
          style={{
            padding: "10px 12px",
            font: "500 13.5px/1 var(--font-sans)",
            color: value === o.id ? "var(--ink)" : "var(--ink-3)",
            borderBottom: value === o.id ? "2px solid var(--ink)" : "2px solid transparent",
            marginBottom: -1, cursor: "pointer", background: "transparent",
          }}>{o.label}</button>
      ))}
    </div>
  );
}

const { useState: useStateC, useEffect: useEffectC } = React;

// ─────────────────────────────── DATA ───────────────────────────────
// Pretend the signed-in creator is "Alex Chen / @alexchen". Their published
// portfolio is a curated subset of the marketplace catalog plus a couple of
// drafts/in-review entries that don't exist in the public catalog.
const CREATOR = {
  name: "Alex Chen",
  handle: "@alexchen",
  email: "alex@chen.dev",
  org: "Independent",
  verified: true,
  joined: "Mar 2024",
  payoutMethod: "Bank · ••4218",
};

const CREATOR_SKILLS = [
  {
    id: "spec-drafter", name: "Spec Drafter", status: "published",
    version: "0.9.1", visibility: "public",
    installs30d: 1842, installsTotal: 7400, activation: 0.71, rating: 4.6, reviews: 188,
    revenue30d: 0, // free
    pricing: "Free", trend: [12, 18, 22, 19, 28, 34, 29, 38, 44, 41, 52, 48],
    issues: 0,
  },
  {
    id: "research-summarizer", name: "Research Summarizer", status: "published",
    version: "1.2.0", visibility: "public",
    installs30d: 2210, installsTotal: 12800, activation: 0.78, rating: 4.7, reviews: 342,
    revenue30d: 1284,
    pricing: "$4/mo", trend: [40, 38, 44, 50, 47, 55, 58, 62, 60, 66, 71, 68],
    issues: 1, // 1 open review reply
  },
  {
    id: "ux-copy-editor", name: "UX Copy Editor", status: "published",
    version: "2.0.3", visibility: "public",
    installs30d: 612, installsTotal: 3120, activation: 0.64, rating: 4.4, reviews: 81,
    revenue30d: 0,
    pricing: "Free", trend: [8, 9, 11, 10, 14, 12, 15, 18, 17, 21, 19, 23],
    issues: 0,
  },
  {
    id: "meeting-recap-pro", name: "Meeting Recap Pro", status: "in-review",
    version: "0.1.0", visibility: "public",
    installs30d: 0, installsTotal: 0, activation: 0, rating: 0, reviews: 0,
    revenue30d: 0,
    pricing: "$6/mo", trend: [],
    submittedAt: "2 days ago", reviewStage: "Security review",
  },
  {
    id: "calendar-triage", name: "Calendar Triage", status: "draft",
    version: "—", visibility: "private",
    installs30d: 0, installsTotal: 0, activation: 0, rating: 0, reviews: 0,
    revenue30d: 0,
    pricing: "—", trend: [],
    completion: 0.6, // wizard progress
  },
];

// ─────────────────────────────── UI BITS ───────────────────────────────
function StatusPill({ s }) {
  const map = {
    "published":  { bg: "var(--green-50)", fg: "var(--green-700)", dot: "var(--green-600)", label: "Published" },
    "in-review":  { bg: "var(--amber-50)", fg: "var(--amber-700)", dot: "#b88200",          label: "In review" },
    "draft":      { bg: "var(--bg-muted)", fg: "var(--ink-2)",     dot: "var(--ink-4)",     label: "Draft" },
    "deprecated": { bg: "#fbe9e8",         fg: "#a83227",          dot: "#a83227",          label: "Deprecated" },
  }[s] || { bg: "var(--bg-muted)", fg: "var(--ink-2)", dot: "var(--ink-4)", label: s };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "3px 9px 3px 8px", borderRadius: 999,
      background: map.bg, color: map.fg,
      font: "500 11.5px/1 var(--font-sans)",
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: map.dot }} />
      {map.label}
    </span>
  );
}

function Sparkline({ data, w = 96, h = 28, color = "var(--accent)" }) {
  if (!data || data.length === 0) {
    return <span className="meta" style={{ color: "var(--ink-4)" }}>—</span>;
  }
  const max = Math.max(...data), min = Math.min(...data);
  const span = max - min || 1;
  const step = w / (data.length - 1 || 1);
  const pts = data.map((v, i) => `${i * step},${h - ((v - min) / span) * (h - 4) - 2}`).join(" ");
  return (
    <svg width={w} height={h} style={{ display: "block" }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function StatCard({ label, value, delta, sub }) {
  const positive = delta && delta.startsWith("+");
  return (
    <div className="card col gap-2" style={{ padding: 16, flex: "1 1 0", minWidth: 0 }}>
      <div className="eyebrow">{label}</div>
      <div className="row gap-2" style={{ alignItems: "baseline" }}>
        <div style={{ font: "600 24px/1 var(--font-display)", letterSpacing: "-0.01em" }}>{value}</div>
        {delta && (
          <span style={{
            font: "500 11.5px/1 var(--font-sans)",
            color: positive ? "var(--green-700)" : "#a83227",
          }}>{delta}</span>
        )}
      </div>
      {sub && <div className="meta">{sub}</div>}
    </div>
  );
}

// ─────────────────────────────── SIGN-IN GATE ───────────────────────────────
function CreatorSignIn({ onSignIn }) {
  return (
    <div className="page col gap-5" style={{ padding: "60px 28px 80px", maxWidth: 460 }}>
      <div className="col gap-3">
        <span className="eyebrow" style={{ color: "var(--iris-700)" }}>Creator Studio</span>
        <h1 className="h2" style={{ margin: 0 }}>Publish skills your agents can use.</h1>
        <div className="body-sm text-2">
          Bring your capability to IrisGo. Free to publish, with optional paid tiers and revenue share.
        </div>
      </div>

      <div className="card col gap-3" style={{ padding: 22 }}>
        <button className="btn btn-lg" style={{ justifyContent: "center" }}>
          <I.User size={14} /> Continue with Google
        </button>
        <button className="btn btn-lg" style={{ justifyContent: "center" }}>
          <I.Code size={14} /> Continue with GitHub
        </button>
        <div className="row gap-2" style={{ alignItems: "center", margin: "4px 0" }}>
          <span style={{ flex: 1, height: 1, background: "var(--line)" }} />
          <span className="meta">or</span>
          <span style={{ flex: 1, height: 1, background: "var(--line)" }} />
        </div>
        <input className="input" placeholder="you@company.com" />
        <button className="btn btn-primary btn-lg" style={{ justifyContent: "center" }} onClick={onSignIn}>
          Sign in to Studio <I.Arrow size={14} />
        </button>
      </div>

      <div className="meta">
        New here? <a href="#" style={{ color: "var(--ink)" }}>Read the publishing guide</a> · By signing in you accept the <a href="#" style={{ color: "var(--ink)" }}>Creator terms</a>.
      </div>
    </div>
  );
}

// ─────────────────────────────── DASHBOARD HOME ───────────────────────────────
function CreatorOverview({ onOpenSkill, onTab }) {
  const totals = CREATOR_SKILLS.reduce((a, s) => ({
    installs30d: a.installs30d + s.installs30d,
    revenue30d: a.revenue30d + s.revenue30d,
    published: a.published + (s.status === "published" ? 1 : 0),
  }), { installs30d: 0, revenue30d: 0, published: 0 });

  const todos = [
    { icon: "Star",       t: "Reply to 1 review on Research Summarizer", d: "@dawn.k left a 3★ review 2 days ago.", action: "View", target: "research-summarizer" },
    { icon: "ShieldCheck", t: "Meeting Recap Pro is in security review", d: "Submitted 2 days ago. Average wait: 3 business days.", action: "Track", target: "meeting-recap-pro" },
    { icon: "Sparkle",    t: "New IrisGo runtime v2.4 — re-test Spec Drafter", d: "Compatibility check recommended. Skills usually pass without changes.", action: "Run check" },
  ];

  const trend = [142, 168, 184, 175, 210, 232, 218, 264, 288, 276, 312, 304, 296, 322, 348];

  return (
    <div className="col gap-7">
      {/* Stats row */}
      <div className="row gap-3 wrap">
        <StatCard label="Installs · 30d" value="4,664" delta="+18.2%" sub="vs previous 30d" />
        <StatCard label="Revenue · 30d" value="$1,284" delta="+22.4%" sub="3 paid skills" />
        <StatCard label="Active users" value="2,810" delta="+9.1%" sub="Activated within 7d of install" />
        <StatCard label="Avg rating" value="4.6" sub="611 reviews · all skills" />
      </div>

      {/* Trend chart placeholder + todos */}
      <div className="row gap-4 wrap">
        <div className="card col gap-3" style={{ padding: 20, flex: "2 1 460px" }}>
          <div className="row between" style={{ alignItems: "baseline" }}>
            <div className="col">
              <div className="eyebrow">Installs over time</div>
              <div style={{ font: "600 20px/1.2 var(--font-display)" }}>Last 90 days</div>
            </div>
            <div className="row gap-1">
              {["7d", "30d", "90d", "1y"].map((p, i) => (
                <button key={p} className="btn btn-sm" style={{
                  background: i === 2 ? "var(--bg-muted)" : "transparent",
                  borderColor: "transparent",
                }}>{p}</button>
              ))}
            </div>
          </div>
          <div style={{ height: 180, position: "relative" }}>
            <Sparkline data={trend} w={500} h={180} color="var(--iris-600)" />
            <div style={{ position: "absolute", inset: 0, pointerEvents: "none",
              background: "linear-gradient(180deg, transparent 60%, rgba(16,65,59,0.06))" }} />
          </div>
        </div>

        <div className="card col" style={{ padding: 0, flex: "1 1 320px" }}>
          <div className="row between" style={{ padding: "16px 18px 12px", alignItems: "baseline" }}>
            <div className="eyebrow">Needs your attention</div>
            <span className="meta">{todos.length}</span>
          </div>
          {todos.map((t, i) => {
            const G = I[t.icon] || I.Sparkle;
            return (
              <div key={i} className="row gap-3" style={{
                padding: "12px 18px",
                borderTop: "1px solid var(--line-soft)",
                alignItems: "flex-start",
              }}>
                <span style={{
                  width: 28, height: 28, borderRadius: 8,
                  background: "var(--bg-muted)", color: "var(--ink-2)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto",
                }}><G size={13} /></span>
                <div className="col grow" style={{ minWidth: 0 }}>
                  <div className="body-sm" style={{ color: "var(--ink-1)", fontWeight: 500 }}>{t.t}</div>
                  <div className="meta">{t.d}</div>
                </div>
                <button className="btn btn-sm" onClick={() => t.target ? onOpenSkill(t.target) : null}>{t.action}</button>
              </div>
            );
          })}
        </div>
      </div>

      {/* Top skills */}
      <div className="col gap-3">
        <div className="row between" style={{ alignItems: "baseline" }}>
          <h2 className="h3" style={{ margin: 0 }}>Top performing</h2>
          <button className="btn btn-sm" onClick={() => onTab("skills")}>View all skills <I.Arrow size={12} /></button>
        </div>
        <div className="card col" style={{ padding: 0 }}>
          {CREATOR_SKILLS.filter(s => s.status === "published").slice(0, 3).map((s, i) => (
            <button key={s.id} onClick={() => onOpenSkill(s.id)} className="unstyled"
              style={{
                display: "grid",
                gridTemplateColumns: "1fr 110px 90px 90px 110px 14px",
                alignItems: "center", gap: 16,
                padding: "14px 18px", textAlign: "left",
                borderTop: i ? "1px solid var(--line-soft)" : "none",
                cursor: "pointer", background: "transparent",
              }}>
              <div className="col" style={{ minWidth: 0 }}>
                <div style={{ font: "500 14px/1.3 var(--font-sans)" }}>{s.name}</div>
                <div className="meta">v{s.version} · {s.pricing}</div>
              </div>
              <div className="col">
                <div className="body-sm">{s.installs30d.toLocaleString()}</div>
                <div className="meta">installs · 30d</div>
              </div>
              <div className="col">
                <div className="body-sm">{Math.round(s.activation * 100)}%</div>
                <div className="meta">activation</div>
              </div>
              <div className="col">
                <div className="body-sm">★ {s.rating}</div>
                <div className="meta">{s.reviews} reviews</div>
              </div>
              <Sparkline data={s.trend} color="var(--iris-600)" />
              <I.Arrow size={12} style={{ color: "var(--ink-4)" }} />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────── MY SKILLS ───────────────────────────────
function CreatorSkills({ onOpenSkill, onSubmit }) {
  const [filter, setFilter] = useStateC("all");
  const filtered = filter === "all" ? CREATOR_SKILLS : CREATOR_SKILLS.filter(s => s.status === filter);

  return (
    <div className="col gap-5">
      <div className="row between wrap gap-3" style={{ alignItems: "center" }}>
        <FilterChips
          value={filter}
          options={["all", "published", "in-review", "draft"]}
          onChange={setFilter}
        />
        <button className="btn btn-primary" onClick={onSubmit}>
          <I.Plus size={13} /> Submit new skill
        </button>
      </div>

      <div className="card col" style={{ padding: 0 }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: "minmax(200px,2fr) 110px 110px 90px 110px 110px 30px",
          gap: 16, padding: "11px 18px",
          borderBottom: "1px solid var(--line)",
          background: "var(--bg-soft)",
          font: "500 11.5px/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase",
          color: "var(--ink-3)",
        }}>
          <div>Skill</div>
          <div>Status</div>
          <div>Installs · 30d</div>
          <div>Rating</div>
          <div>Revenue · 30d</div>
          <div>Trend</div>
          <div></div>
        </div>
        {filtered.map((s, i) => (
          <button key={s.id} onClick={() => onOpenSkill(s.id)} className="unstyled"
            style={{
              display: "grid",
              gridTemplateColumns: "minmax(200px,2fr) 110px 110px 90px 110px 110px 30px",
              gap: 16, padding: "14px 18px", textAlign: "left",
              alignItems: "center",
              borderTop: i ? "1px solid var(--line-soft)" : "none",
              cursor: "pointer", background: "transparent",
            }}>
            <div className="col" style={{ minWidth: 0 }}>
              <div className="row gap-2" style={{ alignItems: "center" }}>
                <span style={{ font: "500 14px/1.2 var(--font-sans)" }}>{s.name}</span>
                {s.issues > 0 && (
                  <span style={{
                    width: 6, height: 6, borderRadius: 999, background: "#d97706",
                  }} title={`${s.issues} item${s.issues > 1 ? "s" : ""} need attention`} />
                )}
              </div>
              <div className="meta">
                {s.status === "draft" ? "Draft · " : ""}v{s.version} · {s.pricing}
              </div>
            </div>
            <div><StatusPill s={s.status} /></div>
            <div className="body-sm" style={{ color: s.installs30d ? "var(--ink-1)" : "var(--ink-4)" }}>
              {s.installs30d ? s.installs30d.toLocaleString() : "—"}
            </div>
            <div className="body-sm" style={{ color: s.rating ? "var(--ink-1)" : "var(--ink-4)" }}>
              {s.rating ? `★ ${s.rating}` : "—"}
            </div>
            <div className="body-sm" style={{ color: s.revenue30d ? "var(--ink-1)" : "var(--ink-4)" }}>
              {s.revenue30d ? `$${s.revenue30d.toLocaleString()}` : "—"}
            </div>
            <div>
              {s.status === "draft" ? (
                <div className="col gap-1">
                  <div style={{ height: 4, background: "var(--bg-muted)", borderRadius: 999, overflow: "hidden" }}>
                    <div style={{ width: `${(s.completion || 0) * 100}%`, height: "100%", background: "var(--iris-500)" }} />
                  </div>
                  <span className="meta">{Math.round((s.completion || 0) * 100)}% drafted</span>
                </div>
              ) : (
                <Sparkline data={s.trend} color="var(--iris-600)" />
              )}
            </div>
            <I.Arrow size={12} style={{ color: "var(--ink-4)" }} />
          </button>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────── SKILL DETAIL ───────────────────────────────
function CreatorSkillDetail({ skillId, onBack }) {
  const s = CREATOR_SKILLS.find(x => x.id === skillId) || CREATOR_SKILLS[0];
  const [tab, setTab] = useStateC("overview");

  const versions = [
    { v: s.version, date: "5 days ago", note: "Better handling of long transcripts. Fixes a crash on empty input.", current: true },
    { v: "0.9.0", date: "3 weeks ago", note: "Added Spanish, French. Faster cold-start." },
    { v: "0.8.4", date: "5 weeks ago", note: "Sample template improvements." },
    { v: "0.8.0", date: "2 months ago", note: "Initial public release." },
  ];

  const reviews = [
    { user: "@dawn.k", stars: 3, when: "2d", body: "Good output but I wish I could pick a different default tone. The PRD-style draft is too formal for engineering kickoffs.", replied: false },
    { user: "@tomas.r", stars: 5, when: "1w", body: "Replaced 3 different prompt templates I had floating around. Just works.", replied: true },
    { user: "@priya.s", stars: 4, when: "2w", body: "Solid. Would love a way to pin a glossary so it stops re-defining acronyms.", replied: true },
  ];

  return (
    <div className="col gap-5">
      <div className="row gap-2" style={{ alignItems: "center" }}>
        <button className="btn btn-sm btn-ghost" onClick={onBack}>
          <I.ChevL size={12} /> All skills
        </button>
      </div>

      <div className="row between gap-4 wrap" style={{ alignItems: "flex-start" }}>
        <div className="col gap-2" style={{ minWidth: 0 }}>
          <div className="row gap-2" style={{ alignItems: "center" }}>
            <h1 className="h2" style={{ margin: 0 }}>{s.name}</h1>
            <StatusPill s={s.status} />
          </div>
          <div className="meta">
            v{s.version} · {s.visibility} · {s.pricing} · {s.installsTotal.toLocaleString()} total installs
          </div>
        </div>
        <div className="row gap-2">
          <button className="btn">View on marketplace</button>
          <button className="btn">Edit metadata</button>
          <button className="btn btn-primary"><I.Plus size={12} /> Publish update</button>
        </div>
      </div>

      <div className="row gap-3 wrap">
        <StatCard label="Installs · 30d" value={s.installs30d.toLocaleString()} delta="+18.2%" />
        <StatCard label="Activation" value={`${Math.round(s.activation * 100)}%`} sub="Activated within 7d" />
        <StatCard label="Rating" value={`★ ${s.rating}`} sub={`${s.reviews} reviews`} />
        <StatCard label="Revenue · 30d" value={s.revenue30d ? `$${s.revenue30d.toLocaleString()}` : "Free"} delta={s.revenue30d ? "+22.4%" : null} />
      </div>

      <CTabs value={tab} onChange={setTab} options={[
        { id: "overview", label: "Overview" },
        { id: "versions", label: "Versions" },
        { id: "reviews", label: `Reviews · ${reviews.length}` },
        { id: "permissions", label: "Permissions" },
        { id: "settings", label: "Settings" },
      ]} />

      {tab === "overview" && (
        <div className="col gap-5">
          <div className="card col gap-3" style={{ padding: 20 }}>
            <div className="eyebrow">Installs over time · 90d</div>
            <Sparkline data={[120, 142, 168, 152, 184, 210, 198, 232, 256, 244, 288, 312]} w={800} h={140} color="var(--iris-600)" />
          </div>
          <div className="row gap-3 wrap">
            <div className="card col gap-2" style={{ padding: 18, flex: "1 1 280px" }}>
              <div className="eyebrow">Top use cases</div>
              {[
                ["Drafting PRDs from notes", 0.42],
                ["Meeting → spec hand-off", 0.28],
                ["Migrating legacy specs", 0.18],
                ["Other", 0.12],
              ].map(([label, pct]) => (
                <div key={label} className="col gap-1">
                  <div className="row between"><span className="body-sm">{label}</span><span className="meta">{Math.round(pct * 100)}%</span></div>
                  <div style={{ height: 4, background: "var(--bg-muted)", borderRadius: 999 }}>
                    <div style={{ width: `${pct * 100}%`, height: "100%", background: "var(--iris-500)", borderRadius: 999 }} />
                  </div>
                </div>
              ))}
            </div>
            <div className="card col gap-2" style={{ padding: 18, flex: "1 1 280px" }}>
              <div className="eyebrow">Where it runs</div>
              {[
                ["IrisGo runtime", 0.72],
                ["API", 0.18],
                ["CLI", 0.10],
              ].map(([label, pct]) => (
                <div key={label} className="row between" style={{ alignItems: "center" }}>
                  <span className="body-sm">{label}</span>
                  <div className="row gap-2" style={{ alignItems: "center" }}>
                    <div style={{ width: 80, height: 4, background: "var(--bg-muted)", borderRadius: 999 }}>
                      <div style={{ width: `${pct * 100}%`, height: "100%", background: "var(--iris-500)", borderRadius: 999 }} />
                    </div>
                    <span className="meta" style={{ minWidth: 32, textAlign: "right" }}>{Math.round(pct * 100)}%</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {tab === "versions" && (
        <div className="card col" style={{ padding: 0 }}>
          {versions.map((v, i) => (
            <div key={v.v} className="row gap-4" style={{
              padding: 16, borderTop: i ? "1px solid var(--line-soft)" : "none",
              alignItems: "flex-start",
            }}>
              <div className="col" style={{ flex: "0 0 120px" }}>
                <div className="row gap-2" style={{ alignItems: "baseline" }}>
                  <span style={{ font: "600 14px/1.2 var(--font-mono)" }}>v{v.v}</span>
                  {v.current && <span className="meta" style={{ color: "var(--green-700)" }}>Current</span>}
                </div>
                <span className="meta">{v.date}</span>
              </div>
              <div className="body-sm grow" style={{ color: "var(--ink-1)" }}>{v.note}</div>
              <button className="btn btn-sm">View diff</button>
            </div>
          ))}
        </div>
      )}

      {tab === "reviews" && (
        <div className="col gap-3">
          {reviews.map((r, i) => (
            <div key={i} className="card col gap-3" style={{ padding: 18 }}>
              <div className="row between" style={{ alignItems: "baseline" }}>
                <div className="row gap-2" style={{ alignItems: "baseline" }}>
                  <span style={{ font: "500 13px/1.2 var(--font-sans)" }}>{r.user}</span>
                  <span className="meta">{"★".repeat(r.stars)}{"☆".repeat(5 - r.stars)}</span>
                  <span className="meta">{r.when}</span>
                </div>
                {!r.replied && <span className="meta" style={{ color: "#b88200" }}>Awaiting reply</span>}
              </div>
              <div className="body-sm" style={{ color: "var(--ink-1)" }}>{r.body}</div>
              <div className="row gap-2">
                <button className="btn btn-sm">{r.replied ? "View thread" : "Reply"}</button>
                <button className="btn btn-sm btn-ghost">Mark resolved</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {tab === "permissions" && (
        <div className="card col" style={{ padding: 0 }}>
          {[
            { p: "Read files in working directory", scope: "Required", since: "v0.1.0" },
            { p: "Write Markdown files", scope: "Required", since: "v0.1.0" },
            { p: "Network: api.openai.com", scope: "Optional", since: "v0.8.0" },
          ].map((p, i) => (
            <div key={i} className="row gap-3" style={{ padding: "14px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none", alignItems: "center" }}>
              <I.Shield size={14} style={{ color: "var(--ink-3)" }} />
              <div className="col grow">
                <div className="body-sm" style={{ color: "var(--ink-1)" }}>{p.p}</div>
                <div className="meta">Declared since {p.since}</div>
              </div>
              <span className="meta">{p.scope}</span>
            </div>
          ))}
        </div>
      )}

      {tab === "settings" && (
        <div className="card col" style={{ padding: 0 }}>
          <SettingRow t="Visibility" d="Public on the marketplace." action="Change" />
          <SettingRow t="Pricing" d={s.pricing === "Free" ? "Free" : `${s.pricing} · 70/30 revenue share`} action="Change" />
          <SettingRow t="Auto-update" d="Patch versions auto-roll to all installs." action="Change" />
          <SettingRow t="Deprecate skill" d="Hide from search and prevent new installs. Existing installs keep working." action="Deprecate" danger />
        </div>
      )}
    </div>
  );
}

function SettingRow({ t, d, action, danger }) {
  return (
    <div className="row gap-4" style={{ padding: 16, borderTop: "1px solid var(--line-soft)", alignItems: "center" }}>
      <div className="col grow">
        <div className="body-sm" style={{ color: "var(--ink-1)", fontWeight: 500 }}>{t}</div>
        <div className="meta">{d}</div>
      </div>
      <button className="btn btn-sm" style={danger ? { color: "#a83227" } : null}>{action}</button>
    </div>
  );
}

// ─────────────────────────────── PAYOUTS ───────────────────────────────
function CreatorPayouts() {
  const months = [
    { m: "Apr 2026", gross: "$1,284", fees: "−$385", net: "$899", status: "Paid", date: "May 1" },
    { m: "Mar 2026", gross: "$1,050", fees: "−$315", net: "$735", status: "Paid", date: "Apr 1" },
    { m: "Feb 2026", gross: "$842",   fees: "−$253", net: "$589", status: "Paid", date: "Mar 1" },
    { m: "Jan 2026", gross: "$612",   fees: "−$184", net: "$428", status: "Paid", date: "Feb 1" },
  ];
  return (
    <div className="col gap-5">
      <div className="row gap-3 wrap">
        <StatCard label="Lifetime revenue" value="$8,420" sub="Across all paid skills" />
        <StatCard label="Pending payout" value="$246" sub="Settles May 1" />
        <StatCard label="Revenue share" value="70%" sub="Standard creator rate" />
      </div>
      <div className="card col" style={{ padding: 0 }}>
        <div className="row between" style={{ padding: "14px 18px", borderBottom: "1px solid var(--line)", alignItems: "center" }}>
          <div className="eyebrow">Payout method</div>
          <button className="btn btn-sm">Manage</button>
        </div>
        <div className="row gap-3" style={{ padding: 16, alignItems: "center" }}>
          <span style={{ width: 36, height: 36, borderRadius: 8, background: "var(--bg-muted)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <I.Code size={14} style={{ color: "var(--ink-2)" }} />
          </span>
          <div className="col grow">
            <div className="body-sm" style={{ fontWeight: 500 }}>Bank account · ••4218</div>
            <div className="meta">Wells Fargo · USD · monthly on the 1st</div>
          </div>
        </div>
      </div>

      <div className="col gap-2">
        <h3 className="h3" style={{ margin: 0 }}>Payout history</h3>
        <div className="card col" style={{ padding: 0 }}>
          <div style={{
            display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr 1fr 1fr",
            gap: 16, padding: "11px 18px",
            borderBottom: "1px solid var(--line)", background: "var(--bg-soft)",
            font: "500 11.5px/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase",
            color: "var(--ink-3)",
          }}>
            <div>Period</div><div>Gross</div><div>Fees</div><div>Net</div><div>Status</div><div>Paid on</div>
          </div>
          {months.map((r, i) => (
            <div key={r.m} style={{
              display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr 1fr 1fr",
              gap: 16, padding: "14px 18px", alignItems: "center",
              borderTop: i ? "1px solid var(--line-soft)" : "none",
            }}>
              <div className="body-sm" style={{ fontWeight: 500 }}>{r.m}</div>
              <div className="body-sm">{r.gross}</div>
              <div className="body-sm" style={{ color: "var(--ink-3)" }}>{r.fees}</div>
              <div className="body-sm" style={{ fontWeight: 500 }}>{r.net}</div>
              <div><StatusPill s="published" /></div>
              <div className="body-sm" style={{ color: "var(--ink-2)" }}>{r.date}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────── SUBMIT WIZARD ───────────────────────────────
// (kept compact — reuses the previous PublishScreen content)
function CreatorSubmit({ onCancel }) {
  return (
    <div className="col gap-5">
      <div className="row between" style={{ alignItems: "baseline" }}>
        <h2 className="h3" style={{ margin: 0 }}>Submit a new skill</h2>
        <button className="btn btn-sm btn-ghost" onClick={onCancel}>Cancel</button>
      </div>

      <div className="card col" style={{ padding: 0 }}>
        {[
          { i: "1", t: "Define metadata", d: "Name, one-liner, category, use cases, supported environments." , done: true},
          { i: "2", t: "Add invocation + samples", d: "Trigger, inputs, outputs, and 1–3 sample runs.", done: true },
          { i: "3", t: "Declare permissions", d: "Network, file system, and command execution scopes.", done: true },
          { i: "4", t: "Submit for security review", d: "Static analysis + behavioral run on a sandbox.", current: true },
          { i: "5", t: "Verify author identity", d: "Domain or org match. Optional but boosts trust score." },
          { i: "6", t: "Publish to public or private", d: "Choose visibility and rollout policy." },
        ].map((s, i) => (
          <div key={i} className="row gap-3" style={{
            padding: 16, borderTop: i ? "1px solid var(--line-soft)" : "none",
            alignItems: "flex-start",
            background: s.current ? "var(--iris-50)" : "transparent",
          }}>
            <span style={{
              width: 26, height: 26, borderRadius: 999,
              background: s.done ? "var(--green-600)" : s.current ? "var(--iris-700)" : "var(--bg-muted)",
              color: s.done || s.current ? "#fff" : "var(--ink-3)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              font: "600 12px/1 var(--font-mono)", flex: "0 0 auto",
            }}>{s.done ? <I.Check size={12} /> : s.i}</span>
            <div className="col grow">
              <div className="row gap-2" style={{ alignItems: "baseline" }}>
                <span style={{ font: "600 14px/1.2 var(--font-display)" }}>{s.t}</span>
                {s.done && <span className="meta" style={{ color: "var(--green-700)" }}>Done</span>}
                {s.current && <span className="meta" style={{ color: "var(--iris-700)" }}>In progress</span>}
              </div>
              <div className="body-sm text-2">{s.d}</div>
            </div>
            {s.current && <button className="btn btn-sm btn-primary">Continue</button>}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────── SHELL ───────────────────────────────
function CreatorStudio() {
  const [signedIn, setSignedIn] = useStateC(true);
  const [tab, setTab] = useStateC("overview"); // overview | skills | payouts | submit
  const [openSkill, setOpenSkill] = useStateC(null);

  if (!signedIn) return <CreatorSignIn onSignIn={() => setSignedIn(true)} />;

  return (
    <div className="page col gap-5" style={{ padding: "28px 28px 56px", maxWidth: 1240 }}>
      {/* Studio header */}
      <header className="col gap-3">
        <div className="row between gap-3 wrap" style={{ alignItems: "flex-end" }}>
          <div className="col gap-1">
            <div className="row gap-2">
              <span className="eyebrow" style={{ color: "var(--iris-700)" }}>Creator Studio</span>
              <span className="eyebrow text-4">·</span>
              <span className="eyebrow text-4">{CREATOR.handle}</span>
              {CREATOR.verified && (
                <span className="row gap-1" style={{ alignItems: "center", color: "var(--blue-700)", font: "500 11px/1 var(--font-sans)" }}>
                  <I.ShieldCheck size={11} /> Verified
                </span>
              )}
            </div>
            <h1 className="h2" style={{ margin: 0 }}>Welcome back, {CREATOR.name.split(" ")[0]}.</h1>
          </div>
          <div className="row gap-2">
            <button className="btn"><I.User size={13} /> Identity</button>
            <button className="btn-ghost btn" onClick={() => setSignedIn(false)}>Sign out</button>
          </div>
        </div>

        {/* Inner tabs */}
        <CTabs
          value={openSkill ? "__detail" : tab}
          onChange={(id) => { setTab(id); setOpenSkill(null); }}
          options={[
            { id: "overview", label: "Overview" },
            { id: "skills", label: `My skills · ${CREATOR_SKILLS.length}` },
            { id: "payouts", label: "Payouts" },
            { id: "submit", label: "Submit new" },
          ]} />
      </header>

      {openSkill ? (
        <CreatorSkillDetail skillId={openSkill} onBack={() => setOpenSkill(null)} />
      ) : tab === "overview" ? (
        <CreatorOverview onOpenSkill={(id) => { setTab("skills"); setOpenSkill(id); }} onTab={setTab} />
      ) : tab === "skills" ? (
        <CreatorSkills onOpenSkill={setOpenSkill} onSubmit={() => setTab("submit")} />
      ) : tab === "payouts" ? (
        <CreatorPayouts />
      ) : (
        <CreatorSubmit onCancel={() => setTab("skills")} />
      )}
    </div>
  );
}

window.CreatorStudio = CreatorStudio;
