/* global React, window */
// Dynamic dashboard components for the Dolado homepage.
// Each one is a self-contained "fragment" — Palantir-leaning, hairline-heavy,
// with monospace data, animated entrance, and a live status header.

const { useState, useEffect, useRef, useMemo } = React;

/* ============================================================
   Shared — live status pulse dot
   ============================================================ */
function LiveDot() {
  return <span className="dash-livedot" aria-hidden="true"></span>;
}

/* ============================================================
   1) OpsBoard — multi-channel marketplace operations console
   ============================================================ */
function OpsBoard({ data }) {
  const [tick, setTick] = useState(0);
  const [visible, setVisible] = useState(false);
  const ref = useRef(null);

  // Reveal-on-view
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.2 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Heartbeat — adds tiny jitter to GMV numbers so they feel live.
  useEffect(() => {
    if (!visible) return;
    const id = setInterval(() => setTick((x) => x + 1), 1800);
    return () => clearInterval(id);
  }, [visible]);

  const jitter = (base) => {
    // ±0.4% jitter — deterministic per tick so it doesn't go crazy
    const seed = (tick * 17 + base * 100) % 7;
    return base * (1 + (seed - 3) * 0.0012);
  };

  return (
    <div className="dash dash-ops" ref={ref}>
      <div className="dash-head">
        <span><LiveDot />{data.label}</span>
        <span className="dash-head-meta">
          <span className="dash-sync">{data.sync.replace(/\d+/, String((tick % 9) + 1))}</span>
        </span>
      </div>

      <div className="ops-table">
        <div className="ops-row ops-row-head">
          {data.cols.map((c, i) => <div key={i} className={`ops-cell ops-cell-h ops-cell-${i}`}>{c}</div>)}
        </div>

        {data.rows.map((r, i) => {
          const gmvNow = jitter(r.gmv);
          return (
            <div className={`ops-row ${visible ? "in" : ""}`} key={i} style={{ animationDelay: `${i * 80}ms` }}>
              <div className="ops-cell ops-cell-0">
                <span className={`ops-mark ops-mark-${r.code.toLowerCase()}`}>{r.code}</span>
                <span className="ops-channel">{r.channel}</span>
              </div>
              <div className="ops-cell ops-cell-1">
                <span className="ops-gmv">
                  <span className="ops-gmv-cur">R$</span>
                  {gmvNow.toFixed(2)}
                  <span className="ops-gmv-unit">MM</span>
                </span>
                <svg className="ops-spark" viewBox="0 0 80 16" preserveAspectRatio="none">
                  {(() => {
                    const pts = r.trend;
                    const max = Math.max(...pts);
                    const path = pts.map((p, j) =>
                      `${j === 0 ? "M" : "L"} ${(j / (pts.length - 1)) * 80} ${16 - (p / max) * 14 - 1}`
                    ).join(" ");
                    return <path d={path} fill="none" stroke="var(--accent)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />;
                  })()}
                </svg>
              </div>
              <div className="ops-cell ops-cell-2">
                <span className="ops-sla-val">{r.sla.toFixed(1)}%</span>
                <span className="ops-sla-bar">
                  <span className="ops-sla-bar-fill" style={{ width: visible ? `${r.sla}%` : "0%" }}></span>
                  <span className="ops-sla-bar-target" style={{ left: `${r.slaTarget}%` }}></span>
                </span>
              </div>
              <div className="ops-cell ops-cell-3">
                <span className={`ops-rep ops-rep-${r.repState}`}>{r.rep}</span>
              </div>
              <div className="ops-cell ops-cell-4 ops-listings">
                {r.listings.toLocaleString("en-US").replace(/,/g, ".")}
              </div>
              <div className="ops-cell ops-cell-5">
                <span className={`ops-status ops-status-${r.repState}`}>
                  <span className="ops-status-dot"></span>{r.status}
                </span>
              </div>
            </div>
          );
        })}
      </div>

      <div className="dash-foot">
        <span>{data.footer[0]}</span>
        <span>{data.footer[1]}</span>
      </div>
    </div>
  );
}

/* ============================================================
   2) PromptMatrix — coverage heatmap
   ============================================================ */
