// ============================================================
// Universal Tool Graph — full chain from Slack msg to final deliverable
// ============================================================

function ToolGraphSection() {
  const [step, setStep] = React.useState(0);
  const [auto, setAuto] = React.useState(true);

  // Full provenance chain: raw signal → knowledge lookup → agent work → deliverable
  const chain = [
    {
      stage: "TRIGGER",
      tool: "Slack",
      icon: "chat",
      who: "Dana Ortiz",
      label: "DM to Signal (CoS)",
      body: "Can you put together a proposal draft for Acme by EOD Thursday? They want pricing + a rollout plan.",
      meta: "T-0 · 2:14pm · #signal-dm",
      color: "primary",
    },
    {
      stage: "PARSE",
      tool: "Signal · CoS",
      icon: "hub",
      who: "Signal",
      label: "Intent extracted · mission opened",
      body: "MISSION#8241 — Draft proposal for Acme Corp. Scope: pricing tiers, rollout plan, exec summary. Due: Thu 18:00.",
      meta: "T+0:03 · classified as DEAL_CLOSE · high priority",
      color: "primary",
    },
    {
      stage: "RECALL",
      tool: "Tool Graph",
      icon: "account_tree",
      who: "Knowledge lookup",
      label: "Pulled 14 nodes across 6 tools",
      nodes: [
        { tool: "Gmail", label: "Acme intro thread · 22 msgs", weight: 0.91 },
        { tool: "Zoom",  label: "Discovery call · 48min transcript", weight: 0.88 },
        { tool: "Granola", label: "Follow-up notes · 3 meetings", weight: 0.82 },
        { tool: "Hubspot", label: "Deal: Acme Corp · $240k ARR", weight: 0.79 },
        { tool: "Notion", label: "Proposal template v4", weight: 0.74 },
        { tool: "Drive", label: "Pricing matrix · Q4 2025", weight: 0.71 },
        { tool: "Slack", label: "#deal-acme · 180 msgs", weight: 0.67 },
      ],
      meta: "T+0:08 · permissions: Dana's scope · redacted 3 legal nodes",
      color: "secondary",
    },
    {
      stage: "DELEGATE",
      tool: "Signal → CMO · CRO · CFO",
      icon: "share",
      who: "Signal",
      label: "Fanout to 3 functional chiefs",
      delegations: [
        { to: "Trail · CMO", task: "Write exec summary + narrative. Voice: Dana's.", eta: "2h" },
        { to: "Ledger · CRO", task: "Assemble pricing tiers from Hubspot + matrix.", eta: "45m" },
        { to: "Chart · Insights", task: "Compose rollout plan referencing Q4 2025 playbook.", eta: "1h" },
      ],
      meta: "T+0:12 · parallel execution · coordinated merge",
      color: "primary",
    },
    {
      stage: "CROSS-ORG",
      tool: "Signal ↔ Axis",
      icon: "swap_horiz",
      who: "Peer Chief call",
      label: "Procurement ETA needed",
      body: "Signal → Axis: \"Need procurement/legal review timeline for Acme (standard MSA, $240k).\"  Axis → Parley → Charter → replies: \"3 business days, no redlines expected.\"",
      meta: "T+0:19 · agent-to-agent · no human involved",
      color: "secondary",
    },
    {
      stage: "DRAFT",
      tool: "Drive · Google Docs",
      icon: "description",
      who: "Trail · CMO agent",
      label: "Assembled draft v1 · 6 pages",
      body: "Draft cites 14 source nodes inline. Every claim links back to the thread, transcript, or doc it came from.",
      meta: "T+1:47 · 2,140 words · 14 citations",
      color: "primary",
    },
    {
      stage: "REVIEW",
      tool: "Human in the loop",
      icon: "fingerprint",
      who: "Dana Ortiz",
      label: "Approved with 2 edits",
      body: "Dana tightened the opener and adjusted Tier 2 pricing. Edits written back to the graph as preference signals.",
      meta: "T+2:04 · 6 min review · preferences saved to memory",
      color: "primary",
    },
    {
      stage: "DELIVER",
      tool: "Gmail",
      icon: "outgoing_mail",
      who: "Signal",
      label: "Sent to Acme procurement",
      body: "Subject: \"Acme × Parallel · Proposal v1 · Rollout Plan\"  —  attached PDF + editable Docs link. CC'd to Dana, internal deal channel updated.",
      meta: "T+2:07 · delivered · Hubspot stage → Proposal Sent",
      color: "secondary",
    },
  ];

  // Autoplay
  React.useEffect(() => {
    if (!auto) return;
    const id = setInterval(() => setStep(s => (s + 1) % chain.length), 3200);
    return () => clearInterval(id);
  }, [auto]);

  const current = chain[step];

  return (
    <section className="py-16 md:py-24 lg:py-32 bg-surface relative overflow-hidden border-y border-outline-variant/10">
      <GridBackdrop className="text-primary" opacity={0.04} />
      <div className="max-w-screen-2xl mx-auto px-4 sm:px-6 md:px-8 relative">
        <div className="grid lg:grid-cols-12 gap-16 mb-16">
          <Reveal className="lg:col-span-5">
            <SectionTag num="CTRL·07">A mission, end-to-end</SectionTag>
            <h2 className="font-headline text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-bold tracking-[-0.03em] leading-[1.05] mb-8">
              One sentence in.<br />
              <span className="text-primary italic">A finished artifact out.</span>
            </h2>
          </Reveal>
          <Reveal delay={200} className="lg:col-span-6 lg:col-start-7 flex items-end">
            <p className="text-on-surface-variant text-lg leading-relaxed">
              Every mission runs the same shape: <span className="text-on-surface">Plan → Approve → Execute → Review.</span> Watch one intent travel the loop — parsed into a mission, cross-referenced across your tools, delegated across a sub-org, cleared by a peer Chief, drafted, reviewed, and delivered. Every node is cited. Every hop is logged.
            </p>
          </Reveal>
        </div>

        {/* Intent bar — the kickoff */}
        <Reveal>
          <div className="bg-surface-container-lowest border border-primary/50 px-6 py-5 mb-px relative">
            <div className="font-label text-[10px] tracking-[0.3em] text-primary uppercase mb-2">◉ Intent · from Dana</div>
            <div className="font-headline text-xl md:text-2xl text-on-surface leading-snug">
              "Put together a proposal draft for Acme by EOD Thursday — pricing tiers + a rollout plan."
            </div>
          </div>
        </Reveal>

        {/* 4-phase lifecycle strip (deck slide 09) */}
        <Reveal delay={120}>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-px bg-outline-variant/15 mb-6">
            {[
              { k: "§01 · Plan",    side: "Chief",  body: "CoS drafts the mission. Agents, sources, HITL checkpoints, ETA — all visible.", active: step <= 1 },
              { k: "§02 · Approve", side: "Human",  body: "You greenlight scope, budget, and tool permissions. One click.",                 active: step === 1 },
              { k: "§03 · Execute", side: "Agents", body: "The phantom org pulls data, drafts, cross-checks. Live receipts. Replayable.",   active: step >= 2 && step <= 5 },
              { k: "§04 · Review",  side: "Human",  body: "Artifact returns. You approve, edit, redirect. Edits propagate. Saved as playbook.", active: step >= 6 },
            ].map((p, i) => (
              <div key={i} className={`p-5 transition-colors ${p.active ? "bg-primary/[0.06]" : "bg-surface-container-lowest"}`}>
                <div className="flex items-baseline justify-between mb-3">
                  <span className={`font-label text-[10px] tracking-[0.28em] uppercase ${p.active ? "text-primary" : "text-outline"}`}>{p.k}</span>
                  <span className={`font-label text-[9px] tracking-[0.22em] px-2 py-0.5 ${
                    p.side === "Human" ? "bg-primary/15 text-primary" :
                    p.side === "Chief" ? "bg-secondary/15 text-secondary" :
                    "bg-tertiary/15 text-tertiary"
                  }`}>{p.side.toUpperCase()}</span>
                </div>
                <div className="font-body text-sm text-on-surface-variant leading-snug">{p.body}</div>
              </div>
            ))}
          </div>
        </Reveal>

        {/* Mission header */}
        <div className="bg-surface-container border-l-2 border-primary p-5 mb-px flex items-center gap-6 flex-wrap">
          <div>
            <div className="font-label text-[9px] tracking-[0.3em] text-outline uppercase mb-1">Mission · Live replay</div>
            <div className="font-headline text-lg font-bold">#8241 — Acme Corp proposal</div>
          </div>
          <div className="flex items-center gap-2 ml-auto">
            <span className="font-label text-[10px] tracking-widest text-outline uppercase">Step {step + 1}/{chain.length}</span>
            <button onClick={() => { setAuto(a => !a); }}
              className="font-label text-[10px] tracking-[0.2em] uppercase px-3 py-1.5 bg-surface-container-high hover:bg-surface-container-highest transition-colors">
              {auto ? "⏸ Pause" : "▶ Play"}
            </button>
            <button onClick={() => setStep(s => (s - 1 + chain.length) % chain.length)}
              className="font-label text-[10px] tracking-[0.2em] uppercase px-3 py-1.5 bg-surface-container-high hover:bg-surface-container-highest transition-colors">◀</button>
            <button onClick={() => setStep(s => (s + 1) % chain.length)}
              className="font-label text-[10px] tracking-[0.2em] uppercase px-3 py-1.5 bg-surface-container-high hover:bg-surface-container-highest transition-colors">▶</button>
          </div>
        </div>

        {/* Main layout: timeline | detail panel | graph */}
        <div className="grid lg:grid-cols-12 gap-px bg-outline-variant/15">
          {/* Timeline rail */}
          <div className="lg:col-span-3 bg-surface-container-lowest p-6">
            <TeleLabel className="mb-4 block">Chain</TeleLabel>
            <div className="space-y-px">
              {chain.map((c, i) => {
                const active = i === step;
                const done = i < step;
                return (
                  <button key={i} onClick={() => { setAuto(false); setStep(i); }}
                    className={`w-full text-left flex items-start gap-3 p-3 transition-colors ${active ? "bg-primary/15" : done ? "bg-surface-container/60 hover:bg-surface-container" : "hover:bg-surface-container/40"}`}>
                    <div className="flex flex-col items-center shrink-0 mt-1">
                      <span className={`w-5 h-5 flex items-center justify-center font-label text-[9px] font-bold ${active ? "bg-primary text-on-primary" : done ? "bg-secondary text-on-secondary" : "bg-surface-container-high text-outline"}`}>
                        {done ? "✓" : String(i + 1).padStart(2, "0")}
                      </span>
                      {i < chain.length - 1 && <span className={`w-px h-5 mt-1 ${done || active ? "bg-primary/50" : "bg-outline-variant/20"}`} />}
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className={`font-label text-[9px] tracking-[0.25em] uppercase mb-0.5 ${active ? "text-primary" : done ? "text-secondary" : "text-outline"}`}>{c.stage}</div>
                      <div className="font-headline text-xs font-bold truncate">{c.tool}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Detail panel */}
          <div className="lg:col-span-6 bg-surface-container-lowest p-8 min-h-[500px]">
            <div className="flex items-center gap-3 mb-5">
              <div className={`w-10 h-10 bg-${current.color}/15 flex items-center justify-center`}>
                <span className={`material-symbols-outlined text-${current.color}`} style={{ fontSize: 22 }}>{current.icon}</span>
              </div>
              <div>
                <div className={`font-label text-[9px] tracking-[0.3em] uppercase text-${current.color}`}>{current.stage} · {current.tool}</div>
                <div className="font-headline text-xl font-bold leading-tight">{current.label}</div>
                <div className="font-label text-[10px] text-outline tracking-wider uppercase mt-0.5">{current.who}</div>
              </div>
            </div>

            {current.body && (
              <div className="bg-surface-container p-5 mb-4 text-sm text-on-surface leading-relaxed border-l border-outline-variant/20">
                {current.body}
              </div>
            )}

            {current.nodes && (
              <div className="space-y-px bg-outline-variant/10">
                {current.nodes.map((n, i) => (
                  <div key={i} className="bg-surface-container flex items-center gap-3 p-3 animate-[fadeInUp_0.3s_ease-out_both]" style={{ animationDelay: `${i * 40}ms` }}>
                    <span className="font-label text-[9px] tracking-[0.25em] uppercase text-primary w-20 shrink-0">{n.tool}</span>
                    <span className="text-sm text-on-surface flex-1 truncate">{n.label}</span>
                    <div className="flex items-center gap-2 shrink-0">
                      <div className="w-20 h-1 bg-surface-container-high relative overflow-hidden">
                        <div className="absolute inset-y-0 left-0 bg-primary" style={{ width: `${n.weight * 100}%` }} />
                      </div>
                      <span className="font-label text-[10px] text-outline tracking-widest w-8 text-right">{n.weight.toFixed(2)}</span>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {current.delegations && (
              <div className="space-y-px bg-outline-variant/10">
                {current.delegations.map((d, i) => (
                  <div key={i} className="bg-surface-container p-4 animate-[fadeInUp_0.3s_ease-out_both]" style={{ animationDelay: `${i * 60}ms` }}>
                    <div className="flex items-center gap-2 mb-1">
                      <span className="w-5 h-5 bg-primary/15 text-primary flex items-center justify-center font-label text-[10px]">→</span>
                      <span className="font-headline text-sm font-bold">{d.to}</span>
                      <span className="ml-auto font-label text-[9px] tracking-widest uppercase text-outline">ETA {d.eta}</span>
                    </div>
                    <div className="text-sm text-on-surface-variant ml-7">{d.task}</div>
                  </div>
                ))}
              </div>
            )}

            <div className="mt-6 pt-4 border-t border-outline-variant/10 flex items-center gap-2 font-label text-[10px] text-outline tracking-wider uppercase">
              <StatusDot state={current.color === "secondary" ? "nominal" : "warn"} />
              <span>{current.meta}</span>
            </div>
          </div>

          {/* Graph visualization */}
          <div className="lg:col-span-3 bg-surface-container-lowest p-6 relative">
            <TeleLabel className="mb-4 block">Graph · Live</TeleLabel>
            <div className="relative aspect-square">
              <svg viewBox="0 0 200 200" className="w-full h-full">
                <defs>
                  <radialGradient id="nodeglow" cx="50%" cy="50%" r="50%">
                    <stop offset="0%" stopColor="#ffc880" stopOpacity="0.4" />
                    <stop offset="100%" stopColor="#ffc880" stopOpacity="0" />
                  </radialGradient>
                </defs>
                {/* Edges */}
                {[
                  { a: [100, 100], b: [40, 40],  tool: "Slack" },
                  { a: [100, 100], b: [160, 40], tool: "Gmail" },
                  { a: [100, 100], b: [30, 100], tool: "Zoom" },
                  { a: [100, 100], b: [170, 100], tool: "Hubspot" },
                  { a: [100, 100], b: [40, 160], tool: "Notion" },
                  { a: [100, 100], b: [160, 160], tool: "Drive" },
                  { a: [100, 100], b: [100, 25],  tool: "Granola" },
                  { a: [100, 100], b: [100, 175], tool: "Linear" },
                ].map((e, i) => {
                  const active = step >= 2 && step <= 5;
                  return (
                    <line key={i}
                      x1={e.a[0]} y1={e.a[1]} x2={e.b[0]} y2={e.b[1]}
                      stroke={active ? "#ffc880" : "#524534"}
                      strokeOpacity={active ? 0.6 : 0.25}
                      strokeWidth={active ? 0.6 : 0.4}
                      strokeDasharray={active ? "2 1.5" : ""}
                      style={active ? { animation: `dash 1.2s linear infinite`, animationDelay: `${i * 0.1}s` } : {}} />
                  );
                })}
                {/* Center CoS node */}
                <circle cx="100" cy="100" r="14" fill="url(#nodeglow)" />
                <circle cx="100" cy="100" r="6" fill="#ffc880" />
                <text x="100" y="120" textAnchor="middle" fontSize="5" fill="#ffc880" fontFamily="IBM Plex Mono" letterSpacing="1">SIGNAL</text>
                {/* Peripheral tool nodes */}
                {[
                  { x: 40, y: 40,   label: "SLACK" },
                  { x: 160, y: 40,  label: "GMAIL" },
                  { x: 30, y: 100,  label: "ZOOM" },
                  { x: 170, y: 100, label: "HUBSPOT" },
                  { x: 40, y: 160,  label: "NOTION" },
                  { x: 160, y: 160, label: "DRIVE" },
                  { x: 100, y: 25,  label: "GRANOLA" },
                  { x: 100, y: 175, label: "LINEAR" },
                ].map((n, i) => (
                  <g key={i}>
                    <circle cx={n.x} cy={n.y} r="3" fill="#9f8e7a" />
                    <text x={n.x} y={n.y + 9} textAnchor="middle" fontSize="4" fill="#9f8e7a" fontFamily="IBM Plex Mono">{n.label}</text>
                  </g>
                ))}
              </svg>
              {/* Live overlay */}
              <div className="absolute top-0 right-0 font-label text-[9px] text-outline tracking-wider uppercase text-right space-y-0.5">
                <div>Graph · <span className="text-on-surface">live</span></div>
                <div>Nodes · <span className="text-on-surface">in scope</span></div>
                <div>Perm · <span className="text-secondary">scoped</span></div>
              </div>
            </div>
            <div className="mt-6 pt-4 border-t border-outline-variant/10 space-y-2 font-label text-[10px]">
              <div className="flex items-center justify-between">
                <span className="text-outline tracking-widest uppercase">Access scope</span>
                <span className="text-secondary">Dana Ortiz</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-outline tracking-widest uppercase">Redacted</span>
                <span className="text-primary">3 nodes</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-outline tracking-widest uppercase">Citations</span>
                <span className="text-on-surface">14 inline</span>
              </div>
            </div>
          </div>
        </div>

        {/* Footer — audit guarantees */}
        <div className="grid md:grid-cols-4 gap-px bg-outline-variant/15 mt-px">
          {[
            { k: "Every claim cited", v: "Inline provenance on every sentence of every draft." },
            { k: "Every hop logged", v: "Agent-to-agent handoffs kept for replay and audit." },
            { k: "Permission-scoped", v: "Agents see only what the requesting human can see." },
            { k: "Replayable end-to-end", v: "Rewind any mission from trigger to delivery." },
          ].map((f, i) => (
            <div key={i} className="bg-surface-container-lowest p-6">
              <div className="font-label text-[9px] tracking-[0.3em] text-primary uppercase mb-2">0{i+1}</div>
              <div className="font-headline text-sm font-bold mb-1">{f.k}</div>
              <div className="text-xs text-on-surface-variant leading-relaxed">{f.v}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ToolGraphSection });
