// STUDIO SHELF — Three real technical artifacts. Trust without fake logos:
// engineers see this and know we're not bluffing.
// Tabs: Agentforce topic diagram (SVG) · Token routing config (YAML) · Agent runbook (markdown).

function StudioShelf() {
  const [tab, setTab] = useState("topic");

  return (
    <section className="section" id="shelf">
      <div className="shell">
        <SectionHead
          num="§ 05"
          label="STUDIO SHELF · REAL ARTIFACTS"
          title="The receipts, instead of logos."
          kicker="We're new to publishing case studies. We're not new to shipping. Three pieces of work from active engagements — redacted, real."
        />

        {/* Tabs */}
        <div style={{ display: "flex", gap: 0, marginBottom: 0, borderBottom: "1px solid var(--ink)", flexWrap: "wrap" }}>
          {[
            { id: "topic", label: "Agentforce topic", n: "01" },
            { id: "routing", label: "Token routing", n: "02" },
            { id: "runbook", label: "Agent runbook", n: "03" },
          ].map(t => {
            const active = tab === t.id;
            return (
              <button
                key={t.id}
                type="button"
                onClick={() => setTab(t.id)}
                style={{
                  padding: "16px 24px",
                  background: active ? "var(--ink)" : "transparent",
                  color: active ? "var(--bone)" : "var(--ink-2)",
                  border: "1px solid var(--ink)",
                  borderBottom: active ? "1px solid var(--ink)" : "none",
                  marginBottom: -1,
                  cursor: "pointer",
                  fontFamily: "var(--font-mono)",
                  fontSize: 12,
                  letterSpacing: "0.1em",
                  textTransform: "uppercase",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 10,
                  transition: "all 0.18s",
                }}
              >
                <span style={{ color: active ? "var(--persimmon)" : "var(--ink-mute)" }}>{t.n}</span>
                <span>{t.label}</span>
              </button>
            );
          })}
        </div>

        {/* Panels */}
        <div style={{ border: "1px solid var(--ink)", borderTop: "none", background: "var(--paper)" }}>
          {tab === "topic" && <ShelfTopic />}
          {tab === "routing" && <ShelfRouting />}
          {tab === "runbook" && <ShelfRunbook />}
        </div>

        {/* Footer */}
        <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
          <p className="body" style={{ margin: 0, maxWidth: "50ch", color: "var(--ink-soft)" }}>
            These are from work we're shipping today. Names removed, structure intact.
            Want to see the full unredacted versions under NDA?
          </p>
          <a href="contact.html#book" className="btn btn-ghost">Request a deep-dive <span className="arr">→</span></a>
        </div>
      </div>
    </section>
  );
}

// ── PANEL 1: AGENTFORCE TOPIC DIAGRAM (inline SVG) ─────────────
function ShelfTopic() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 0 }} className="shelf-grid">
      <div style={{ padding: "36px 40px", borderRight: "1px solid var(--rule)" }}>
        <p className="eyebrow" style={{ margin: 0 }}>FROM: B2B SAAS · 140 PPL · SALES CLOUD + CPQ</p>
        <h3 className="serif" style={{ margin: "12px 0 0 0", fontSize: "clamp(24px, 2.6vw, 36px)", lineHeight: 1.05, letterSpacing: "-0.02em" }}>
          Renewal voice agent — topic graph.
        </h3>
        <p className="body" style={{ marginTop: 16, color: "var(--ink-soft)", maxWidth: "50ch" }}>
          One root topic, six tools, three escalation paths. Total reading time before a developer
          could ship a clone: about ten minutes. That's the bar.
        </p>

        <ul style={{ marginTop: 24, padding: 0, listStyle: "none", display: "grid", gap: 12 }}>
          {[
            ["Identify caller", "Match phone → Contact → Opportunity"],
            ["Pull renewal context", "Recent activity, opened-not-replied emails, stage"],
            ["Negotiate scope", "Confirm seats, tier, term"],
            ["Schedule + handoff", "Book AE if signal, deflect if not"],
          ].map(([k, v], i) => (
            <li key={k} style={{ display: "grid", gridTemplateColumns: "24px 1fr", gap: 12 }}>
              <span className="mono" style={{ fontSize: 11, color: "var(--persimmon)", paddingTop: 2 }}>{String(i + 1).padStart(2, "0")}</span>
              <div>
                <div style={{ fontWeight: 600, fontSize: 15 }}>{k}</div>
                <div className="body-sm" style={{ color: "var(--ink-soft)" }}>{v}</div>
              </div>
            </li>
          ))}
        </ul>
      </div>

      <div style={{ padding: 32, background: "var(--paper-2)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <TopicDiagram />
      </div>

      <style>{`
        @media (max-width: 980px) {
          .shelf-grid { grid-template-columns: 1fr !important; }
          .shelf-grid > div:first-child { border-right: none !important; border-bottom: 1px solid var(--rule); }
        }
      `}</style>
    </div>
  );
}

