// ============================================================
// autoclient.io: EDITORIAL DATA-JOURNALISM CHART SYSTEM (Charts 01–12)
// Light-mode publication cards (#FFFFFF / #F9F8F6), Silka typography,
// coral (#FF6666) & purple (#8784FD) focal highlights, muted neutral context,
// keyboard/hover/tap inspection, zero SVG text overlaps or clipping.
// ============================================================
(() => {
  const { useState: useChState, useMemo: useChMemo, useRef: useChRef } = React;

  const INK = "#231F20";
  const INK_MUTED = "#5C5658";
  const GRID = "#ECE8E6";
  const AXIS = "#C8C2C4";
  const MUTED_DOT = "#B9B4B6";
  const CORAL = "#FF6666";
  const CORAL_INK = "#C93B3B";
  const PURPLE = "#8784FD";
  const PURPLE_INK = "#5652D6";
  const SLATE = "#767073";
  const FONT = '"Silka", "Helvetica Neue", Arial, system-ui, sans-serif';

  const fmtDollar = (v, dec = 2) => "$" + Number(v).toFixed(dec);
  const fmtPct = (v, dec = 2) => Number(v).toFixed(dec) + "%";
  const fmtSignedPct = (v, dec = 1) => (v > 0 ? "+" : "") + Number(v).toFixed(dec) + "%";
  const fmtSignedPp = (v, dec = 2) => (v > 0 ? "+" : "") + Number(v).toFixed(dec) + " pp";
  const pctChange = (prev, curr) => ((curr - prev) / prev) * 100;

  function renderHeadlineParts(parts) {
    if (!Array.isArray(parts)) return parts;
    return parts.map((p, idx) => {
      if (p.accent === "coral") return <span key={idx} className="rc-accent-coral">{p.text}</span>;
      if (p.accent === "purple") return <span key={idx} className="rc-accent-purple">{p.text}</span>;
      return <React.Fragment key={idx}>{p.text}</React.Fragment>;
    });
  }

  function a11yMarkProps(label, onSelect) {
    return {
      tabIndex: 0,
      role: "button",
      "aria-label": label,
      style: { cursor: "pointer" },
      onMouseEnter: onSelect,
      onFocus: onSelect,
      onClick: onSelect,
      onKeyDown: (e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          onSelect();
        }
      }
    };
  }

  /* ---------- Light-mode editorial card shell ---------- */
  function ResearchChartCard({
    chartId,
    kicker,
    headline,
    subtitle,
    sourceFootnote,
    sourceUrl,
    methodologyNote,
    controls,
    children,
    className
  }) {
    const LogoComp = window.Logo;
    return (
      <figure className={"rc-card" + (className ? " " + className : "")} data-chart-id={chartId || ""}>
        <div className="rc-head">
          {kicker && <div className="rc-kicker">{kicker}</div>}
          {headline && <h3 className="rc-headline">{Array.isArray(headline) ? renderHeadlineParts(headline) : headline}</h3>}
          {subtitle && <p className="rc-subtitle">{subtitle}</p>}
        </div>
        {controls && <div className="rc-controls">{controls}</div>}
        <div className="rc-plot-wrap">{children}</div>
        <figcaption className="rc-footer">
          <div className="rc-source-col">
            {sourceFootnote && (
              <div className="rc-source-line">
                <span className="rc-source-label">Source:</span>{" "}
                {sourceUrl ? (
                  <a href={sourceUrl} target="_blank" rel="noopener noreferrer" className="rc-source-link">
                    {sourceFootnote}
                  </a>
                ) : (
                  <span>{sourceFootnote}</span>
                )}
              </div>
            )}
            {methodologyNote && <div className="rc-method-note">{methodologyNote}</div>}
          </div>
          <div className="rc-brand-mark">
            {LogoComp ? <LogoComp negative={false} height={15} /> : <span className="rc-brand-fallback">autoclient</span>}
          </div>
        </figcaption>
      </figure>
    );
  }

  /* ---------- Pinned inspector readout below SVG ---------- */
  function ChartInspector({ badge, title, metrics = [], note }) {
    return (
      <div className="rc-inspector" role="status" aria-live="polite">
        <div className="rc-inspector-main">
          {badge && <span className="rc-inspector-badge">{badge}</span>}
          <strong className="rc-inspector-title">{title}</strong>
        </div>
        {metrics.length > 0 && (
          <div className="rc-inspector-metrics">
            {metrics.map((m, i) => (
              <div key={i} className="rc-inspector-kv">
                <span className="rc-inspector-k">{m.label}</span>
                <span className={"rc-inspector-v" + (m.tone ? " is-" + m.tone : "")}>{m.value}</span>
              </div>
            ))}
          </div>
        )}
        {note && <div className="rc-inspector-note">{note}</div>}
      </div>
    );
  }

  /* ============================================================
     CHART 01 — Search CPC vs CVR Bubble Scatter (23 Industries)
     ============================================================ */
  function Chart01({ ds, defaultHighlight }) {
    const rows = ds.search2026;
    const med = ds.search2026Overall;
    const [activeId, setActiveId] = useChState(defaultHighlight || "real-estate");
    const [pillId, setPillId] = useChState("all");

    const W = 760, H = 400;
    const L = 66, R = 732, T = 36, B = 344;
    const xScale = (v) => L + (v / 11) * (R - L);
    const yScale = (v) => B - (v / 18) * (B - T);
    const rScale = (cpl) => Math.sqrt(cpl) * 1.6;

    const active = rows.find((r) => r.id === activeId) || rows[0];

    const focalLabels = {
      "real-estate": { text: "Real Estate · $103", dx: -25, dy: -6, anchor: "end", color: CORAL_INK },
      "furniture": { text: "Furniture · $107", dx: 19, dy: 16, anchor: "start", color: CORAL_INK },
      "attorneys-legal": { text: "Attorneys · $132", dx: 0, dy: 35, anchor: "middle", color: CORAL_INK },
      "dentists": { text: "Dentists · $73", dx: 17, dy: -8, anchor: "start", color: PURPLE_INK },
      "auto-repair": { text: "Auto Repair · $30", dx: 13, dy: 4, anchor: "start", color: PURPLE_INK }
    };

    const quickPills = [
      { id: "all", label: "All 23" },
      { id: "real-estate", label: "Real Estate" },
      { id: "furniture", label: "Furniture" },
      { id: "attorneys-legal", label: "Attorneys" },
      { id: "dentists", label: "Dentists" },
      { id: "auto-repair", label: "Auto Repair" },
      { id: "home-improvement", label: "Home Services" }
    ];

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-pills" role="group" aria-label="Highlight industry">
          {quickPills.map((p) => (
            <button
              key={p.id}
              type="button"
              aria-pressed={pillId === p.id}
              className={"rc-pill" + (pillId === p.id ? " is-active" : "")}
              onClick={() => {
                setPillId(p.id);
                if (p.id !== "all") setActiveId(p.id);
              }}
            >
              {p.label}
            </button>
          ))}
        </div>
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />High CPL ($90+)</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />Efficient CVR (10%+)</span>
          <span className="rc-legend-item">Bubble area = published CPL</span>
        </div>
      </div>
    );

    const xTicks = [0, 2, 4, 6, 8, 10];
    const yTicks = [0, 4, 8, 12, 16];

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Scatter plot of 2026 Search CPC versus conversion rate across 23 industries, sized by median cost per lead">
            {/* Gridlines */}
            {xTicks.map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T} x2={xScale(t)} y2={B} stroke={GRID} strokeWidth="1" />
                <text x={xScale(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>${t}</text>
              </g>
            ))}
            {yTicks.map((t) => (
              <g key={"gy" + t}>
                <line x1={L} y1={yScale(t)} x2={R} y2={yScale(t)} stroke={GRID} strokeWidth="1" />
                <text x={L - 10} y={yScale(t) + 4} textAnchor="end" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            {/* Axes */}
            <line x1={L} y1={B} x2={R} y2={B} stroke={AXIS} strokeWidth="1.2" />
            <line x1={L} y1={T} x2={L} y2={B} stroke={AXIS} strokeWidth="1.2" />
            <text x={(L + R) / 2} y={H - 12} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Median Cost Per Click (USD)</text>
            <text x={18} y={(T + B) / 2} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT} transform={`rotate(-90 18 ${(T + B) / 2})`}>Conversion Rate (%)</text>

            {/* Median crosshairs */}
            <line x1={xScale(med.cpc26)} y1={T} x2={xScale(med.cpc26)} y2={B} stroke={AXIS} strokeWidth="1.2" strokeDasharray="4 4" />
            <text x={xScale(med.cpc26)} y={T - 10} textAnchor="middle" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>Median CPC $5.42</text>
            <line x1={L} y1={yScale(med.cvr26)} x2={R} y2={yScale(med.cvr26)} stroke={AXIS} strokeWidth="1.2" strokeDasharray="4 4" />
            <text x={R - 4} y={yScale(med.cvr26) - 7} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>Median CVR 8.18%</text>

            {/* Bubbles */}
            {rows.map((r) => {
              const cx = xScale(r.cpc26);
              const cy = yScale(r.cvr26);
              const rad = rScale(r.cpl26);
              const isAct = active.id === r.id;
              const isHighCpl = r.cpl26 >= 90;
              const isHighCvr = r.cvr26 >= 10.3;
              const fill = isHighCpl ? CORAL : isHighCvr ? PURPLE : MUTED_DOT;
              const dimmed = pillId !== "all" && pillId !== r.id && !isAct;
              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: ${fmtDollar(r.cpc26)} CPC, ${fmtPct(r.cvr26)} CVR, ${fmtDollar(r.cpl26)} CPL`, () => setActiveId(r.id))}>
                  {isAct && <circle cx={cx} cy={cy} r={rad + 4.5} fill="none" stroke={INK} strokeWidth="2" />}
                  <circle
                    cx={cx}
                    cy={cy}
                    r={rad}
                    fill={fill}
                    fillOpacity={dimmed ? 0.22 : isAct ? 0.92 : isHighCpl || isHighCvr ? 0.72 : 0.45}
                    stroke={isAct ? INK : "#FFFFFF"}
                    strokeWidth={isAct ? 1.8 : 1.2}
                  />
                </g>
              );
            })}

            {/* Curated direct labels (non-overlapping) */}
            {Object.entries(focalLabels).map(([id, cfg]) => {
              const r = rows.find((x) => x.id === id);
              if (!r) return null;
              const cx = xScale(r.cpc26);
              const cy = yScale(r.cvr26);
              return (
                <text
                  key={"lbl-" + id}
                  x={cx + cfg.dx}
                  y={cy + cfg.dy}
                  textAnchor={cfg.anchor}
                  fill={cfg.color}
                  fontSize="11"
                  fontWeight={active.id === id ? "700" : "600"}
                  fontFamily={FONT}
                  style={{ pointerEvents: "none" }}
                >
                  {cfg.text}
                </text>
              );
            })}
          </svg>
          <ChartInspector
            badge={active.isLocalService ? "Local Service" : "Search Benchmark"}
            title={active.name}
            metrics={[
              { label: "2026 CPC", value: fmtDollar(active.cpc26) },
              { label: "2026 CVR", value: fmtPct(active.cvr26), tone: active.cvr26 >= med.cvr26 ? "purple" : undefined },
              { label: "Published CPL", value: fmtDollar(active.cpl26), tone: active.cpl26 >= 90 ? "coral" : "purple" },
              { label: "2026 CTR", value: fmtPct(active.ctr26) }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 02 — Search CPC vs CPL YoY Change (2025 → 2026)
     ============================================================ */
  function Chart02({ ds, defaultHighlight }) {
    const rows = useChMemo(() => ds.search2026.map((r) => ({
      ...r,
      cpcYoy: pctChange(r.cpc25, r.cpc26),
      cplYoy: pctChange(r.cpl25, r.cpl26)
    })), [ds]);
    const [activeId, setActiveId] = useChState(defaultHighlight || "real-estate");
    const [quadFilter, setQuadFilter] = useChState("all");

    const W = 760, H = 400;
    const L = 68, R = 732, T = 36, B = 344;
    const xScale = (v) => L + ((v - (-28)) / (32 - (-28))) * (R - L);
    const yScale = (v) => B - ((v - (-44)) / (20 - (-44))) * (B - T);

    const active = rows.find((r) => r.id === activeId) || rows[0];

    const matchesFilter = (r) => {
      if (quadFilter === "all") return true;
      if (quadFilter === "cpc-up-cpl-down") return r.cpcYoy > 0 && r.cplYoy < 0;
      if (quadFilter === "cpc-up-cpl-up") return r.cpcYoy > 0 && r.cplYoy > 0;
      if (quadFilter === "cpc-down-cpl-down") return r.cpcYoy < 0 && r.cplYoy < 0;
      return true;
    };

    const focalLabels = {
      "travel": { text: "Travel (-39% CPL)", dx: 11, dy: 4, anchor: "start", color: PURPLE_INK },
      "beauty-personal-care": { text: "Beauty (-35% CPL)", dx: 11, dy: 4, anchor: "start", color: PURPLE_INK },
      "education": { text: "Education (-23% CPC)", dx: 11, dy: 4, anchor: "start", color: PURPLE_INK },
      "auto-for-sale": { text: "Auto For Sale (+14% CPL)", dx: -11, dy: 4, anchor: "end", color: CORAL_INK },
      "real-estate": { text: "Real Estate (+27% CPC)", dx: -11, dy: -9, anchor: "end", color: CORAL_INK },
      "attorneys-legal": { text: "Attorneys (+15% CPC, 0% CPL)", dx: 9, dy: 16, anchor: "start", color: INK_MUTED }
    };

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-pills" role="group" aria-label="Filter by quadrant">
          {[
            { id: "all", label: "All 23" },
            { id: "cpc-up-cpl-down", label: "CPC ↑ · CPL ↓" },
            { id: "cpc-up-cpl-up", label: "CPC ↑ · CPL ↑" },
            { id: "cpc-down-cpl-down", label: "CPC ↓ · CPL ↓" }
          ].map((p) => (
            <button key={p.id} type="button" aria-pressed={quadFilter === p.id} className={"rc-pill" + (quadFilter === p.id ? " is-active" : "")} onClick={() => setQuadFilter(p.id)}>
              {p.label}
            </button>
          ))}
        </div>
        <div className="rc-stat-pill">17/23 CPC ↑ · 13/23 CPL ↓</div>
      </div>
    );

    const xTicks = [-20, -10, 0, 10, 20, 30];
    const yTicks = [-40, -20, 0, 20];

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Four-quadrant scatter of 2025 to 2026 CPC change versus CPL change across 23 industries">
            {/* Soft tint on lower-right efficiency quadrant (CPC up, CPL down) */}
            <rect x={xScale(0)} y={yScale(0)} width={R - xScale(0)} height={B - yScale(0)} fill="rgba(135,132,253,0.06)" />
            {/* Grid */}
            {xTicks.map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T} x2={xScale(t)} y2={B} stroke={t === 0 ? AXIS : GRID} strokeWidth={t === 0 ? 1.5 : 1} />
                <text x={xScale(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t > 0 ? `+${t}%` : `${t}%`}</text>
              </g>
            ))}
            {yTicks.map((t) => (
              <g key={"gy" + t}>
                <line x1={L} y1={yScale(t)} x2={R} y2={yScale(t)} stroke={t === 0 ? AXIS : GRID} strokeWidth={t === 0 ? 1.5 : 1} />
                <text x={L - 10} y={yScale(t) + 4} textAnchor="end" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t > 0 ? `+${t}%` : `${t}%`}</text>
              </g>
            ))}
            <text x={(L + R) / 2} y={H - 12} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>CPC YoY Change (2025 → 2026)</text>
            <text x={18} y={(T + B) / 2} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT} transform={`rotate(-90 18 ${(T + B) / 2})`}>CPL YoY Change (%)</text>

            {/* Quadrant tags */}
            <text x={R - 6} y={T + 14} textAnchor="end" fill={CORAL_INK} fontSize="10" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">PRICIER CLICKS · PRICIER LEADS</text>
            <text x={R - 6} y={B - 10} textAnchor="end" fill={PURPLE_INK} fontSize="10" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">PRICIER CLICKS · CHEAPER LEADS</text>
            <text x={L + 8} y={B - 10} textAnchor="start" fill={INK_MUTED} fontSize="10" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">CHEAPER CLICKS · CHEAPER LEADS</text>

            {/* Points */}
            {rows.map((r) => {
              const cx = xScale(r.cpcYoy);
              const cy = yScale(r.cplYoy);
              const isAct = active.id === r.id;
              const match = matchesFilter(r);
              const fill = r.cplYoy < 0 ? PURPLE : r.cplYoy > 0 ? CORAL : SLATE;
              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: CPC ${fmtSignedPct(r.cpcYoy)}, CPL ${fmtSignedPct(r.cplYoy)}`, () => setActiveId(r.id))}>
                  {isAct && <circle cx={cx} cy={cy} r={10.5} fill="none" stroke={INK} strokeWidth="2" />}
                  <circle
                    cx={cx}
                    cy={cy}
                    r={isAct ? 7 : 6}
                    fill={fill}
                    fillOpacity={!match ? 0.16 : isAct ? 1 : 0.8}
                    stroke="#FFFFFF"
                    strokeWidth="1.4"
                  />
                </g>
              );
            })}

            {/* Direct labels */}
            {Object.entries(focalLabels).map(([id, cfg]) => {
              const r = rows.find((x) => x.id === id);
              if (!r) return null;
              return (
                <text
                  key={"lbl-" + id}
                  x={xScale(r.cpcYoy) + cfg.dx}
                  y={yScale(r.cplYoy) + cfg.dy}
                  textAnchor={cfg.anchor}
                  fill={cfg.color}
                  fontSize="11"
                  fontWeight={active.id === id ? "700" : "600"}
                  fontFamily={FONT}
                  style={{ pointerEvents: "none" }}
                >
                  {cfg.text}
                </text>
              );
            })}
          </svg>
          <ChartInspector
            badge="2025 → 2026"
            title={active.name}
            metrics={[
              { label: "CPC Change", value: `${fmtDollar(active.cpc25)} → ${fmtDollar(active.cpc26)} (${fmtSignedPct(active.cpcYoy)})`, tone: active.cpcYoy > 0 ? "coral" : "purple" },
              { label: "CPL Change", value: `${fmtDollar(active.cpl25)} → ${fmtDollar(active.cpl26)} (${fmtSignedPct(active.cplYoy)})`, tone: active.cplYoy < 0 ? "purple" : active.cplYoy > 0 ? "coral" : undefined },
              { label: "CVR", value: `${fmtPct(active.cvr25)} → ${fmtPct(active.cvr26)}` }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 03 — Local Service Industries CVR Dumbbell (11 rows)
     ============================================================ */
  function Chart03({ ds, defaultHighlight }) {
    const rows = useChMemo(() =>
      ds.search2026
        .filter((r) => r.isLocalService)
        .slice()
        .sort((a, b) => b.cvr26 - a.cvr26),
      [ds]
    );
    const medCvr = ds.search2026Overall.cvr26;
    const [activeId, setActiveId] = useChState(defaultHighlight || rows[0].id);

    const W = 760, H = 396;
    const L = 172, R = 640, T = 46, rowH = 28;
    const B = T + rows.length * rowH;
    const xScale = (v) => L + (v / 18) * (R - L);
    const active = rows.find((r) => r.id === activeId) || rows[0];

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: MUTED_DOT }} />2025 CVR</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />2026 CVR</span>
          <span className="rc-legend-item"><span className="rc-swatch-dash" />2026 overall median (8.18%)</span>
        </div>
        <div className="rc-stat-pill">11 / 11 Improved YoY</div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Horizontal dumbbell chart showing conversion rate gains from 2025 to 2026 across all 11 local service industries">
            {[0, 4, 8, 12, 16].map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T - 8} x2={xScale(t)} y2={B} stroke={GRID} strokeWidth="1" />
                <text x={xScale(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            {/* Median dashed line */}
            <line x1={xScale(medCvr)} y1={T - 12} x2={xScale(medCvr)} y2={B} stroke={CORAL} strokeWidth="1.3" strokeDasharray="4 4" />
            <text x={xScale(medCvr)} y={22} textAnchor="middle" fill={CORAL_INK} fontSize="10.5" fontWeight="700" fontFamily={FONT}>8.18% all-industry median</text>
            <text x={742} y={22} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>YoY Δ</text>

            {rows.map((r, i) => {
              const y = T + i * rowH + rowH / 2;
              const x1 = xScale(r.cvr25);
              const x2 = xScale(r.cvr26);
              const delta = r.cvr26 - r.cvr25;
              const isAct = active.id === r.id;
              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: ${fmtPct(r.cvr25)} in 2025 to ${fmtPct(r.cvr26)} in 2026 (${fmtSignedPp(delta)})`, () => setActiveId(r.id))}>
                  {isAct && <rect x={6} y={y - 13} width={W - 12} height={26} rx={6} fill="#F4F2F0" />}
                  <text x={L - 12} y={y + 4} textAnchor="end" fill={isAct ? INK : INK_MUTED} fontSize="12" fontWeight={isAct ? "700" : "500"} fontFamily={FONT}>
                    {r.shortName}
                  </text>
                  <line x1={x1} y1={y} x2={x2} y2={y} stroke={PURPLE} strokeWidth={isAct ? 3.5 : 2.6} strokeLinecap="round" />
                  <circle cx={x1} cy={y} r={4.5} fill={MUTED_DOT} stroke="#FFFFFF" strokeWidth="1.2" />
                  <circle cx={x2} cy={y} r={isAct ? 6.5 : 5.5} fill={PURPLE} stroke="#FFFFFF" strokeWidth="1.4" />
                  <text x={x2 + 9} y={y + 4} textAnchor="start" fill={INK} fontSize="11" fontWeight="600" fontFamily={FONT}>
                    {r.cvr26.toFixed(1)}%
                  </text>
                  <text x={742} y={y + 4} textAnchor="end" fill={PURPLE_INK} fontSize="11" fontWeight="700" fontFamily={FONT}>
                    {fmtSignedPp(delta)}
                  </text>
                </g>
              );
            })}
            <text x={(L + R) / 2} y={H - 8} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Search Conversion Rate (%)</text>
          </svg>
          <ChartInspector
            badge="Local Service"
            title={active.name}
            metrics={[
              { label: "2025 CVR", value: fmtPct(active.cvr25) },
              { label: "2026 CVR", value: fmtPct(active.cvr26), tone: "purple" },
              { label: "Gain", value: fmtSignedPp(active.cvr26 - active.cvr25), tone: "purple" },
              { label: "2026 CPL", value: fmtDollar(active.cpl26) }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 04 — CPC vs CPL Historical Path (2021–2026)
     ============================================================ */
  function Chart04({ ds }) {
    const pts = ds.searchHistory;
    const base = pts[0];
    const [mode, setMode] = useChState("indexed");
    const [activeYear, setActiveYear] = useChState(2026);

    const W = 760, H = 360;
    const L = 66, R = 612, T = 44, B = 304;
    const xScale = (yr) => L + ((yr - 2021) / 5) * (R - L);

    const indexed = pts.map((p) => ({
      ...p,
      cpcIdx: (p.cpc / base.cpc) * 100,
      cplIdx: (p.cpl / base.cpl) * 100
    }));

    const yIdx = (v) => B - ((v - 90) / 90) * (B - T);
    const yCpc = (v) => B - ((v - 3.0) / 3.0) * (B - T);
    const yCpl = (v) => B - ((v - 35) / 40) * (B - T);

    const active = indexed.find((p) => p.year === activeYear) || indexed[indexed.length - 1];

    const seg2023To2026 = indexed.slice(1);
    const linePath = (arr, getY) => arr.map((p, i) => `${i === 0 ? "M" : "L"}${xScale(p.year).toFixed(1)},${getY(p).toFixed(1)}`).join(" ");

    const getCpcY = (p) => (mode === "indexed" ? yIdx(p.cpcIdx) : yCpc(p.cpc));
    const getCplY = (p) => (mode === "indexed" ? yIdx(p.cplIdx) : yCpl(p.cpl));

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-pills" role="group" aria-label="Scale mode">
          <button type="button" aria-pressed={mode === "indexed"} className={"rc-pill" + (mode === "indexed" ? " is-active" : "")} onClick={() => setMode("indexed")}>
            Indexed (2021 = 100)
          </button>
          <button type="button" aria-pressed={mode === "dollars"} className={"rc-pill" + (mode === "dollars" ? " is-active" : "")} onClick={() => setMode("dollars")}>
            Dollar Values ($)
          </button>
        </div>
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />Median CPL (+61%)</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />Median CPC (+54%)</span>
        </div>
      </div>
    );

    const yearsAll = [2021, 2022, 2023, 2024, 2025, 2026];
    const peakPt = indexed.find((p) => p.year === 2025);
    const lastPt = indexed[indexed.length - 1];

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Five-year trajectory of Search median CPC and CPL from 2021 to 2026">
            {/* 2022 omitted vertical band */}
            <rect x={xScale(2022) - 24} y={T} width={48} height={B - T} fill="#F5F3F1" />
            <text x={xScale(2022)} y={T + 14} textAnchor="middle" fill={INK_MUTED} fontSize="9.5" fontWeight="600" fontFamily={FONT}>2022 omitted</text>

            {/* Gridlines */}
            {mode === "indexed" ? (
              [100, 120, 140, 160, 180].map((t) => (
                <g key={"gi" + t}>
                  <line x1={L} y1={yIdx(t)} x2={R} y2={yIdx(t)} stroke={t === 100 ? AXIS : GRID} strokeWidth={t === 100 ? 1.3 : 1} />
                  <text x={L - 10} y={yIdx(t) + 4} textAnchor="end" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}</text>
                </g>
              ))
            ) : (
              <>
                {[3, 4, 5, 6].map((t) => (
                  <g key={"gc" + t}>
                    <line x1={L} y1={yCpc(t)} x2={R} y2={yCpc(t)} stroke={GRID} strokeWidth="1" />
                    <text x={L - 10} y={yCpc(t) + 4} textAnchor="end" fill={CORAL_INK} fontSize="11" fontFamily={FONT}>${t.toFixed(0)}</text>
                  </g>
                ))}
                {[40, 50, 60, 70].map((t) => (
                  <text key={"gl" + t} x={R + 10} y={yCpl(t) + 4} textAnchor="start" fill={PURPLE_INK} fontSize="11" fontFamily={FONT}>${t}</text>
                ))}
              </>
            )}

            {/* X ticks */}
            <line x1={L} y1={B} x2={R} y2={B} stroke={AXIS} strokeWidth="1.2" />
            {yearsAll.map((yr) => (
              <text key={"yr" + yr} x={xScale(yr)} y={B + 20} textAnchor="middle" fill={yr === 2022 ? "#6E686A" : INK_MUTED} fontSize="11.5" fontWeight={yr === activeYear ? "700" : "500"} fontFamily={FONT}>
                {yr}
              </text>
            ))}

            {/* Axis titles */}
            <text x={18} y={(T + B) / 2} textAnchor="middle" fill={mode === "indexed" ? INK_MUTED : CORAL_INK} fontSize="11" fontWeight="600" fontFamily={FONT} transform={`rotate(-90 18 ${(T + B) / 2})`}>
              {mode === "indexed" ? "Index (2021 = 100)" : "Median CPC (USD)"}
            </text>
            {mode === "dollars" && (
              <text x={R + 50} y={(T + B) / 2} textAnchor="middle" fill={PURPLE_INK} fontSize="11" fontWeight="600" fontFamily={FONT} transform={`rotate(90 ${R + 50} ${(T + B) / 2})`}>
                Median CPL (USD)
              </text>
            )}

            {/* Dashed bridges 2021 -> 2023 */}
            <line x1={xScale(2021)} y1={getCplY(indexed[0])} x2={xScale(2023)} y2={getCplY(indexed[1])} stroke={PURPLE} strokeWidth="2.5" strokeDasharray="5 5" />
            <line x1={xScale(2021)} y1={getCpcY(indexed[0])} x2={xScale(2023)} y2={getCpcY(indexed[1])} stroke={CORAL} strokeWidth="2.5" strokeDasharray="5 5" />

            {/* Solid lines 2023 -> 2026 */}
            <path d={linePath(seg2023To2026, getCplY)} fill="none" stroke={PURPLE} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
            <path d={linePath(seg2023To2026, getCpcY)} fill="none" stroke={CORAL} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />

            {/* Peak 2025 CPL callout */}
            <text x={xScale(2025)} y={getCplY(peakPt) - 14} textAnchor="middle" fill={PURPLE_INK} fontSize="11" fontWeight="700" fontFamily={FONT}>
              2025 peak: $70.11
            </text>

            {/* Endpoint labels */}
            {mode === "indexed" && (
              <>
                <text x={R + 12} y={getCplY(lastPt) - 4} textAnchor="start" fill={PURPLE_INK} fontSize="11.5" fontWeight="700" fontFamily={FONT}>
                  CPL +61% ($66.69)
                </text>
                <text x={R + 12} y={getCpcY(lastPt) + 14} textAnchor="start" fill={CORAL_INK} fontSize="11.5" fontWeight="700" fontFamily={FONT}>
                  CPC +54% ($5.42)
                </text>
              </>
            )}

            {/* Interactive year points */}
            {indexed.map((p) => {
              const cx = xScale(p.year);
              const isAct = p.year === activeYear;
              return (
                <g key={p.year} {...a11yMarkProps(`${p.year}: CPC ${fmtDollar(p.cpc)}, CPL ${fmtDollar(p.cpl)}, CVR ${fmtPct(p.cvr)}`, () => setActiveYear(p.year))}>
                  {isAct && <line x1={cx} y1={T} x2={cx} y2={B} stroke={AXIS} strokeWidth="1" strokeDasharray="2 3" />}
                  <circle cx={cx} cy={getCplY(p)} r={isAct ? 7 : 5.5} fill={PURPLE} stroke="#FFFFFF" strokeWidth="2" />
                  <circle cx={cx} cy={getCpcY(p)} r={isAct ? 7 : 5.5} fill={CORAL} stroke="#FFFFFF" strokeWidth="2" />
                </g>
              );
            })}
          </svg>
          <ChartInspector
            badge={`${active.year} Wave`}
            title={`WordStream ${active.year} All-Industry Median`}
            metrics={[
              { label: "Median CPC", value: `${fmtDollar(active.cpc)} (${fmtSignedPct(active.cpcIdx - 100, 0)} vs '21)`, tone: "coral" },
              { label: "Median CPL", value: `${fmtDollar(active.cpl)} (${fmtSignedPct(active.cplIdx - 100, 0)} vs '21)`, tone: "purple" },
              { label: "Median CVR", value: fmtPct(active.cvr) },
              { label: "Median CTR", value: fmtPct(active.ctr) }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 05 — Meta Lead Ads CTR vs CVR Bubble Scatter (14 rows)
     ============================================================ */
  function Chart05({ ds, defaultHighlight }) {
    const rows = ds.metaLeads2026;
    const med = ds.metaLeadsOverall;
    const [activeId, setActiveId] = useChState(defaultHighlight || "dentists");
    const [pillId, setPillId] = useChState("all");

    const W = 760, H = 400;
    const L = 64, R = 732, T = 36, B = 344;
    const xScale = (v) => L + ((v - 0.8) / (4.6 - 0.8)) * (R - L);
    const yScale = (v) => B - ((v - 2) / (18 - 2)) * (B - T);
    const rScale = (cpl) => Math.sqrt(cpl) * 2.1;

    const active = rows.find((r) => r.id === activeId) || rows[0];

    const focalLabels = {
      "dentists": { text: "Dentists · $61.56", dx: 20, dy: -8, anchor: "start", color: CORAL_INK },
      "beauty-personal-care": { text: "Beauty · $50.91", dx: 0, dy: 28, anchor: "middle", color: CORAL_INK },
      "education": { text: "Education · 15.9% CVR", dx: 16, dy: 4, anchor: "start", color: PURPLE_INK },
      "real-estate": { text: "Real Estate · $13.74", dx: -14, dy: -12, anchor: "end", color: PURPLE_INK },
      "career-employment": { text: "Career · $12.30", dx: 12, dy: 4, anchor: "start", color: PURPLE_INK }
    };

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-pills" role="group" aria-label="Highlight Meta vertical">
          {[
            { id: "all", label: "All 14" },
            { id: "dentists", label: "Dentists" },
            { id: "beauty-personal-care", label: "Beauty" },
            { id: "education", label: "Education" },
            { id: "real-estate", label: "Real Estate" },
            { id: "career-employment", label: "Career" }
          ].map((p) => (
            <button key={p.id} type="button" aria-pressed={pillId === p.id} className={"rc-pill" + (pillId === p.id ? " is-active" : "")} onClick={() => {
              setPillId(p.id);
              if (p.id !== "all") setActiveId(p.id);
            }}>
              {p.label}
            </button>
          ))}
        </div>
        <div className="rc-stat-pill">r(CTR, CPL) = -0.66 · r(CVR, CPL) = -0.45</div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Scatter plot of 2026 Meta Lead Ads CTR versus conversion rate across 14 industries, sized by median CPL">
            {/* Low-CTR danger zone */}
            <rect x={L} y={T} width={xScale(2.2) - L} height={B - T} fill="rgba(255,102,102,0.06)" />
            <text x={L + 8} y={T + 14} textAnchor="start" fill={CORAL_INK} fontSize="10" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">LOW CTR · EXPENSIVE LEADS</text>

            {[1, 2, 3, 4].map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T} x2={xScale(t)} y2={B} stroke={GRID} strokeWidth="1" />
                <text x={xScale(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            {[4, 8, 12, 16].map((t) => (
              <g key={"gy" + t}>
                <line x1={L} y1={yScale(t)} x2={R} y2={yScale(t)} stroke={GRID} strokeWidth="1" />
                <text x={L - 10} y={yScale(t) + 4} textAnchor="end" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            <line x1={L} y1={B} x2={R} y2={B} stroke={AXIS} strokeWidth="1.2" />
            <line x1={L} y1={T} x2={L} y2={B} stroke={AXIS} strokeWidth="1.2" />
            <text x={(L + R) / 2} y={H - 12} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Meta Leads Click-Through Rate (%)</text>
            <text x={18} y={(T + B) / 2} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT} transform={`rotate(-90 18 ${(T + B) / 2})`}>Lead Form Conversion Rate (%)</text>

            {/* Medians */}
            <line x1={xScale(med.ctr)} y1={T} x2={xScale(med.ctr)} y2={B} stroke={AXIS} strokeWidth="1.2" strokeDasharray="4 4" />
            <text x={xScale(med.ctr)} y={T - 10} textAnchor="middle" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>Median CTR 2.70%</text>
            <line x1={L} y1={yScale(med.cvr)} x2={R} y2={yScale(med.cvr)} stroke={AXIS} strokeWidth="1.2" strokeDasharray="4 4" />
            <text x={R - 4} y={yScale(med.cvr) - 7} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>Median CVR 8.54%</text>

            {rows.map((r) => {
              const cx = xScale(r.ctr);
              const cy = yScale(r.cvr);
              const rad = rScale(r.cpl);
              const isAct = active.id === r.id;
              const isHighCpl = r.cpl >= 40;
              const isLowCpl = r.cpl <= 16;
              const fill = isHighCpl ? CORAL : isLowCpl ? PURPLE : MUTED_DOT;
              const dimmed = pillId !== "all" && pillId !== r.id && !isAct;
              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: ${fmtPct(r.ctr)} CTR, ${fmtPct(r.cvr)} CVR, ${fmtDollar(r.cpl)} CPL`, () => setActiveId(r.id))}>
                  {isAct && <circle cx={cx} cy={cy} r={rad + 4.5} fill="none" stroke={INK} strokeWidth="2" />}
                  <circle
                    cx={cx}
                    cy={cy}
                    r={rad}
                    fill={fill}
                    fillOpacity={dimmed ? 0.2 : isAct ? 0.92 : isHighCpl || isLowCpl ? 0.75 : 0.48}
                    stroke={isAct ? INK : "#FFFFFF"}
                    strokeWidth={isAct ? 1.8 : 1.2}
                  />
                </g>
              );
            })}

            {Object.entries(focalLabels).map(([id, cfg]) => {
              const r = rows.find((x) => x.id === id);
              if (!r) return null;
              return (
                <text
                  key={"lbl-" + id}
                  x={xScale(r.ctr) + cfg.dx}
                  y={yScale(r.cvr) + cfg.dy}
                  textAnchor={cfg.anchor}
                  fill={cfg.color}
                  fontSize="11"
                  fontWeight={active.id === id ? "700" : "600"}
                  fontFamily={FONT}
                  style={{ pointerEvents: "none" }}
                >
                  {cfg.text}
                </text>
              );
            })}
          </svg>
          <ChartInspector
            badge="Meta Leads"
            title={active.name}
            metrics={[
              { label: "Leads CTR", value: fmtPct(active.ctr), tone: active.ctr < 2 ? "coral" : "purple" },
              { label: "Leads CVR", value: fmtPct(active.cvr) },
              { label: "Leads CPC", value: fmtDollar(active.cpc) },
              { label: "Published CPL", value: fmtDollar(active.cpl), tone: active.cpl >= 40 ? "coral" : "purple" }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 06 — Meta Traffic vs Leads CPC Dumbbell (Overall + 13)
     ============================================================ */
  function Chart06({ ds, defaultHighlight }) {
    const overall = { id: "overall", name: "Overall Median (All Industries)", shortName: "Overall Median", ...ds.metaTrafficOverall, isOverall: true };
    const rows = [overall, ...ds.metaTrafficVsLeads2026];
    const [activeId, setActiveId] = useChState(defaultHighlight || "dentists");

    const W = 760, H = 486;
    const L = 166, R = 640, T = 44, rowH = 27;
    const rowY = (i) => T + i * rowH + (i > 0 ? 12 : 0) + rowH / 2;
    const B = rowY(rows.length - 1) + 20;
    const xScale = (v) => L + (v / 6.4) * (R - L);

    const active = rows.find((r) => r.id === activeId) || rows[1];

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: MUTED_DOT }} />Traffic CPC</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />Leads CPC</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />Highest premium (Dentists 9.3×)</span>
        </div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Horizontal dumbbell chart comparing Meta Traffic CPC versus Leads CPC across overall median and 13 industries">
            {[0, 1, 2, 3, 4, 5, 6].map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T - 6} x2={xScale(t)} y2={B} stroke={GRID} strokeWidth="1" />
                <text x={xScale(t)} y={B + 17} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>${t}</text>
              </g>
            ))}
            <text x={742} y={24} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>Leads ÷ Traffic</text>
            <line x1={12} y1={T + rowH + 6} x2={W - 12} y2={T + rowH + 6} stroke={AXIS} strokeWidth="1" strokeDasharray="3 3" />

            {rows.map((r, i) => {
              const y = rowY(i);
              const x1 = xScale(r.trafficCpc);
              const x2 = xScale(r.leadsCpc);
              const isAct = active.id === r.id;
              const isFocal = r.id === "dentists" || r.id === "beauty-personal-care";
              const barColor = isFocal ? CORAL : r.isOverall ? INK : PURPLE;
              const badgeColor = isFocal ? CORAL_INK : r.isOverall ? INK : PURPLE_INK;
              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: Traffic CPC ${fmtDollar(r.trafficCpc)}, Leads CPC ${fmtDollar(r.leadsCpc)}, ${r.multiple.toFixed(1)}x multiple`, () => setActiveId(r.id))}>
                  {isAct && <rect x={6} y={y - 12.5} width={W - 12} height={25} rx={6} fill="#F4F2F0" />}
                  <text x={L - 12} y={y + 4} textAnchor="end" fill={r.isOverall || isAct ? INK : INK_MUTED} fontSize="11.5" fontWeight={r.isOverall || isAct ? "700" : "500"} fontFamily={FONT}>
                    {r.shortName}
                  </text>
                  <line x1={x1} y1={y} x2={x2} y2={y} stroke={barColor} strokeWidth={isAct ? 3.5 : 2.5} strokeLinecap="round" />
                  <circle cx={x1} cy={y} r={4.5} fill={MUTED_DOT} stroke="#FFFFFF" strokeWidth="1.2" />
                  <circle cx={x2} cy={y} r={isAct ? 6.5 : 5.5} fill={barColor} stroke="#FFFFFF" strokeWidth="1.4" />
                  <text x={x2 + 9} y={y + 4} textAnchor="start" fill={INK} fontSize="11" fontWeight="600" fontFamily={FONT}>
                    {fmtDollar(r.leadsCpc)}
                  </text>
                  <text x={742} y={y + 4} textAnchor="end" fill={badgeColor} fontSize="11.5" fontWeight="700" fontFamily={FONT}>
                    {r.multiple.toFixed(1)}×
                  </text>
                </g>
              );
            })}
            <text x={(L + R) / 2} y={H - 6} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Median Cost Per Click (USD)</text>
          </svg>
          <ChartInspector
            badge={active.isOverall ? "All Industries" : "Meta Objective Gap"}
            title={active.name}
            metrics={[
              { label: "Traffic CPC", value: fmtDollar(active.trafficCpc) },
              { label: "Leads CPC", value: fmtDollar(active.leadsCpc), tone: active.multiple >= 5 ? "coral" : "purple" },
              { label: "Premium", value: `+${fmtDollar(active.leadsCpc - active.trafficCpc)} (${active.multiple.toFixed(2)}×)`, tone: active.multiple >= 5 ? "coral" : "purple" }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 07 — BrightLocal Review Sources 2025 vs 2026 (10 rows)
     ============================================================ */
  function Chart07({ ds, defaultHighlight }) {
    const allRows = ds.reviewSources2026;
    const [filter, setFilter] = useChState("all");
    const [activeId, setActiveId] = useChState(defaultHighlight || "chatgpt");

    const rows = useChMemo(() => {
      if (filter === "growing") return allRows.filter((r) => r.debut || (r.y2025 !== null && r.y2026 > r.y2025));
      if (filter === "declining") return allRows.filter((r) => r.y2025 !== null && r.y2026 < r.y2025);
      return allRows;
    }, [allRows, filter]);

    const active = rows.find((r) => r.id === activeId) || rows[0] || allRows[0];

    const W = 760, rowH = 30, T = 44;
    const H = T + rows.length * rowH + 46;
    const L = 152, R = 626;
    const B = T + rows.length * rowH;
    const xScale = (v) => L + (v / 92) * (R - L);

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-pills" role="group" aria-label="Filter platforms">
          {[
            { id: "all", label: "All 10" },
            { id: "growing", label: "Growing & Debut" },
            { id: "declining", label: "Declining" }
          ].map((p) => (
            <button key={p.id} type="button" aria-pressed={filter === p.id} className={"rc-pill" + (filter === p.id ? " is-active" : "")} onClick={() => setFilter(p.id)}>
              {p.label}
            </button>
          ))}
        </div>
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: MUTED_DOT }} />2025</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />2026 Up / Debut</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />2026 Down</span>
        </div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Horizontal dumbbell chart of consumer review and discovery platform usage in 2025 versus 2026">
            {[0, 20, 40, 60, 80].map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T - 6} x2={xScale(t)} y2={B} stroke={GRID} strokeWidth="1" />
                <text x={xScale(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            <text x={742} y={24} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>2025 → 2026</text>

            {rows.map((r, i) => {
              const y = T + i * rowH + rowH / 2;
              const x26 = xScale(r.y2026);
              const isAct = active.id === r.id;
              const has25 = r.y2025 !== null && r.y2025 !== undefined;
              const x25 = has25 ? xScale(r.y2025) : null;
              const delta = has25 ? r.y2026 - r.y2025 : null;
              const isDown = has25 && r.y2026 < r.y2025;
              const isFlat = has25 && r.y2026 === r.y2025;
              const dotColor = r.debut ? PURPLE : isDown ? CORAL : isFlat ? SLATE : PURPLE;
              const rightLabel = r.debut ? `Debut · ${r.y2026}%` : delta === 0 ? "0 pp" : `${delta > 0 ? "+" : ""}${delta} pp`;
              const rightColor = r.debut ? PURPLE_INK : isDown ? CORAL_INK : isFlat ? INK_MUTED : PURPLE_INK;
              const labelX = Math.max(x26, has25 ? x25 : x26) + (r.debut ? 14 : 10);

              return (
                <g
                  key={r.id}
                  {...a11yMarkProps(
                    r.debut
                      ? `${r.name}: debuted at ${r.y2026}% in 2026 (not fielded individually in 2025)`
                      : `${r.name}: ${r.y2025}% in 2025 to ${r.y2026}% in 2026 (${delta > 0 ? "+" : ""}${delta} pp)`,
                    () => setActiveId(r.id)
                  )}
                >
                  {isAct && <rect x={6} y={y - 13} width={W - 12} height={26} rx={6} fill="#F4F2F0" />}
                  <text x={L - 12} y={y + 4} textAnchor="end" fill={isAct || r.debut ? INK : INK_MUTED} fontSize="12" fontWeight={isAct || r.debut ? "700" : "500"} fontFamily={FONT}>
                    {r.name}
                  </text>
                  {has25 ? (
                    <>
                      <line x1={x25} y1={y} x2={x26} y2={y} stroke={dotColor} strokeWidth={isAct ? 3.5 : 2.6} strokeLinecap="round" />
                      <circle cx={x25} cy={y} r={4.5} fill={MUTED_DOT} stroke="#FFFFFF" strokeWidth="1.2" />
                      <circle cx={x26} cy={y} r={isAct ? 6.5 : 5.5} fill={dotColor} stroke="#FFFFFF" strokeWidth="1.4" />
                    </>
                  ) : (
                    <>
                      <circle cx={x26} cy={y} r={10} fill="rgba(135,132,253,0.16)" stroke={PURPLE} strokeWidth="1.2" strokeDasharray="2 2" />
                      <circle cx={x26} cy={y} r={6} fill={PURPLE} stroke="#FFFFFF" strokeWidth="1.5" />
                    </>
                  )}
                  <text x={labelX} y={y + 4} textAnchor="start" fill={INK} fontSize="11" fontWeight="600" fontFamily={FONT}>
                    {r.y2026}%
                  </text>
                  <text x={742} y={y + 4} textAnchor="end" fill={rightColor} fontSize="11" fontWeight="700" fontFamily={FONT}>
                    {rightLabel}
                  </text>
                </g>
              );
            })}
            <text x={(L + R) / 2} y={H - 8} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Share of US Consumers Using Platform to Research Local Businesses (%)</text>
          </svg>
          <ChartInspector
            badge={active.debut ? "2026 Debut" : "BrightLocal YoY"}
            title={active.name}
            metrics={[
              { label: "2025 Usage", value: active.y2025 === null ? "Not fielded (—)" : active.y2025 + "%" },
              { label: "2026 Usage", value: active.y2026 + "%", tone: active.y2025 !== null && active.y2026 < active.y2025 ? "coral" : "purple" },
              { label: "YoY Change", value: active.y2025 === null ? "First year tracked" : `${active.y2026 - active.y2025 > 0 ? "+" : ""}${active.y2026 - active.y2025} pp`, tone: active.y2025 !== null && active.y2026 < active.y2025 ? "coral" : "purple" }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 08 — Whitespark 2026 Ranking Factor Weights (8 groups)
     ============================================================ */
  function Chart08({ ds, defaultHighlight }) {
    const rows = ds.rankingFactors2026;
    const [showOrganic, setShowOrganic] = useChState(false);
    const [activeId, setActiveId] = useChState(defaultHighlight || "gbp");

    const W = 760;
    const rowH = showOrganic ? 54 : 38;
    const T = 44;
    const B = T + rows.length * rowH;
    const H = B + 46;
    const L = 186, R = 636;
    const xScale = (v) => L + (v / 38) * (R - L);

    const active = rows.find((r) => r.id === activeId) || rows[0];

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-pills" role="group" aria-label="Surface comparison mode">
          <button type="button" aria-pressed={!showOrganic} className={"rc-pill" + (!showOrganic ? " is-active" : "")} onClick={() => setShowOrganic(false)}>
            Maps vs. AI Search
          </button>
          <button type="button" aria-pressed={showOrganic} className={"rc-pill" + (showOrganic ? " is-active" : "")} onClick={() => setShowOrganic(true)}>
            + Include Local Organic
          </button>
        </div>
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />Local Pack / Maps</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />AI Search</span>
          {showOrganic && <span className="rc-legend-item"><span className="rc-swatch" style={{ background: SLATE }} />Local Organic</span>}
        </div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Grouped horizontal bar chart comparing Whitespark 2026 expert ranking weights across Local Pack Maps, AI Search, and Local Organic">
            {[0, 10, 20, 30].map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T - 6} x2={xScale(t)} y2={B} stroke={GRID} strokeWidth="1" />
                <text x={xScale(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            <line x1={L} y1={T - 6} x2={L} y2={B} stroke={AXIS} strokeWidth="1.2" />
            <text x={742} y={24} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>AI − Maps</text>

            {rows.map((r, i) => {
              const topY = T + i * rowH;
              const midY = topY + rowH / 2;
              const delta = r.ai - r.maps;
              const isAct = active.id === r.id;
              const barH = showOrganic ? 9 : 11;
              const gap = showOrganic ? 5 : 3;
              const startBarY = showOrganic ? topY + 8 : topY + 7;

              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: Maps ${r.maps}%, AI Search ${r.ai}%, Local Organic ${r.organic}%`, () => setActiveId(r.id))}>
                  {isAct && <rect x={6} y={topY + 1} width={W - 12} height={rowH - 2} rx={6} fill="#F4F2F0" />}
                  <text x={L - 12} y={midY + 4} textAnchor="end" fill={isAct ? INK : INK_MUTED} fontSize="12" fontWeight={isAct ? "700" : "500"} fontFamily={FONT}>
                    {r.name}
                  </text>
                  {/* Maps bar */}
                  <rect x={L} y={startBarY} width={Math.max(2, xScale(r.maps) - L)} height={barH} rx={3} fill={CORAL} fillOpacity={isAct ? 1 : 0.88} />
                  <text x={xScale(r.maps) + 6} y={startBarY + barH - 1} textAnchor="start" fill={CORAL_INK} fontSize="10" fontWeight="700" fontFamily={FONT}>{r.maps}%</text>
                  {/* AI bar */}
                  <rect x={L} y={startBarY + barH + gap} width={Math.max(2, xScale(r.ai) - L)} height={barH} rx={3} fill={PURPLE} fillOpacity={isAct ? 1 : 0.88} />
                  <text x={xScale(r.ai) + 6} y={startBarY + barH * 2 + gap - 1} textAnchor="start" fill={PURPLE_INK} fontSize="10" fontWeight="700" fontFamily={FONT}>{r.ai}%</text>
                  {/* Optional Local Organic bar */}
                  {showOrganic && (
                    <>
                      <rect x={L} y={startBarY + (barH + gap) * 2} width={Math.max(2, xScale(r.organic) - L)} height={barH} rx={3} fill={SLATE} fillOpacity={isAct ? 0.95 : 0.72} />
                      <text x={xScale(r.organic) + 6} y={startBarY + barH * 3 + gap * 2 - 1} textAnchor="start" fill={INK_MUTED} fontSize="10" fontWeight="600" fontFamily={FONT}>{r.organic}%</text>
                    </>
                  )}
                  <text x={742} y={midY + 4} textAnchor="end" fill={delta > 0 ? PURPLE_INK : CORAL_INK} fontSize="11.5" fontWeight="700" fontFamily={FONT}>
                    {delta > 0 ? `+${delta} pp` : `${delta} pp`}
                  </text>
                </g>
              );
            })}
            <text x={(L + R) / 2} y={H - 8} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Expert-Estimated Signal Weight (each surface sums to 100%)</text>
          </svg>
          <ChartInspector
            badge="Whitespark 2026"
            title={active.name}
            metrics={[
              { label: "Local Pack / Maps", value: active.maps + "%", tone: "coral" },
              { label: "AI Search Visibility", value: active.ai + "%", tone: "purple" },
              { label: "AI − Maps Shift", value: `${active.ai - active.maps > 0 ? "+" : ""}${active.ai - active.maps} pp`, tone: active.ai > active.maps ? "purple" : "coral" },
              { label: "Local Organic", value: active.organic + "%" }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 09 — Ahrefs Feb 2026 AI Overviews CTR Loss by Rank (#1–#10)
     ============================================================ */
  function Chart09({ ds, defaultHighlight }) {
    const rows = ds.aiOverviewsCtr2026;
    const [activeRank, setActiveRank] = useChState(defaultHighlight || 1);

    const W = 760, H = 356;
    const L = 66, R = 730, T = 44, B = 304;
    const yScale = (pct) => T + (Math.abs(pct) / 65) * (B - T);
    const step = (R - L) / rows.length;
    const barW = 38;
    const active = rows.find((r) => r.rank === activeRank) || rows[0];

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />Top-3 ranks (-58.0% to -46.4%)</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />Ranks #4–#10</span>
          <span className="rc-legend-item"><span className="rc-swatch-dash" />Apr 2025 #1 baseline (-34.5%)</span>
        </div>
      </div>
    );

    const refY = yScale(-34.5);

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Hanging negative bar chart showing AI Overview desktop CTR loss from organic rank 1 through 10">
            {[0, -15, -30, -45, -60].map((t) => (
              <g key={"gy" + t}>
                <line x1={L} y1={yScale(t)} x2={R} y2={yScale(t)} stroke={t === 0 ? AXIS : GRID} strokeWidth={t === 0 ? 1.5 : 1} />
                <text x={L - 10} y={yScale(t) + 4} textAnchor="end" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t === 0 ? "0%" : `${t}%`}</text>
              </g>
            ))}

            {/* Reference line: Apr 2025 -34.5% */}
            <line x1={L} y1={refY} x2={R} y2={refY} stroke={INK_MUTED} strokeWidth="1.3" strokeDasharray="5 4" />
            <text x={R - 4} y={refY + 18} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>
              Apr 2025 #1 baseline (-34.5%)
            </text>

            {/* Bars */}
            {rows.map((r, i) => {
              const cx = L + step * i + step / 2;
              const yEnd = yScale(r.dropPct);
              const isAct = r.rank === activeRank;
              const fill = r.rank <= 3 ? CORAL : PURPLE;
              const txtColor = r.rank <= 3 ? CORAL_INK : PURPLE_INK;
              return (
                <g key={r.rank} {...a11yMarkProps(`Organic position #${r.rank}: ${r.dropPct.toFixed(1)}% CTR impact when an AI Overview appears`, () => setActiveRank(r.rank))}>
                  <text x={cx} y={T - 12} textAnchor="middle" fill={isAct ? INK : INK_MUTED} fontSize="11.5" fontWeight={isAct ? "700" : "600"} fontFamily={FONT}>
                    #{r.rank}
                  </text>
                  <rect
                    x={cx - barW / 2}
                    y={T}
                    width={barW}
                    height={Math.max(4, yEnd - T)}
                    rx={4}
                    fill={fill}
                    fillOpacity={isAct ? 1 : r.rank === 1 ? 0.94 : 0.78}
                    stroke={isAct ? INK : "none"}
                    strokeWidth={isAct ? 1.8 : 0}
                  />
                  <text x={cx} y={yEnd + 15} textAnchor="middle" fill={isAct ? INK : txtColor} fontSize="10.5" fontWeight="700" fontFamily={FONT}>
                    {r.dropPct.toFixed(1)}%
                  </text>
                </g>
              );
            })}
            <text x={18} y={(T + B) / 2} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT} transform={`rotate(-90 18 ${(T + B) / 2})`}>CTR Impact With AI Overview (%)</text>
            <text x={(L + R) / 2} y={H - 10} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Organic Search Rank Position (Page 1)</text>
          </svg>
          <ChartInspector
            badge={`Rank #${active.rank}`}
            title={`Organic Position #${active.rank} CTR Shortfall`}
            metrics={[
              { label: "Feb 2026 Impact", value: `${active.dropPct.toFixed(1)}%`, tone: active.rank <= 3 ? "coral" : "purple" },
              { label: "Apr 2025 #1 Baseline", value: "-34.5%" },
              { label: "Sample", value: "300,000 keywords (desktop GSC)" }
            ]}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 10 — Pew Research Center Jul 2025: Clicks vs Exits
     ============================================================ */
  function Chart10({ ds }) {
    const pew = ds.pewAiBehavior2025;
    const groups = [
      {
        id: "result-click",
        label: "Clicked traditional result",
        withoutAi: pew.withoutAi.resultClick,
        withAi: pew.withAi.resultClick,
        deltaLabel: "-47% relative",
        deltaTone: "coral",
        withColor: CORAL,
        summary: "Clicks to standard search links fell from 15% of visits without an AI summary to 8% when an AI summary appeared (-7 pp)."
      },
      {
        id: "ai-link",
        label: "Clicked AI summary link",
        withoutAi: null,
        withAi: pew.withAi.aiLinkClick,
        deltaLabel: "1% citation CTR",
        deltaTone: "purple",
        withColor: PURPLE,
        summary: "Only 1% of searches with an AI summary resulted in a click on a source link inside the summary itself."
      },
      {
        id: "session-exit",
        label: "Ended browsing session",
        withoutAi: pew.withoutAi.sessionExit,
        withAi: pew.withAi.sessionExit,
        deltaLabel: "+63% relative",
        deltaTone: "coral",
        withColor: CORAL,
        summary: "26% of visits with an AI summary ended the browsing session entirely vs. 16% without one (+10 pp)."
      }
    ];

    const [activeId, setActiveId] = useChState("result-click");
    const active = groups.find((g) => g.id === activeId) || groups[0];

    const W = 760, H = 356;
    const L = 66, R = 730, T = 48, B = 286;
    const yScale = (v) => B - (v / 32) * (B - T);
    const centers = [184, 398, 612];
    const barW = 54;
    const barGap = 14;

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: MUTED_DOT }} />Without AI summary</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />With AI summary (click loss / exit jump)</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />AI citation link click</span>
        </div>
        <div className="rc-stat-pill">Cross-sectional · Mar 2025</div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Grouped bar chart comparing Google user click and session exit behavior with versus without an AI summary">
            {[0, 10, 20, 30].map((t) => (
              <g key={"gy" + t}>
                <line x1={L} y1={yScale(t)} x2={R} y2={yScale(t)} stroke={t === 0 ? AXIS : GRID} strokeWidth={t === 0 ? 1.4 : 1} />
                <text x={L - 10} y={yScale(t) + 4} textAnchor="end" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            <text x={18} y={(T + B) / 2} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT} transform={`rotate(-90 18 ${(T + B) / 2})`}>Share of Google Search Visits (%)</text>

            {groups.map((g, i) => {
              const cx = centers[i];
              const leftX = cx - barW - barGap / 2;
              const rightX = cx + barGap / 2;
              const isAct = active.id === g.id;
              const maxVal = Math.max(g.withoutAi || 0, g.withAi);
              const badgeY = Math.min(yScale(maxVal) - 28, T + 4);

              return (
                <g
                  key={g.id}
                  {...a11yMarkProps(
                    `${g.label}: ${g.withoutAi === null ? "N/A without AI" : g.withoutAi + "% without AI"} vs ${g.withAi}% with AI summary`,
                    () => setActiveId(g.id)
                  )}
                >
                  {isAct && <rect x={cx - 86} y={T - 26} width={172} height={B - T + 68} rx={10} fill="#F7F5F3" />}
                  {/* Delta label above group */}
                  <text x={cx} y={badgeY} textAnchor="middle" fill={g.deltaTone === "coral" ? CORAL_INK : PURPLE_INK} fontSize="11" fontWeight="700" fontFamily={FONT}>
                    {g.deltaLabel}
                  </text>

                  {/* Without AI bar */}
                  {g.withoutAi === null ? (
                    <>
                      <rect x={leftX} y={B - 14} width={barW} height={14} rx={3} fill="none" stroke={AXIS} strokeWidth="1.2" strokeDasharray="3 3" />
                      <text x={leftX + barW / 2} y={B - 20} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontWeight="600" fontFamily={FONT}>N/A</text>
                    </>
                  ) : (
                    <>
                      <rect x={leftX} y={yScale(g.withoutAi)} width={barW} height={B - yScale(g.withoutAi)} rx={4} fill={MUTED_DOT} />
                      <text x={leftX + barW / 2} y={yScale(g.withoutAi) - 7} textAnchor="middle" fill={INK_MUTED} fontSize="12" fontWeight="700" fontFamily={FONT}>{g.withoutAi}%</text>
                    </>
                  )}

                  {/* With AI bar */}
                  <rect x={rightX} y={yScale(g.withAi)} width={barW} height={Math.max(6, B - yScale(g.withAi))} rx={4} fill={g.withColor} />
                  <text x={rightX + barW / 2} y={yScale(g.withAi) - 7} textAnchor="middle" fill={g.withColor === CORAL ? CORAL_INK : PURPLE_INK} fontSize="12" fontWeight="700" fontFamily={FONT}>
                    {g.withAi}%
                  </text>

                  {/* Category label */}
                  <text x={cx} y={B + 22} textAnchor="middle" fill={isAct ? INK : INK_MUTED} fontSize="12" fontWeight={isAct ? "700" : "600"} fontFamily={FONT}>
                    {g.label}
                  </text>
                </g>
              );
            })}
          </svg>
          <ChartInspector
            badge="Pew Research Center"
            title={active.label}
            metrics={[
              { label: "Without AI Summary", value: active.withoutAi === null ? "N/A" : active.withoutAi + "%" },
              { label: "With AI Summary", value: active.withAi + "%", tone: active.deltaTone },
              { label: "Shift", value: active.deltaLabel, tone: active.deltaTone }
            ]}
            note={active.summary}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 11 — SE Ranking Jun 2026: AI Referrals Share vs YoY Growth
     ============================================================ */
  function Chart11({ ds, defaultHighlight }) {
    const rows = ds.aiReferrals2026;
    const [activeId, setActiveId] = useChState(defaultHighlight || "chatgpt");
    const active = rows.find((r) => r.id === activeId) || rows[0];

    const W = 760, H = 290;
    const L1 = 142, R1 = 386; // Left panel: 2026 Share (0% -> 85%)
    const DIV = 448;
    const L2 = 472, R2 = 690; // Right panel: YoY Growth (-25% -> +355%)
    const T = 44, rowH = 42;
    const B = T + rows.length * rowH;

    const xShare = (v) => L1 + (v / 85) * (R1 - L1);
    const xGrowth = (v) => L2 + ((v - (-25)) / (355 - (-25))) * (R2 - L2);
    const zeroX = xGrowth(0);

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-legend">
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: PURPLE }} />Share leader (ChatGPT 74.78%)</span>
          <span className="rc-legend-item"><span className="rc-swatch" style={{ background: CORAL }} />Fastest YoY growth (Claude +320%, Gemini +231%)</span>
        </div>
        <div className="rc-stat-pill">Top 5 = 99.70% of AI referrals</div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Synchronized dual-panel bar chart showing 2026 global AI referral share alongside year-over-year referral traffic growth from SE Ranking">
            {/* Panel titles */}
            <text x={L1} y={24} textAnchor="start" fill={INK_MUTED} fontSize="10.5" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">2026 GLOBAL AI REFERRAL SHARE</text>
            <text x={L2} y={24} textAnchor="start" fill={INK_MUTED} fontSize="10.5" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">YOY REFERRAL GROWTH (2025 → 2026)</text>

            {/* Panel A grid */}
            {[0, 25, 50, 75].map((t) => (
              <g key={"ga" + t}>
                <line x1={xShare(t)} y1={T - 6} x2={xShare(t)} y2={B} stroke={t === 0 ? AXIS : GRID} strokeWidth={t === 0 ? 1.2 : 1} />
                <text x={xShare(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="10.5" fontFamily={FONT}>{t}%</text>
              </g>
            ))}

            {/* Divider */}
            <line x1={DIV} y1={T - 10} x2={DIV} y2={B + 4} stroke={GRID} strokeWidth="1.2" />

            {/* Panel B grid */}
            {[0, 100, 200, 300].map((t) => (
              <g key={"gb" + t}>
                <line x1={xGrowth(t)} y1={T - 6} x2={xGrowth(t)} y2={B} stroke={t === 0 ? AXIS : GRID} strokeWidth={t === 0 ? 1.4 : 1} />
                <text x={xGrowth(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="10.5" fontFamily={FONT}>{t === 0 ? "0%" : `+${t}%`}</text>
              </g>
            ))}

            {rows.map((r, i) => {
              const y = T + i * rowH + rowH / 2;
              const isAct = active.id === r.id;
              const shareW = Math.max(4, xShare(r.sharePct) - L1);
              const shareFill = r.id === "chatgpt" ? PURPLE : MUTED_DOT;
              const isFast = r.yoyPct >= 200;
              const isNeg = r.yoyPct < 0;
              const gFill = isFast ? CORAL : isNeg ? SLATE : PURPLE;
              const gx1 = isNeg ? xGrowth(r.yoyPct) : zeroX;
              const gw = Math.max(4, Math.abs(xGrowth(r.yoyPct) - zeroX));
              const gLabelX = isNeg ? zeroX + 8 : zeroX + gw + 8;

              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: ${r.sharePct}% share of AI referrals, ${r.yoyLabel} YoY growth`, () => setActiveId(r.id))}>
                  {isAct && <rect x={6} y={y - 16} width={W - 12} height={32} rx={6} fill="#F4F2F0" />}
                  <text x={L1 - 12} y={y + 4} textAnchor="end" fill={isAct ? INK : INK_MUTED} fontSize="12" fontWeight={isAct || r.id === "chatgpt" ? "700" : "500"} fontFamily={FONT}>
                    {r.name}
                  </text>
                  {/* Left bar: Share */}
                  <rect x={L1} y={y - 9} width={shareW} height={18} rx={4} fill={shareFill} fillOpacity={isAct ? 1 : 0.85} />
                  <text x={L1 + shareW + 8} y={y + 4} textAnchor="start" fill={r.id === "chatgpt" ? PURPLE_INK : INK} fontSize="11" fontWeight="700" fontFamily={FONT}>
                    {r.sharePct.toFixed(2)}%
                  </text>
                  {/* Right bar: YoY growth */}
                  <rect x={gx1} y={y - 9} width={gw} height={18} rx={4} fill={gFill} fillOpacity={isAct ? 1 : 0.88} />
                  <text x={gLabelX} y={y + 4} textAnchor="start" fill={isFast ? CORAL_INK : isNeg ? INK_MUTED : PURPLE_INK} fontSize="11" fontWeight="700" fontFamily={FONT}>
                    {r.yoyLabel}
                  </text>
                </g>
              );
            })}
          </svg>
          <ChartInspector
            badge="SE Ranking · Jun 2026"
            title={active.name}
            metrics={[
              { label: "2026 AI Referral Share", value: active.sharePct.toFixed(2) + "%", tone: active.id === "chatgpt" ? "purple" : undefined },
              { label: "YoY Growth", value: active.yoyLabel, tone: active.yoyPct >= 200 ? "coral" : active.yoyPct > 0 ? "purple" : undefined },
              { label: "Study Scope", value: "101,574 GA4 sites (0.32% of web traffic)" }
            ]}
            note={active.derived ? "*Derived from SE Ranking's published total-traffic shares for Perplexity (0.0245% in 2025 → 0.0230% in 2026, described as a slight decline)." : undefined}
          />
        </>
      )
    };
  }

  /* ============================================================
     CHART 12 — Search CTR vs CVR 2×2 Quadrant (23 Industries)
     ============================================================ */
  function Chart12({ ds, defaultHighlight }) {
    const rows = ds.search2026;
    const med = ds.search2026Overall;
    const [activeId, setActiveId] = useChState(defaultHighlight || "auto-repair");
    const [quad, setQuad] = useChState("all");

    const W = 760, H = 400;
    const L = 64, R = 732, T = 36, B = 344;
    const xScale = (v) => L + ((v - 4.8) / (13.6 - 4.8)) * (R - L);
    const yScale = (v) => B - ((v - 1.5) / (17.5 - 1.5)) * (B - T);

    const active = rows.find((r) => r.id === activeId) || rows[0];

    const matchesQuad = (r) => {
      if (quad === "all") return true;
      if (quad === "low-high") return r.ctr26 < med.ctr26 && r.cvr26 >= med.cvr26;
      if (quad === "high-high") return r.ctr26 >= med.ctr26 && r.cvr26 >= med.cvr26;
      if (quad === "high-low") return r.ctr26 >= med.ctr26 && r.cvr26 < med.cvr26;
      if (quad === "low-low") return r.ctr26 < med.ctr26 && r.cvr26 < med.cvr26;
      return true;
    };

    const focalLabels = {
      "auto-repair": { text: "Auto Repair (5.56% · 15.51%)", dx: 15, dy: 20, anchor: "start", color: CORAL_INK },
      "animals-pets": { text: "Animals & Pets (16.22% CVR)", dx: 11, dy: 4, anchor: "start", color: PURPLE_INK },
      "dentists": { text: "Dentists (5.66% · 10.67%)", dx: 11, dy: 4, anchor: "start", color: PURPLE_INK },
      "attorneys-legal": { text: "Attorneys (5.87% · 5.55%)", dx: 11, dy: 4, anchor: "start", color: INK_MUTED },
      "finance-insurance": { text: "Finance (2.64% CVR)", dx: 11, dy: 4, anchor: "start", color: INK_MUTED },
      "arts-entertainment": { text: "Arts & Ent. (12.75% CTR)", dx: -11, dy: -8, anchor: "end", color: INK_MUTED }
    };

    const controls = (
      <div className="rc-controls-row">
        <div className="rc-pills" role="group" aria-label="Filter by quadrant">
          {[
            { id: "all", label: "All 23" },
            { id: "low-high", label: "Low CTR · High CVR" },
            { id: "high-high", label: "High CTR · High CVR" },
            { id: "high-low", label: "High CTR · Low CVR" },
            { id: "low-low", label: "Low CTR · Low CVR" }
          ].map((p) => (
            <button key={p.id} type="button" aria-pressed={quad === p.id} className={"rc-pill" + (quad === p.id ? " is-active" : "")} onClick={() => setQuad(p.id)}>
              {p.label}
            </button>
          ))}
        </div>
      </div>
    );

    return {
      controls,
      body: (
        <>
          <svg className="rc-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Quadrant scatter plot of 2026 Search CTR versus conversion rate across 23 industries highlighting Auto Repair">
            {/* Quiet converters quadrant highlight */}
            <rect x={L} y={T} width={xScale(med.ctr26) - L} height={yScale(med.cvr26) - T} fill="rgba(135,132,253,0.06)" />

            {[5, 7, 9, 11, 13].map((t) => (
              <g key={"gx" + t}>
                <line x1={xScale(t)} y1={T} x2={xScale(t)} y2={B} stroke={GRID} strokeWidth="1" />
                <text x={xScale(t)} y={B + 18} textAnchor="middle" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            {[2, 6, 10, 14].map((t) => (
              <g key={"gy" + t}>
                <line x1={L} y1={yScale(t)} x2={R} y2={yScale(t)} stroke={GRID} strokeWidth="1" />
                <text x={L - 10} y={yScale(t) + 4} textAnchor="end" fill={INK_MUTED} fontSize="11" fontFamily={FONT}>{t}%</text>
              </g>
            ))}
            <line x1={L} y1={B} x2={R} y2={B} stroke={AXIS} strokeWidth="1.2" />
            <line x1={L} y1={T} x2={L} y2={B} stroke={AXIS} strokeWidth="1.2" />
            <text x={(L + R) / 2} y={H - 12} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT}>Search Click-Through Rate (%)</text>
            <text x={18} y={(T + B) / 2} textAnchor="middle" fill={INK_MUTED} fontSize="11.5" fontWeight="600" fontFamily={FONT} transform={`rotate(-90 18 ${(T + B) / 2})`}>Search Conversion Rate (%)</text>

            {/* Median crosshairs */}
            <line x1={xScale(med.ctr26)} y1={T} x2={xScale(med.ctr26)} y2={B} stroke={AXIS} strokeWidth="1.2" strokeDasharray="4 4" />
            <text x={xScale(med.ctr26)} y={T - 10} textAnchor="middle" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>Median CTR 6.64%</text>
            <line x1={L} y1={yScale(med.cvr26)} x2={R} y2={yScale(med.cvr26)} stroke={AXIS} strokeWidth="1.2" strokeDasharray="4 4" />
            <text x={R - 4} y={yScale(med.cvr26) - 7} textAnchor="end" fill={INK_MUTED} fontSize="10.5" fontWeight="600" fontFamily={FONT}>Median CVR 8.18%</text>

            {/* Quadrant corner tags */}
            <text x={L + 8} y={T + 14} textAnchor="start" fill={PURPLE_INK} fontSize="10" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">LOW CTR · HIGH CVR</text>
            <text x={R - 6} y={T + 14} textAnchor="end" fill={INK_MUTED} fontSize="10" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">HIGH CTR · HIGH CVR</text>
            <text x={R - 6} y={B - 10} textAnchor="end" fill={INK_MUTED} fontSize="10" fontWeight="700" fontFamily={FONT} letterSpacing="0.06em">HIGH CTR · LOW CVR</text>

            {/* Points */}
            {rows.map((r) => {
              const cx = xScale(r.ctr26);
              const cy = yScale(r.cvr26);
              const isAuto = r.id === "auto-repair";
              const isAct = active.id === r.id;
              const match = matchesQuad(r);
              const fill = isAuto ? CORAL : r.cvr26 >= med.cvr26 ? PURPLE : MUTED_DOT;
              return (
                <g key={r.id} {...a11yMarkProps(`${r.name}: ${fmtPct(r.ctr26)} CTR, ${fmtPct(r.cvr26)} CVR, ${fmtDollar(r.cpl26)} CPL`, () => setActiveId(r.id))}>
                  {isAuto && <circle cx={cx} cy={cy} r={12} fill="rgba(255,102,102,0.16)" stroke={CORAL} strokeWidth="1.4" />}
                  {isAct && <circle cx={cx} cy={cy} r={isAuto ? 15 : 10} fill="none" stroke={INK} strokeWidth="1.8" />}
                  <circle
                    cx={cx}
                    cy={cy}
                    r={isAuto ? 7.5 : isAct ? 6.5 : 5.5}
                    fill={fill}
                    fillOpacity={!match ? 0.16 : isAct || isAuto ? 1 : 0.78}
                    stroke="#FFFFFF"
                    strokeWidth="1.4"
                  />
                </g>
              );
            })}

            {Object.entries(focalLabels).map(([id, cfg]) => {
              const r = rows.find((x) => x.id === id);
              if (!r) return null;
              return (
                <text
                  key={"lbl-" + id}
                  x={xScale(r.ctr26) + cfg.dx}
                  y={yScale(r.cvr26) + cfg.dy}
                  textAnchor={cfg.anchor}
                  fill={cfg.color}
                  fontSize="11"
                  fontWeight={active.id === id || id === "auto-repair" ? "700" : "600"}
                  fontFamily={FONT}
                  style={{ pointerEvents: "none" }}
                >
                  {cfg.text}
                </text>
              );
            })}
          </svg>
          <ChartInspector
            badge={active.id === "auto-repair" ? "#1 Lowest CTR · #2 Highest CVR" : "Search Quadrant"}
            title={active.name}
            metrics={[
              { label: "2026 CTR", value: fmtPct(active.ctr26), tone: active.ctr26 < med.ctr26 ? "coral" : undefined },
              { label: "2026 CVR", value: fmtPct(active.cvr26), tone: active.cvr26 >= med.cvr26 ? "purple" : undefined },
              { label: "2026 CPC", value: fmtDollar(active.cpc26) },
              { label: "Published CPL", value: fmtDollar(active.cpl26) }
            ]}
          />
        </>
      )
    };
  }

  const CHART_RENDERERS = {
    chart01: Chart01,
    chart02: Chart02,
    chart03: Chart03,
    chart04: Chart04,
    chart05: Chart05,
    chart06: Chart06,
    chart07: Chart07,
    chart08: Chart08,
    chart09: Chart09,
    chart10: Chart10,
    chart11: Chart11,
    chart12: Chart12
  };

  function ChartHost({ Renderer, ds, defaultHighlight, compact, meta, src, className }) {
    const { controls, body } = Renderer({ ds, defaultHighlight, compact });
    return (
      <ResearchChartCard
        chartId={meta.id}
        kicker={meta.kicker}
        headline={meta.headlineParts}
        subtitle={meta.subtitle}
        sourceFootnote={meta.sourceFootnote}
        sourceUrl={src.url}
        methodologyNote={meta.methodologyNote}
        controls={controls}
        className={(compact ? "rc-card-compact " : "") + (className || "")}
      >
        {body}
      </ResearchChartCard>
    );
  }

  /* ---------- EditorialChart wrapper ---------- */
  function EditorialChart({ chartId, defaultHighlight, compact, className }) {
    const charts = window.RESEARCH_CHARTS || {};
    const datasets = window.RESEARCH_DATASETS || null;
    const sources = window.RESEARCH_SOURCES || {};
    const meta = charts[chartId];
    const Renderer = CHART_RENDERERS[chartId];

    if (!meta || !datasets || !Renderer) {
      return (
        <ResearchChartCard
          chartId={chartId || "unknown"}
          kicker="BENCHMARK DATA"
          headline="Chart data unavailable"
          subtitle="The requested research benchmark could not be loaded."
          className={className}
        >
          <div className="rc-fallback">Unknown or unavailable chart identifier: {String(chartId || "")}</div>
        </ResearchChartCard>
      );
    }

    const src = sources[meta.sourceKey] || {};
    return (
      <ChartHost
        key={meta.id}
        Renderer={Renderer}
        ds={datasets}
        defaultHighlight={defaultHighlight}
        compact={compact}
        meta={meta}
        src={src}
        className={className}
      />
    );
  }

  /* ---------- Accessible multi-chart tab explorer ---------- */
  function ResearchChartTabs({ tabs = [], defaultTab, eyebrow, heading, intro, className }) {
    const safeTabs = Array.isArray(tabs)
      ? tabs.filter((t) => t && typeof t === "object" && (t.id || t.chartId))
      : [];
    const initial = defaultTab && safeTabs.some((t) => (t.id || t.chartId) === defaultTab)
      ? defaultTab
      : (safeTabs[0] ? (safeTabs[0].id || safeTabs[0].chartId) : "");
    const [selected, setSelected] = useChState(initial);
    const btnRefs = useChRef([]);

    if (!safeTabs.length) return null;
    const current = safeTabs.find((t) => (t.id || t.chartId) === selected) || safeTabs[0];
    const currentId = current.id || current.chartId;

    const onKeyDown = (e, idx) => {
      let next = null;
      if (e.key === "ArrowRight") next = (idx + 1) % safeTabs.length;
      else if (e.key === "ArrowLeft") next = (idx - 1 + safeTabs.length) % safeTabs.length;
      else if (e.key === "Home") next = 0;
      else if (e.key === "End") next = safeTabs.length - 1;
      if (next !== null) {
        e.preventDefault();
        const t = safeTabs[next];
        setSelected(t.id || t.chartId);
        if (btnRefs.current[next]) btnRefs.current[next].focus();
      }
    };

    const OverlineComp = window.Overline;

    return (
      <div className={"rc-tabs-shell" + (className ? " " + className : "")}>
        {(eyebrow || heading || intro) && (
          <div className="rc-tabs-intro">
            {eyebrow && (OverlineComp ? <OverlineComp grad>{eyebrow}</OverlineComp> : <span className="overline-grad">{eyebrow}</span>)}
            {heading && <h2 className="rc-tabs-heading">{heading}</h2>}
            {intro && <p className="rc-tabs-sub">{intro}</p>}
          </div>
        )}
        <div className="rc-tabs" role="tablist" aria-label={heading || eyebrow || "Benchmark research charts"}>
          {safeTabs.map((t, idx) => {
            const tid = t.id || t.chartId;
            const isSel = tid === currentId;
            return (
              <button
                key={tid}
                ref={(el) => { btnRefs.current[idx] = el; }}
                type="button"
                role="tab"
                id={`rc-tab-${tid}`}
                aria-selected={isSel}
                aria-controls={`rc-panel-${tid}`}
                tabIndex={isSel ? 0 : -1}
                className={"rc-tab" + (isSel ? " is-active" : "")}
                onClick={() => setSelected(tid)}
                onKeyDown={(e) => onKeyDown(e, idx)}
              >
                {t.badge && <span className="rc-tab-badge">{t.badge}</span>}
                <span>{t.label}</span>
              </button>
            );
          })}
        </div>
        <div
          role="tabpanel"
          id={`rc-panel-${currentId}`}
          aria-labelledby={`rc-tab-${currentId}`}
          className="rc-tabpanel"
        >
          <EditorialChart
            key={current.chartId || current.id}
            chartId={current.chartId || current.id}
            defaultHighlight={current.defaultHighlight}
            compact={current.compact}
          />
          {current.caption && <p className="rc-tab-caption">{current.caption}</p>}
        </div>
      </div>
    );
  }

  Object.assign(window, { ResearchChartCard, EditorialChart, ResearchChartTabs });
})();