function PromptMatrix({ data }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.2 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Derive per-brand aggregates from the prompts grid so we don't have
  // hand-maintained numbers drifting out of sync with the data.
  const aggregates = useMemo(() => {
    return data.brands.map((b, ci) => {
      const ranks = data.prompts.map((p) => p.ranks[ci]).filter((r) => r > 0);
      const coverage = Math.round((ranks.length / data.prompts.length) * 100);
      const avg = ranks.length
        ? (ranks.reduce((s, r) => s + r, 0) / ranks.length)
        : null;
      return { coverage, avg, present: ranks.length };
    });
  }, [data]);

  // Find the column index where the "operated" group ends so we can
  // anchor the bracket label correctly even if brand ordering changes.
  const operatedCount = data.brands.filter((b) => b.operated).length;

  return (
    <div className="dash dash-matrix" ref={ref}>
      <div className="dash-head">
        <span><LiveDot />{data.label}</span>
        <span className="dash-head-meta">{data.version}</span>
      </div>

      {/* Lead claim + hero stats */}
      <div className="matrix-claim">
        <p className="matrix-claim-text">
          <span className="matrix-claim-lead">{data.claim.lead}</span>{" "}
          <span className="matrix-claim-punch">{data.claim.punch}</span>
        </p>
        <div className="matrix-hero-stats">
          {data.heroStats.map((s, i) => (
            <div key={i} className={`matrix-hero-stat matrix-hero-stat-${s.tone}`}>
              <div className="matrix-hero-stat-value">
                {s.prefix && <span className="matrix-hero-stat-prefix">{s.prefix}</span>}
                {s.value}
                {s.total && <span className="matrix-hero-stat-total">{s.total}</span>}
              </div>
              <div className="matrix-hero-stat-label">{s.label}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Group bracket above column headers */}
      <div className="matrix-groups" aria-hidden="true">
        <div className="matrix-groups-spacer"></div>
        <div className="matrix-group matrix-group-operated" style={{ gridColumn: `span ${operatedCount}` }}>
          <span className="matrix-group-label">{data.operatedGroupLabel}</span>
        </div>
        <div className="matrix-group matrix-group-competitor" style={{ gridColumn: `span ${data.brands.length - operatedCount}` }}>
          <span className="matrix-group-label">{data.competitorGroupLabel}</span>
        </div>
      </div>

      <div className="matrix-grid" data-visible={visible ? "1" : "0"}>
        <div className="matrix-corner"></div>
        {data.brands.map((b, i) => (
          <div key={i} className={`matrix-col-head ${b.operated ? "operated" : ""}`}>
            <span className="matrix-col-name">{b.short || b.name}</span>
          </div>
        ))}

        {data.prompts.map((p, ri) => (
          <React.Fragment key={ri}>
            <div className="matrix-row-head">
              <span className="matrix-row-n">{String(ri + 1).padStart(2, "0")}</span>
              <span className="matrix-row-cat">{p.cat}</span>
            </div>
            {p.ranks.map((rank, ci) => {
              const isOp = data.brands[ci].operated;
              const isWin = rank === 1;
              return (
                <div
                  key={ci}
                  className={[
                    "matrix-cell",
                    `matrix-rank-${rank}`,
                    isOp ? "operated-col" : "",
                    isOp && isWin ? "op-win" : "",
                  ].filter(Boolean).join(" ")}
                  style={{ transitionDelay: visible ? `${(ri * 60) + (ci * 30)}ms` : "0ms" }}
                  title={rank > 0 ? `#${rank}` : "absent"}
                >
                  {rank > 0 ? (
                    <span className="matrix-cell-rank">{rank}</span>
                  ) : (
                    <span className="matrix-cell-absent" aria-hidden="true">—</span>
                  )}
                </div>
              );
            })}
          </React.Fragment>
        ))}

        {/* Aggregate rows */}
        <div className="matrix-summary-head">{data.coverageLabel}</div>
        {aggregates.map((a, ci) => {
          const isOp = data.brands[ci].operated;
          return (
            <div key={ci} className={`matrix-summary-cell ${isOp ? "operated-col" : ""}`}>
              <span className="matrix-summary-bar">
                <span
                  className="matrix-summary-bar-fill"
                  style={{ width: visible ? `${a.coverage}%` : "0%" }}
                ></span>
              </span>
              <span className="matrix-summary-pct">{a.coverage}%</span>
            </div>
          );
        })}

        <div className="matrix-summary-head">{data.rankLabel}</div>
        {aggregates.map((a, ci) => {
          const isOp = data.brands[ci].operated;
          return (
            <div key={ci} className={`matrix-summary-cell matrix-summary-rank ${isOp ? "operated-col" : ""}`}>
              <span className="matrix-summary-rank-val">
                {a.avg != null ? `#${a.avg.toFixed(1).replace(".", a.avg.toFixed(1).includes(".") ? "." : "")}` : "—"}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ============================================================
   3) GmvTimeline — area chart with annotations
   ============================================================ */
function GmvTimeline({ data }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Chart dims
  const W = 1180;
  const H = 360;
  const padL = 56;
  const padR = 24;
  const padT = 24;
  const padB = 48;

  const xs = data.points.map((_, i) => padL + (i / (data.points.length - 1)) * (W - padL - padR));
  const max = Math.max(...data.points.map((p) => p.gmv));
  // Round up max to a clean number
  const niceMax = Math.ceil(max / 100) * 100;
  const ys = data.points.map((p) => padT + (1 - p.gmv / niceMax) * (H - padT - padB));

  const linePath = data.points.map((p, i) => `${i === 0 ? "M" : "L"} ${xs[i]} ${ys[i]}`).join(" ");
  const areaPath = `${linePath} L ${xs[xs.length - 1]} ${H - padB} L ${xs[0]} ${H - padB} Z`;

  // Y-axis ticks
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map((t) => ({
    y: padT + t * (H - padT - padB),
    label: Math.round(niceMax * (1 - t)),
  }));

  const total = data.points[data.points.length - 1].gmv;

  return (
    <div className="dash dash-timeline" ref={ref}>
      <div className="dash-head">
        <span><LiveDot />{data.label}</span>
        <span className="dash-head-meta">{data.sub}</span>
      </div>

      <div className="timeline-stage">
        <div className="timeline-total">
          <div className="timeline-total-label">{data.legendCurrent}</div>
          <div className="timeline-total-value">
            <span className="timeline-total-cur">R$</span>
            {total.toLocaleString("en-US").replace(/,/g, ".")}
            <span className="timeline-total-unit">MM</span>
          </div>
        </div>

        <svg viewBox={`0 0 ${W} ${H}`} className="timeline-svg" preserveAspectRatio="xMidYMid meet">
          <defs>
            <linearGradient id="tl-area" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.28"/>
              <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
            </linearGradient>
            <clipPath id="tl-clip">
              <rect x={padL} y={0} width={visible ? W - padL - padR : 0} height={H}>
                {visible && <animate attributeName="width" from="0" to={W - padL - padR} dur="1600ms" begin="0s" fill="freeze" calcMode="spline" keySplines="0.22 1 0.36 1" />}
              </rect>
            </clipPath>
          </defs>

          {/* Y-grid */}
          {yTicks.map((t, i) => (
            <g key={i}>
              <line x1={padL} y1={t.y} x2={W - padR} y2={t.y} stroke="var(--hair)" strokeWidth="1" />
              <text x={padL - 12} y={t.y + 4} fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)" textAnchor="end" letterSpacing="0.06em">{t.label}</text>
            </g>
          ))}

          {/* X-axis labels */}
          {data.points.map((p, i) => (
            <text key={i} x={xs[i]} y={H - padB + 24} fontSize="11" fontFamily="var(--font-mono)" fill="var(--fg-3)" textAnchor="middle" letterSpacing="0.04em">
              {p.year}
            </text>
          ))}

          {/* Area + line, clipped for draw-in */}
          <g clipPath="url(#tl-clip)">
            <path d={areaPath} fill="url(#tl-area)" />
            <path d={linePath} fill="none" stroke="var(--accent)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
          </g>

          {/* Annotation dots + notes */}
          {data.points.map((p, i) => p.note ? (
            <g key={i} className="timeline-anno" style={{ opacity: visible ? 1 : 0, transitionDelay: `${800 + i * 120}ms` }}>
              <circle cx={xs[i]} cy={ys[i]} r="5" fill="var(--bg)" stroke="var(--accent)" strokeWidth="2" />
              <line x1={xs[i]} y1={ys[i] - 8} x2={xs[i]} y2={ys[i] - 24} stroke="var(--hair-strong)" strokeWidth="1" strokeDasharray="2 2" />
              <text x={xs[i]} y={ys[i] - 32} fontSize="11" fontFamily="var(--font-mono)" fill="var(--fg-2)" textAnchor="middle" letterSpacing="0.04em">
                {p.note}
              </text>
            </g>
          ) : (
            <circle key={i} cx={xs[i]} cy={ys[i]} r="3" fill="var(--bg)" stroke="var(--accent)" strokeWidth="1.5" style={{ opacity: visible ? 1 : 0, transition: `opacity 400ms var(--ease-out) ${600 + i * 120}ms` }} />
          ))}

          {/* Y-axis title */}
          <text x={padL - 36} y={padT + 8} fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)" letterSpacing="0.1em" textAnchor="start" transform={`rotate(-90 ${padL - 36} ${padT + 8})`}>R$ MM</text>
        </svg>
      </div>

      <div className="dash-foot">
        <span>{data.legendPrev}</span>
        <span>Source: Dolado operating layer · audited Dec 2025</span>
      </div>
    </div>
  );
}

/* ============================================================
   4) CohortTracker — embedded program dashboard
   ============================================================ */
function CohortTracker({ data }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.25 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const total = 12;
  const { confirmed, inReview, open } = data.slotsBreakdown;
  const stages = data.pipelineStages;
  const maxStage = Math.max(...stages.map((s) => s.value));

  return (
    <div className="dash dash-cohort" ref={ref}>
      <div className="dash-head">
        <span><LiveDot />{data.title}</span>
        <span className="dash-head-meta">{data.sync}</span>
      </div>

      <div className="cohort-kpis">
        {data.kpis.map((k, i) => (
          <div key={i} className="cohort-kpi">
            <div className="cohort-kpi-label">{k.label}</div>
            <div className="cohort-kpi-value">
              {k.value}<span className="cohort-kpi-suffix">{k.suffix}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="cohort-slots">
        <div className="cohort-slots-label">{data.slotsLabel}</div>
        <div className="cohort-slots-grid">
          {Array.from({ length: total }).map((_, i) => {
            let state = "open";
            if (i < confirmed) state = "confirmed";
            else if (i < confirmed + inReview) state = "review";
            return (
              <div
                key={i}
                className={`cohort-slot cohort-slot-${state} ${visible ? "in" : ""}`}
                style={{ transitionDelay: `${i * 60}ms` }}
              >
                <span className="cohort-slot-n">{String(i + 1).padStart(2, "0")}</span>
              </div>
            );
          })}
        </div>
        <div className="cohort-slots-legend">
          <span className="cohort-slot-leg cohort-slot-leg-confirmed">{data.confirmedLabel} · {confirmed}</span>
          <span className="cohort-slot-leg cohort-slot-leg-review">{data.reviewLabel} · {inReview}</span>
          <span className="cohort-slot-leg cohort-slot-leg-open">{data.openLabel} · {open}</span>
        </div>
      </div>

      <div className="cohort-pipeline">
        <div className="cohort-pipeline-label">{data.pipelineLabel}</div>
        {stages.map((s, i) => (
          <div key={i} className="cohort-pipe-row">
            <span className="cohort-pipe-name">{s.label}</span>
            <span className="cohort-pipe-bar">
              <span
                className={`cohort-pipe-fill ${i === stages.length - 1 ? "final" : ""}`}
                style={{ width: visible ? `${(s.value / maxStage) * 100}%` : "0%", transitionDelay: `${i * 100}ms` }}
              ></span>
            </span>
            <span className="cohort-pipe-val">{s.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   1b) OpsAnatomy — architecture-of-an-operation diagram
   Editorial composition. Brand, Marketplaces and Consumers are
   typographic annotations (no boxes). The Dolado layer is the
   single bordered element — the visual anchor.
   ============================================================ */
function MarketplaceMark({ code }) {
  if (code === "ML") {
    return (
      <img
        src="assets/marketplaces/mercado-livre.png"
        alt="Mercado Livre"
        className="mp-mark-img"
      />
    );
  }
  if (code === "SHP") {
    return (
      <img
        src="assets/marketplaces/shopee.png"
        alt="Shopee"
        className="mp-mark-img"
      />
    );
  }
  if (code === "AMZ") {
    // Amazon — dark bg with lowercase wordmark and orange smile.
    return (
      <svg viewBox="0 0 40 28" xmlns="http://www.w3.org/2000/svg" className="mp-mark-svg">
        <rect width="40" height="28" rx="3" fill="#131A22"/>
        <text x="20" y="16" textAnchor="middle" fill="#ffffff" fontFamily="Mulish, system-ui, sans-serif" fontWeight="900" fontSize="10" letterSpacing="-0.5">amazon</text>
        <path d="M8 21 C 14 24, 26 24, 32 21" stroke="#FF9900" strokeWidth="2" fill="none" strokeLinecap="round"/>
        <path d="M30 19.2 L 33 21 L 30 22.8 Z" fill="#FF9900"/>
      </svg>
    );
  }
  if (code === "SHP") {
    /* unreachable — handled above */
    return null;
  }
  if (code === "TT") {
    // TikTok Shop — black bg with offset cyan/magenta music-note glyph.
    return (
      <svg viewBox="0 0 40 28" xmlns="http://www.w3.org/2000/svg" className="mp-mark-svg">
        <rect width="40" height="28" rx="3" fill="#000000"/>
        <g transform="translate(20 14)">
          <g transform="translate(1.4 1)">
            <path d="M 3.2 -7 a 3.8 3.8 0 0 0 3.8 3.8 V -1 a 6 6 0 0 1 -3.8 -1.3 V 4 a 4.6 4.6 0 1 1 -4.6 -4.6 v 2.4 a 2.2 2.2 0 1 0 2.2 2.2 V -7 Z" fill="#FE2C55"/>
          </g>
          <g transform="translate(-1.4 -1)">
            <path d="M 3.2 -7 a 3.8 3.8 0 0 0 3.8 3.8 V -1 a 6 6 0 0 1 -3.8 -1.3 V 4 a 4.6 4.6 0 1 1 -4.6 -4.6 v 2.4 a 2.2 2.2 0 1 0 2.2 2.2 V -7 Z" fill="#25F4EE"/>
          </g>
          <path d="M 3.2 -7 a 3.8 3.8 0 0 0 3.8 3.8 V -1 a 6 6 0 0 1 -3.8 -1.3 V 4 a 4.6 4.6 0 1 1 -4.6 -4.6 v 2.4 a 2.2 2.2 0 1 0 2.2 2.2 V -7 Z" fill="#ffffff"/>
        </g>
      </svg>
    );
  }
  return null;
}

function FlowIcon({ name }) {
  const stroke = { stroke: "currentColor", strokeWidth: 1.75, strokeLinecap: "round", strokeLinejoin: "round", fill: "none" };
  if (name === "brand") {
    return (
      <svg viewBox="0 0 32 32" width="32" height="32" {...stroke}>
        <path d="M6 10 L16 5 L26 10 V22 L16 27 L6 22 Z" />
        <path d="M6 10 L16 15 L26 10" />
        <path d="M16 15 V27" />
      </svg>
    );
  }
  if (name === "dolado") {
    return (
      <svg viewBox="0 0 32 32" width="32" height="32" {...stroke}>
        <circle cx="16" cy="16" r="4" fill="currentColor" stroke="none" />
        <path d="M16 3 V10" />
        <path d="M16 22 V29" />
        <path d="M3 16 H10" />
        <path d="M22 16 H29" />
        <circle cx="16" cy="3" r="1.5" fill="currentColor" stroke="none" />
        <circle cx="16" cy="29" r="1.5" fill="currentColor" stroke="none" />
        <circle cx="3" cy="16" r="1.5" fill="currentColor" stroke="none" />
        <circle cx="29" cy="16" r="1.5" fill="currentColor" stroke="none" />
      </svg>
    );
  }
  if (name === "marketplaces") {
    return (
      <svg viewBox="0 0 32 32" width="32" height="32" {...stroke}>
        <rect x="4" y="4" width="10" height="10" rx="1" />
        <rect x="18" y="4" width="10" height="10" rx="1" />
        <rect x="4" y="18" width="10" height="10" rx="1" />
        <rect x="18" y="18" width="10" height="10" rx="1" />
      </svg>
    );
  }
  if (name === "consumers") {
    return (
      <svg viewBox="0 0 32 32" width="32" height="32" {...stroke}>
        <path d="M5 8 H24 a3 3 0 0 1 3 3 V20 a3 3 0 0 1 -3 3 H14 L8 28 V23 H5 a3 3 0 0 1 -3 -3 V11 a3 3 0 0 1 3 -3 Z" />
        <path d="M20 12 L21 14 L23 15 L21 16 L20 18 L19 16 L17 15 L19 14 Z" fill="currentColor" stroke="none" />
      </svg>
    );
  }
  return null;
}

function FlowArrow({ back }) {
  if (back) {
    return (
      <svg viewBox="0 0 36 12" className="flow-arrow-svg" aria-hidden="true">
        <path d="M6 6 H 34" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeDasharray="3 3" />
        <path d="M10 3 L6 6 L10 9" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 36 12" className="flow-arrow-svg" aria-hidden="true">
      <path d="M2 6 H 30" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
      <path d="M26 3 L30 6 L26 9" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function OpsAnatomy({ data }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.18 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const brand = data.steps.find((s) => s.id === "brand");
  const dolado = data.steps.find((s) => s.id === "dolado");
  const mkts = data.steps.find((s) => s.id === "marketplaces");
  const consumers = data.steps.find((s) => s.id === "consumers");

  const renderEndpoint = (step, idx) => (
    <div
      className="anatomy-station"
      style={{ "--anatomy-delay": `${idx * 120}ms` }}
    >
      <div className="anatomy-station-head">
        <span className="anatomy-station-icon"><FlowIcon name={step.icon} /></span>
        <span className="anatomy-station-tag">{step.tag}</span>
      </div>
      <div className="anatomy-station-label">{step.label}</div>
      {step.sublabel && <div className="anatomy-station-sublabel">{step.sublabel}</div>}
      {step.mkts ? (
        <div className="anatomy-station-mkts">
          {step.mkts.map((m, j) => (
            <span key={j} className="anatomy-station-mkt" title={m.name}>
              <MarketplaceMark code={m.code} />
            </span>
          ))}
        </div>
      ) : (
        <div className="anatomy-station-items">
          {step.items.map((it, j) => <span key={j}>{it}</span>)}
        </div>
      )}
    </div>
  );

  return (
    <div className="dash dash-anatomy" ref={ref} data-visible={visible ? "1" : "0"}>
      <div className="dash-head">
        <span><LiveDot />{data.label}</span>
        <span className="dash-head-meta">{data.meta}</span>
      </div>

      <div className="anatomy-board">
        {/* Left endpoint — BRAND */}
        {renderEndpoint(brand, 0)}

        {/* Connector — bi-directional */}
        <div className="anatomy-link anatomy-link-bi" style={{ "--anatomy-delay": "80ms" }}>
          <FlowArrow />
          {data.flows[0].up && <FlowArrow back />}
          <div className="anatomy-link-labels">
            <span className="anatomy-link-label">{data.flows[0].down}</span>
            {data.flows[0].up && (
              <span className="anatomy-link-label anatomy-link-label-mute">{data.flows[0].up}</span>
            )}
          </div>
        </div>

        {/* HERO — Dolado */}
        <div className="anatomy-hero" style={{ "--anatomy-delay": "160ms" }}>
          <div className="anatomy-hero-rail" aria-hidden="true"></div>
          <div className="anatomy-hero-head">
            <div className="anatomy-hero-head-left">
              <span className="anatomy-hero-icon"><FlowIcon name="dolado" /></span>
              <span className="anatomy-hero-tag">{dolado.tag}</span>
            </div>
            <span className="anatomy-hero-note">{dolado.note}</span>
          </div>
          <div className="anatomy-hero-titles">
            <div className="anatomy-hero-name">{dolado.label}</div>
            <div className="anatomy-hero-sub">{dolado.sublabel}</div>
          </div>
          <ol className="anatomy-hero-disciplines">
            {dolado.items.map((it, j) => (
              <li
                key={j}
                className="anatomy-hero-disc"
                style={{ "--disc-delay": `${280 + j * 90}ms` }}
              >
                <span className="anatomy-hero-disc-n">{String(j + 1).padStart(2, "0")}</span>
                <span className="anatomy-hero-disc-name">{it}</span>
              </li>
            ))}
          </ol>
          <div className="anatomy-hero-caps">
            <span className="anatomy-hero-caps-label">{dolado.capsLabel}</span>
            <span className="anatomy-hero-caps-sep" aria-hidden="true">—</span>
            <span className="anatomy-hero-caps-text">
              {dolado.caps.join("  ·  ")}
            </span>
          </div>
        </div>

        {/* Connector — single direction → */}
        <div className="anatomy-link" style={{ "--anatomy-delay": "240ms" }}>
          <FlowArrow />
          <div className="anatomy-link-labels">
            <span className="anatomy-link-label">{data.flows[1].down}</span>
          </div>
        </div>

        {/* Right column — stacked Marketplaces + Consumers */}
        <div className="anatomy-stack">
          {renderEndpoint(mkts, 3)}
          <div className="anatomy-stack-link" aria-hidden="true">
            <FlowArrow />
            <span className="anatomy-link-label anatomy-link-label-mute">{data.flows[2].down}</span>
          </div>
          {renderEndpoint(consumers, 4)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  DoladoDashboards: { OpsBoard, OpsAnatomy, PromptMatrix, GmvTimeline, CohortTracker }
});