function TopicDiagram() {
  return (
    <svg viewBox="0 0 360 320" style={{ width: "100%", maxWidth: 360, height: "auto" }} aria-label="Agentforce topic diagram">
      <defs>
        <marker id="arrow" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto" markerUnits="strokeWidth">
          <path d="M0,0 L6,4 L0,8 z" fill="var(--ink)" />
        </marker>
      </defs>
      {/* Connectors */}
      <g stroke="var(--ink)" strokeWidth="1" fill="none" markerEnd="url(#arrow)">
        <line x1="180" y1="46" x2="180" y2="92" />
        <line x1="180" y1="142" x2="100" y2="180" />
        <line x1="180" y1="142" x2="180" y2="180" />
        <line x1="180" y1="142" x2="260" y2="180" />
        <line x1="100" y1="230" x2="100" y2="266" />
        <line x1="180" y1="230" x2="180" y2="266" />
        <line x1="260" y1="230" x2="260" y2="266" />
      </g>
      {/* Root */}
      <g>
        <rect x="120" y="18" width="120" height="28" fill="var(--persimmon)" stroke="var(--ink)"/>
        <text x="180" y="36" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" fontWeight="600" fill="var(--ink)">RENEWAL_TOPIC</text>
      </g>
      {/* Decision */}
      <g>
        <polygon points="180,92 230,117 180,142 130,117" fill="var(--bone)" stroke="var(--ink)" />
        <text x="180" y="121" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink)">classify</text>
      </g>
      {/* Three branches */}
      {[
        { x: 50, label: "lookup_opp", color: "var(--cobalt)" },
        { x: 130, label: "draft_quote", color: "var(--cobalt)" },
        { x: 210, label: "book_call", color: "var(--cobalt)" },
      ].map((b, i) => (
        <g key={i}>
          <rect x={b.x} y="180" width="100" height="50" fill={b.color} stroke="var(--ink)" />
          <text x={b.x + 50} y="202" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fontWeight="600" fill="var(--bone)">TOOL</text>
          <text x={b.x + 50} y="218" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" fill="var(--bone)">{b.label}</text>
        </g>
      ))}
      {/* Outcomes */}
      {[
        { x: 50, label: "Opp ctx", c: "var(--bone)" },
        { x: 130, label: "Quote DOC", c: "var(--bone)" },
        { x: 210, label: "Calendar evt", c: "var(--bone)" },
      ].map((o, i) => (
        <g key={i}>
          <rect x={o.x} y="266" width="100" height="34" fill={o.c} stroke="var(--ink)" />
          <text x={o.x + 50} y="287" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" fill="var(--ink)">{o.label}</text>
        </g>
      ))}
    </svg>
  );
}

