// Anologe — "How we operate" diagram + AI workflow diagram

const STEPS = [
  {
    n: '01',
    name: 'Intake',
    short: 'Audit',
    desc: 'A 30‑minute working session with a partner. We leave with a scope memo, a system inventory, and a list of the first three things we\'d rebuild.',
    meta: ['1 working session', 'Scope memo', 'System inventory'],
    dur: 'Wk 0'
  },
  {
    n: '02',
    name: 'Map',
    short: 'Model',
    desc: 'We document your current operations as code — schemas, flows, ownership, monitoring. The map becomes the source of truth for the engagement.',
    meta: ['Schema diff', 'Flow inventory', 'Ownership map'],
    dur: 'Wk 1–2'
  },
  {
    n: '03',
    name: 'Deploy',
    short: 'Install',
    desc: 'We build and install. Each system ships with runbooks, eval suites, alerting, and a documented owner. Versioned, deployed, monitored.',
    meta: ['Runbooks', 'Evals & alerts', 'Versioned release'],
    dur: 'Wk 2–10'
  },
  {
    n: '04',
    name: 'Operate',
    short: 'Run',
    desc: 'We sit on‑call alongside your team. We run the surface until your operators own it confidently — typically 6 weeks beyond install.',
    meta: ['Shared on‑call', 'Weekly review', 'Handover at SLO'],
    dur: 'Wk 10–18'
  }
];