// ── PANEL 2: TOKEN ROUTING YAML ─────────────────────────────────
function ShelfRouting() {
  const yaml = `# routing.yaml — production · 2026-05
# Drives per-turn model selection for the renewal voice agent.

agent: renewal_voice
default_model: openai/gpt-realtime
default_voice: verse

routes:
  - when: turn.kind == "greeting"
    model: openai/gpt-realtime-mini
    max_tokens: 80
    note: "8.2k turns/month — saves ~$140/mo"

  - when: turn.kind == "small_talk"
    model: openai/gpt-realtime-mini
    max_tokens: 60

  - when: turn.kind == "tool_decision"
    model: openai/gpt-realtime
    max_tokens: 240

  - when: turn.kind == "negotiation"
    model: anthropic/sonnet-4-realtime
    max_tokens: 320
    note: "Better nuance on price pushback"

  - when: turn.kind == "escalation"
    model: openai/gpt-realtime
    max_tokens: 200
    bypass_cache: true

context_pruning:
  keep_last_n_turns: 6
  always_keep:
    - system_prompt
    - active_opportunity
  evict:
    - prior_tool_outputs:
        if: age_turns > 4

cache:
  prompt_prefix_cache: true
  static_facts:
    ttl_seconds: 3600
    items: ["pricing_tiers", "team_bios", "office_hours"]

cost_budget_per_call_usd: 1.20
fail_open: true   # if route fails, fall back to default_model`;

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 0 }} className="shelf-grid">
      <div style={{ padding: "36px 40px", borderRight: "1px solid var(--rule)" }}>
        <p className="eyebrow" style={{ margin: 0 }}>FROM: TOKEN OPTIMIZATION ENGAGEMENT</p>
        <h3 className="serif" style={{ margin: "12px 0 0 0", fontSize: "clamp(24px, 2.6vw, 36px)", lineHeight: 1.05, letterSpacing: "-0.02em" }}>
          Per-turn model routing config.
        </h3>
        <p className="body" style={{ marginTop: 16, color: "var(--ink-soft)" }}>
          Real YAML from a real agent in production. The boring shape is the point —
          this is what saves you 40% of your bill without changing the agent's voice.
        </p>

        <div style={{ marginTop: 28, padding: 16, background: "var(--paper-2)", border: "1px solid var(--rule)" }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 8 }}>
            What it does
          </div>
          <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "grid", gap: 8, fontSize: 13 }}>
            <li>→ Greetings + small talk routed to a small, cheap model</li>
            <li>→ Negotiation moments routed to Sonnet for nuance</li>
            <li>→ Static facts cached for 1 hour</li>
            <li>→ Hard budget cap with fail-open behavior</li>
          </ul>
        </div>
      </div>

      <div style={{ padding: 0, background: "#1a1d22", minHeight: 480, overflow: "hidden", position: "relative" }}>
        <div style={{
          padding: "12px 20px",
          borderBottom: "1px solid color-mix(in oklab, #f0eddf 14%, transparent)",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          fontFamily: "var(--font-mono)",
          fontSize: 11,
          color: "color-mix(in oklab, #f0eddf 65%, transparent)",
          letterSpacing: "0.1em",
          textTransform: "uppercase",
        }}>
          <span>routing.yaml</span>
          <span style={{ color: "var(--persimmon)" }}>● production</span>
        </div>
        <pre style={{
          margin: 0,
          padding: "20px 24px",
          fontFamily: "var(--font-mono)",
          fontSize: 12,
          lineHeight: 1.55,
          color: "#f0eddf",
          overflow: "auto",
          maxHeight: 520,
        }}><CodeYaml text={yaml} /></pre>
      </div>
    </div>
  );
}

function CodeYaml({ text }) {
  // Lightweight syntax coloring without a library.
  const lines = text.split("\n");
  return (
    <>
      {lines.map((line, i) => {
        let out = line;
        if (/^\s*#/.test(line)) {
          return <div key={i} style={{ color: "color-mix(in oklab, #f0eddf 45%, transparent)" }}>{line}</div>;
        }
        const m = line.match(/^(\s*-?\s*)([a-zA-Z_]+)(\s*:)(.*)$/);
        if (m) {
          return (
            <div key={i}>
              {m[1]}
              <span style={{ color: "#d4a017" }}>{m[2]}</span>
              <span style={{ color: "color-mix(in oklab, #f0eddf 55%, transparent)" }}>{m[3]}</span>
              <ValuePart text={m[4]} />
            </div>
          );
        }
        return <div key={i}>{line}</div>;
      })}
    </>
  );
}

function ValuePart({ text }) {
  if (!text.trim()) return null;
  if (/^\s*(true|false)\s*$/.test(text)) return <span style={{ color: "#c8421e" }}>{text}</span>;
  if (/^\s*[0-9.]+\s*$/.test(text)) return <span style={{ color: "#c8421e" }}>{text}</span>;
  if (/^\s*".+"\s*$/.test(text)) return <span style={{ color: "#a5d6a7" }}>{text}</span>;
  return <span style={{ color: "#f0eddf" }}>{text}</span>;
}