function HowDiagram() {
  const [active, setActive] = React.useState(0);
  const [hover, setHover] = React.useState(null);
  React.useEffect(() => {
    const id = setInterval(() => setActive((a) => (a + 1) % STEPS.length), 3200);
    return () => clearInterval(id);
  }, []);
  const cur = hover !== null ? hover : active;

  return (
    <div className="how">
      <div className="how-track">
        {STEPS.map((s, i) => (
          <div
            key={s.n}
            className={`how-step ${i === cur ? 'active' : ''}`}
            onMouseEnter={() => setHover(i)}
            onMouseLeave={() => setHover(null)}
          >
            <div className="how-meta mono">
              <span>{s.n}</span>
              <span>{s.dur}</span>
            </div>
            <div className="how-name">{s.name}</div>
            <div className="how-short mono">{s.short.toUpperCase()}</div>
            <div className="how-bar"><span className="how-bar-fill" style={{ width: i === cur ? '100%' : i < cur ? '100%' : '0%' }} /></div>
          </div>
        ))}
      </div>

      <div className="how-detail">
        <div className="how-detail-left">
          <div className="mono" style={{ fontSize: 11, color: 'var(--mute)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 10 }}>
            {STEPS[cur].n} / {STEPS[cur].name}
          </div>
          <h3 style={{ fontSize: 28, lineHeight: 1.1, maxWidth: '24ch' }}>
            {STEPS[cur].desc}
          </h3>
        </div>
        <div className="how-detail-right">
          <div className="mono" style={{ fontSize: 11, color: 'var(--mute)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 10 }}>Deliverables</div>
          <ul className="how-deliv">
            {STEPS[cur].meta.map((m) => (
              <li key={m}><span className="mono ix">—</span>{m}</li>
            ))}
          </ul>
          <div className="how-foot mono">
            <span>Engagement: 12–18 weeks</span>
            <span>Pricing: fixed + retainer</span>
          </div>
        </div>
      </div>

      <style>{`
        .how { border: 1px solid var(--line); border-radius: var(--radius-card); background: var(--bg-card); overflow: hidden; }
        .how-track { display: grid; grid-template-columns: repeat(4, 1fr); border-bottom: 1px solid var(--line); }
        .how-step { padding: 22px 22px 18px; border-right: 1px solid var(--line); cursor: default; transition: background 200ms; position: relative; }
        .how-step:last-child { border-right: 0; }
        .how-step:hover, .how-step.active { background: #fcfcf9; }
        .how-step.active .how-name { color: var(--ink); }
        .how-meta { display: flex; justify-content: space-between; font-size: 11px; color: var(--mute-1); letter-spacing: 0.06em; white-space: nowrap; gap: 8px; }
        .how-name { font-family: var(--font-display); font-size: 30px; font-weight: 500; letter-spacing: -0.028em; margin-top: 12px; line-height: 1; }
        .how-short { font-size: 10.5px; color: var(--mute); letter-spacing: 0.1em; margin-top: 4px; }
        .how-bar { margin-top: 16px; height: 2px; background: var(--line); border-radius: 2px; overflow: hidden; }
        .how-bar-fill { display: block; height: 100%; background: var(--ink); transition: width 600ms cubic-bezier(0.2,0.8,0.2,1); }
        .how-step.active .how-bar-fill { background: var(--accent); box-shadow: 0 0 0 0 transparent; }
        .how-detail { display: grid; grid-template-columns: 1.4fr 1fr; gap: 32px; padding: 28px 22px; background: var(--bg); }
        .how-detail-left h3 { font-weight: 400; color: var(--ink-1); letter-spacing: -0.018em; }
        .how-deliv { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; font-size: 14.5px; }
        .how-deliv li { display: flex; gap: 12px; align-items: baseline; }
        .how-deliv .ix { color: var(--mute-1); font-size: 11px; }
        .how-foot { display: flex; gap: 18px; font-size: 11px; color: var(--mute); letter-spacing: 0.04em; text-transform: uppercase; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); }
        @media (max-width: 820px) {
          .how-track { grid-template-columns: 1fr 1fr; }
          .how-step { border-right: 0; border-bottom: 1px solid var(--line); }
          .how-step:nth-child(2n) { border-right: 0; }
          .how-step:nth-child(odd) { border-right: 1px solid var(--line); }
          .how-detail { grid-template-columns: 1fr; }
        }
      `}</style>
    </div>
  );
}

// ============================ Workflow Diagram ============================

function Pulse({ x1, y1, x2, y2, delay = 0, dur = 2.4 }) {
  // Animated dot along a line
  const len = Math.hypot(x2 - x1, y2 - y1);
  const dashArray = 2;
  return (
    <>
      <line x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--line-strong)" strokeWidth="1" />
      <circle r="2.6" fill="var(--accent)" stroke="var(--ink)" strokeWidth="0.6">
        <animateMotion dur={`${dur}s`} repeatCount="indefinite" begin={`${delay}s`} path={`M${x1},${y1} L${x2},${y2}`} />
        <animate attributeName="opacity" values="0;1;1;0" keyTimes="0;0.15;0.85;1" dur={`${dur}s`} repeatCount="indefinite" begin={`${delay}s`} />
      </circle>
    </>
  );
}

function WfNode({ x, y, w, h, label, sub, kind = 'flow', mono = false }) {
  const kindColors = {
    flow: { bg: '#ffffff', border: 'var(--line-strong)' },
    agent: { bg: 'var(--ink)', border: 'var(--ink)', text: '#fafaf7' },
    accent: { bg: 'var(--accent)', border: 'var(--ink)' },
    ghost: { bg: 'transparent', border: 'var(--line)' }
  };
  const c = kindColors[kind];
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx="3" fill={c.bg} stroke={c.border} strokeWidth="1" />
      <text x={x + 12} y={y + 20} fontFamily="IBM Plex Mono" fontSize="9" letterSpacing="0.06em" fill={c.text ? 'rgba(255,255,255,0.55)' : 'var(--mute)'}>{sub}</text>
      <text x={x + 12} y={y + h - 12} fontFamily={mono ? 'IBM Plex Mono' : 'Inter Tight'} fontSize={mono ? '12' : '14'} fontWeight="500" letterSpacing="-0.01em" fill={c.text || 'var(--ink)'}>{label}</text>
    </g>
  );
}

function WorkflowDiagram() {
  // Layout
  const W = 1180, H = 520;
  return (
    <div className="workflow">
      <div className="wf-head">
        <div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--mute)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Representative · revenue + support flow · v18</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 4 }}>
            inbound → enrich → score → branch → resolve → log
          </div>
        </div>
        <div className="wf-legend mono">
          <span><span className="sw flow"></span>Deterministic</span>
          <span><span className="sw agent"></span>Agent</span>
          <span><span className="sw accent"></span>Branch / decision</span>
          <span><span className="sw ghost"></span>Side effect</span>
        </div>
      </div>

      <div className="wf-canvas">
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: 'auto' }}>
          {/* Grid */}
          <defs>
            <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
              <path d="M 40 0 L 0 0 0 40" fill="none" stroke="rgba(10,10,10,0.04)" strokeWidth="0.6" />
            </pattern>
          </defs>
          <rect width={W} height={H} fill="url(#grid)" />

          {/* Lane labels */}
          <text x="20" y="36" fontFamily="IBM Plex Mono" fontSize="10" letterSpacing="0.08em" fill="var(--mute-1)">LANE / INGEST</text>
          <text x="20" y="180" fontFamily="IBM Plex Mono" fontSize="10" letterSpacing="0.08em" fill="var(--mute-1)">LANE / REASONING</text>
          <text x="20" y="340" fontFamily="IBM Plex Mono" fontSize="10" letterSpacing="0.08em" fill="var(--mute-1)">LANE / ACTION</text>
          <text x="20" y="488" fontFamily="IBM Plex Mono" fontSize="10" letterSpacing="0.08em" fill="var(--mute-1)">LANE / LEDGER</text>

          {/* Horizontal lane separators */}
          <line x1="20" y1="56" x2={W - 20} y2="56" stroke="var(--line)" strokeWidth="1" strokeDasharray="2 4" />
          <line x1="20" y1="200" x2={W - 20} y2="200" stroke="var(--line)" strokeWidth="1" strokeDasharray="2 4" />
          <line x1="20" y1="360" x2={W - 20} y2="360" stroke="var(--line)" strokeWidth="1" strokeDasharray="2 4" />

          {/* INGEST nodes */}
          <WfNode x={140} y={80} w={160} h={70} label="Web event" sub="SIGNAL / WEB" kind="flow" />
          <WfNode x={140} y={20} w={160} h={50} label="Form submit" sub="SIGNAL / INBOUND" kind="ghost" />
          <WfNode x={320} y={80} w={170} h={70} label="Identity stitch" sub="STEP / IDENTITY" kind="flow" />
          <WfNode x={510} y={80} w={170} h={70} label="Enrich (Apollo + CRM)" sub="STEP / ENRICH" kind="flow" />

          {/* REASONING (agent score) */}
          <WfNode x={700} y={220} w={180} h={80} label="Score & triage" sub="AGENT / score.v18" kind="agent" />
          <WfNode x={510} y={220} w={170} h={80} label="Retrieve context" sub="RAG / customer_kb" kind="flow" />

          {/* BRANCH */}
          <WfNode x={900} y={220} w={150} h={80} label="ICP ≥ 80?" sub="BRANCH / score" kind="accent" />

          {/* ACTION */}
          <WfNode x={700} y={380} w={180} h={80} label="Route to AE queue" sub="ACTION / routing.rr" kind="flow" />
          <WfNode x={900} y={380} w={150} h={80} label="Nurture sequence" sub="ACTION / lifecycle" kind="flow" />
          <WfNode x={510} y={380} w={170} h={80} label="Draft response" sub="AGENT / draft.v6" kind="agent" />
          <WfNode x={320} y={380} w={170} h={80} label="Operator review" sub="HUMAN / queue" kind="flow" mono />

          {/* LEDGER */}
          <WfNode x={140} y={420} w={920} h={48} label="warehouse.events · evals.runs · audit.log · billing.recon" sub="WRITE / ledger" kind="ghost" mono />

          {/* Edges with pulses */}
          {/* form -> identity */}
          <Pulse x1={300} y1={45} x2={320} y2={100} delay={0} />
          {/* web -> identity */}
          <Pulse x1={300} y1={115} x2={320} y2={115} delay={0.4} />
          {/* identity -> enrich */}
          <Pulse x1={490} y1={115} x2={510} y2={115} delay={0.8} />
          {/* enrich -> retrieve */}
          <Pulse x1={595} y1={150} x2={595} y2={220} delay={1.2} />
          {/* retrieve -> score */}
          <Pulse x1={680} y1={260} x2={700} y2={260} delay={1.6} />
          {/* score -> branch */}
          <Pulse x1={880} y1={260} x2={900} y2={260} delay={2.0} dur={2.0} />
          {/* branch yes -> route */}
          <Pulse x1={975} y1={300} x2={790} y2={380} delay={2.4} dur={2.2} />
          {/* branch no -> nurture */}
          <Pulse x1={975} y1={300} x2={975} y2={380} delay={2.4} dur={2.2} />
          {/* route -> draft (support side parallel) */}
          <Pulse x1={700} y1={420} x2={680} y2={420} delay={0.6} dur={2.4} />
          {/* draft -> operator review */}
          <Pulse x1={510} y1={420} x2={490} y2={420} delay={1.0} dur={2.4} />
          {/* operator -> ledger */}
          <Pulse x1={405} y1={460} x2={405} y2={420} delay={1.4} />
          {/* ledger writes from various nodes */}
          <line x1={595} y1={460} x2={595} y2={420} stroke="var(--line)" strokeWidth="1" strokeDasharray="2 3" />
          <line x1={790} y1={460} x2={790} y2={420} stroke="var(--line)" strokeWidth="1" strokeDasharray="2 3" />
          <line x1={975} y1={460} x2={975} y2={420} stroke="var(--line)" strokeWidth="1" strokeDasharray="2 3" />

          {/* Annotations */}
          <g fontFamily="IBM Plex Mono" fontSize="9.5" fill="var(--mute)" letterSpacing="0.04em">
            <text x="385" y="180">~ 240ms p50 · cache 92%</text>
            <text x="720" y="200">eval pass 247/250 · cost $0.018</text>
            <text x="920" y="200">threshold tunable</text>
            <text x="540" y="360">human review on tonal &lt;0.4</text>
            <text x="140" y="408">All actions append to ledger · audit‑complete</text>
          </g>

          {/* Branch arrow labels */}
          <text x="900" y="345" fontFamily="IBM Plex Mono" fontSize="10" fill="var(--ink)" fontWeight="500">YES → ROUTE</text>
          <text x="985" y="345" fontFamily="IBM Plex Mono" fontSize="10" fill="var(--mute)">NO → NURTURE</text>
        </svg>
      </div>

      <div className="wf-foot">
        <div className="mono"><strong>SLO</strong> p95 &lt; 1.2s · cost ceiling $/run · eval gate ≥ 95%</div>
        <div className="mono"><strong>OWNERS</strong> ops.routing · ops.lifecycle · cs.review</div>
        <div className="mono"><strong>OBSERVABILITY</strong> langfuse · braintrust · grafana</div>
      </div>

      <style>{`
        .workflow { border: 1px solid var(--line); border-radius: var(--radius-card); background: var(--bg-card); overflow: hidden; }
        .wf-head { display: flex; justify-content: space-between; align-items: flex-end; padding: 22px 22px 16px; border-bottom: 1px solid var(--line); flex-wrap: wrap; gap: 16px; }
        .wf-legend { display: flex; gap: 18px; font-size: 11px; color: var(--mute); letter-spacing: 0.04em; }
        .wf-legend .sw { display: inline-block; width: 12px; height: 10px; border: 1px solid var(--line-strong); margin-right: 6px; vertical-align: -1px; }
        .wf-legend .sw.flow { background: #fff; }
        .wf-legend .sw.agent { background: var(--ink); border-color: var(--ink); }
        .wf-legend .sw.accent { background: var(--accent); border-color: var(--ink); }
        .wf-legend .sw.ghost { background: transparent; }
        .wf-canvas { padding: 18px; background: #fcfcf9; }
        .wf-foot { display: grid; grid-template-columns: 1.2fr 1fr 1fr; gap: 18px; padding: 16px 22px; border-top: 1px solid var(--line); font-size: 11px; color: var(--mute); letter-spacing: 0.04em; }
        .wf-foot strong { color: var(--ink); margin-right: 8px; }
        @media (max-width: 820px) { .wf-foot { grid-template-columns: 1fr; gap: 8px; } }
      `}</style>
    </div>
  );
}

const howRoot = document.getElementById('how-diagram');
if (howRoot) ReactDOM.createRoot(howRoot).render(<HowDiagram />);

const wfRoot = document.getElementById('workflow-diagram');
if (wfRoot) ReactDOM.createRoot(wfRoot).render(<WorkflowDiagram />);