// ── PANEL 3: AGENT RUNBOOK MARKDOWN ─────────────────────────────
function ShelfRunbook() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 0 }} className="shelf-grid">
      <div style={{ padding: "36px 40px", borderRight: "1px solid var(--rule)" }}>
        <p className="eyebrow" style={{ margin: 0 }}>FROM: SUPPORT TRIAGE AGENT · LIVE</p>
        <h3 className="serif" style={{ margin: "12px 0 0 0", fontSize: "clamp(24px, 2.6vw, 36px)", lineHeight: 1.05, letterSpacing: "-0.02em" }}>
          The agent runbook.
        </h3>
        <p className="body" style={{ marginTop: 16, color: "var(--ink-soft)" }}>
          Every agent we ship has one of these. Job, tools, escalations, five things it will
          never say. Your auditors get the same copy your admin gets.
        </p>
        <div style={{ marginTop: 24, padding: 14, border: "1px dashed var(--rule-strong)", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-soft)", letterSpacing: "0.04em" }}>
          ↳ One page per agent. Versioned in git alongside the prompt.
        </div>
      </div>

      <div style={{ padding: "32px 40px", background: "var(--paper)", maxHeight: 560, overflowY: "auto" }}>
        <article style={{ fontFamily: "var(--font-ui)", color: "var(--ink)" }}>
          <p className="mono" style={{ margin: 0, fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
            agents/support-triage/runbook.md · v1.4 · 2026-05-18
          </p>
          <h4 className="serif" style={{ margin: "16px 0 0 0", fontSize: 28, lineHeight: 1.05, letterSpacing: "-0.025em" }}># Support Triage Agent</h4>
          <h5 className="serif" style={{ margin: "28px 0 8px 0", fontSize: 18, letterSpacing: "-0.015em" }}>## Job</h5>
          <p style={{ margin: 0, fontSize: 14, lineHeight: 1.5, color: "var(--ink-2)" }}>
            Resolve Tier-1 support tickets end-to-end. Escalate the rest with a one-paragraph
            summary. Never make a human wait more than 8 seconds.
          </p>

          <h5 className="serif" style={{ margin: "28px 0 8px 0", fontSize: 18, letterSpacing: "-0.015em" }}>## Tools</h5>
          <ul style={{ margin: 0, paddingLeft: 20, fontSize: 14, lineHeight: 1.6 }}>
            <li><code style={{ background: "var(--paper-2)", padding: "0 4px", fontFamily: "var(--font-mono)", fontSize: 12 }}>lookupAccount(email)</code> — pull account, plan, recent tickets</li>
            <li><code style={{ background: "var(--paper-2)", padding: "0 4px", fontFamily: "var(--font-mono)", fontSize: 12 }}>resetPassword(accountId)</code> — synchronous, idempotent</li>
            <li><code style={{ background: "var(--paper-2)", padding: "0 4px", fontFamily: "var(--font-mono)", fontSize: 12 }}>createCase(severity, summary)</code> — when escalating</li>
            <li><code style={{ background: "var(--paper-2)", padding: "0 4px", fontFamily: "var(--font-mono)", fontSize: 12 }}>findArticle(query)</code> — KB search, returns top 3</li>
          </ul>

          <h5 className="serif" style={{ margin: "28px 0 8px 0", fontSize: 18, letterSpacing: "-0.015em" }}>## Escalation triggers</h5>
          <ol style={{ margin: 0, paddingLeft: 20, fontSize: 14, lineHeight: 1.6 }}>
            <li>Billing dispute &gt; $500 → human, severity 2</li>
            <li>Outage report → human, severity 1</li>
            <li>Three failed tool calls in one session → human</li>
            <li>Customer asks "let me talk to a person" → human, no negotiation</li>
            <li>Anything involving cancellation, refund, or legal language</li>
          </ol>

          <h5 className="serif" style={{ margin: "28px 0 8px 0", fontSize: 18, letterSpacing: "-0.015em" }}>## Five things this agent will never say</h5>
          <ol style={{ margin: 0, paddingLeft: 20, fontSize: 14, lineHeight: 1.6, color: "var(--persimmon-deep)" }}>
            <li>"I understand how frustrating that must be." (banned filler)</li>
            <li>Any promise of a refund — that's a human call</li>
            <li>Any quote about future product roadmap</li>
            <li>The phrase "as an AI"</li>
            <li>A discount it wasn't specifically authorized to offer</li>
          </ol>

          <h5 className="serif" style={{ margin: "28px 0 8px 0", fontSize: 18, letterSpacing: "-0.015em" }}>## SLA</h5>
          <table style={{ fontSize: 13, borderCollapse: "collapse", marginTop: 6 }}>
            <tbody>
              <tr><td style={{ padding: "4px 14px 4px 0", color: "var(--ink-soft)" }}>First response</td><td style={{ padding: "4px 0", fontFamily: "var(--font-mono)" }}>&lt; 2s</td></tr>
              <tr><td style={{ padding: "4px 14px 4px 0", color: "var(--ink-soft)" }}>Resolution (in-scope)</td><td style={{ padding: "4px 0", fontFamily: "var(--font-mono)" }}>&lt; 90s</td></tr>
              <tr><td style={{ padding: "4px 14px 4px 0", color: "var(--ink-soft)" }}>Escalation handoff</td><td style={{ padding: "4px 0", fontFamily: "var(--font-mono)" }}>&lt; 8s</td></tr>
            </tbody>
          </table>
        </article>
      </div>
    </div>
  );
}

Object.assign(window, { StudioShelf });
