// Guestmaker · CDP Analytics, DARK FUCHSIA
// Live CDP telemetry · ingestion, identity resolution, data health, bookings,
// PMS sources. Mirrors the dark visual language of crm-analytics.jsx but every
// metric is CDP-specific (no "messages" or "AI replies" here · this is data plane).

const { useState: cdaUseState, useEffect: cdaUseEffect, useRef: cdaUseRef, useMemo: cdaUseMemo } = React;

// ── palette ──
const CDA_BG       = "#120912";
const CDA_PANEL    = "#1a0f1a";
const CDA_PANEL_2  = "#22142a";
const CDA_RULE     = "#3a1f3a";
const CDA_RULE_S   = "#2a172a";

const CDA_INK      = "#f5e6f0";
const CDA_MUTED    = "#a896a6";
const CDA_DIM      = "#7a6a78";

const CDA_FUCHSIA  = "#ff4d97";
const CDA_F_DEEP   = "#d63d80";
const CDA_F_LIGHT  = "#ff8fbc";

const CDA_PINK     = "#ff7ab8";
const CDA_MAGENTA  = "#c235a3";
const CDA_ROSE     = "#ff5577";
const CDA_PLUM     = "#8a3a78";
const CDA_HOT      = "#ff2d7c";

const CDA_POS = "#5cd0a0";
const CDA_NEG = "#ff8068";
const CDA_AMBER = "#ffb35c";

// ── atoms ──
const CDAEyebrow = ({ children, color = CDA_FUCHSIA, style }) => (
  <div style={{
    fontFamily: "'JetBrains Mono', ui-monospace, monospace",
    fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
    color, fontWeight: 500, ...style,
  }}>{children}</div>
);
const CDAMono = ({ children, size = 11, color = CDA_MUTED, style }) => (
  <span style={{
    fontFamily: "'JetBrains Mono', ui-monospace, monospace",
    fontSize: size, color, letterSpacing: "0.04em", ...style,
  }}>{children}</span>
);

// ── live hooks ──
function cdaLiveNum(seed, jitter = 4, interval = 1800) {
  const [v, setV] = cdaUseState(seed);
  cdaUseEffect(() => {
    const t = setInterval(() => {
      setV(x => x + Math.floor(Math.random() * jitter * 2));
    }, interval);
    return () => clearInterval(t);
  }, [jitter, interval]);
  return v;
}
function cdaLiveFloat(seed, jitter = 0.05, interval = 2200, min = 0, max = 100, decimals = 1) {
  const [v, setV] = cdaUseState(seed);
  cdaUseEffect(() => {
    const t = setInterval(() => {
      setV(x => {
        const next = x + (Math.random() * jitter * 2 - jitter);
        return Math.max(min, Math.min(max, +next.toFixed(decimals)));
      });
    }, interval);
    return () => clearInterval(t);
  }, [jitter, interval, min, max, decimals]);
  return v;
}
function cdaHeartbeat(interval = 1000) {
  const [n, setN] = cdaUseState(0);
  cdaUseEffect(() => {
    const t = setInterval(() => setN(x => x + 1), interval);
    return () => clearInterval(t);
  }, [interval]);
  return n;
}

// ── chart helpers ──
function cdaBuildPath(data, w, h, pad = 4) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  return data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - pad - ((v - min) / (max - min || 1)) * (h - pad * 2);
    return [x, y];
  });
}
function CDASparkline({ data, color, height = 28, gid }) {
  const pts = cdaBuildPath(data, 100, height);
  const d = pts.map((p, i) => `${i === 0 ? "M" : "L"} ${p[0]} ${p[1]}`).join(" ");
  const area = `${d} L 100 ${height} L 0 ${height} Z`;
  const id = `cdas-${gid || color.replace("#","")}`;
  return (
    <svg width="100%" height={height} viewBox={`0 0 100 ${height}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.45" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${id})`} />
      <path d={d} fill="none" stroke={color} strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2" fill={color}>
        <animate attributeName="r" values="2;3.4;2" dur="1.6s" repeatCount="indefinite" />
      </circle>
    </svg>
  );
}
function CDAAreaChart({ data, color, height = 200, secondary, gid }) {
  const w = 100;
  const max = Math.max(...data, ...(secondary || []));
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = height - 24 - (v / (max || 1)) * (height - 40);
    return [x, y];
  });
  const d = pts.map((p, i) => `${i === 0 ? "M" : "L"} ${p[0]} ${p[1]}`).join(" ");
  const area = `${d} L ${w} ${height-24} L 0 ${height-24} Z`;
  const sec = secondary ? secondary.map((v, i) => {
    const x = (i / (secondary.length - 1)) * w;
    const y = height - 24 - (v / (max || 1)) * (height - 40);
    return [x, y];
  }) : null;
  const dSec = sec ? sec.map((p, i) => `${i === 0 ? "M" : "L"} ${p[0]} ${p[1]}`).join(" ") : null;
  const gradId = `cdaac-${gid || color.replace("#","")}`;
  return (
    <svg width="100%" height={height} viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" style={{ overflow: "visible" }}>
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.5" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map((g, i) => (
        <line key={i} x1="0" x2={w} y1={(height - 24) * (1 - g)} y2={(height - 24) * (1 - g)}
          stroke={CDA_RULE} strokeWidth="0.3" strokeDasharray="0.8 1" vectorEffect="non-scaling-stroke" />
      ))}
      <path d={area} fill={`url(#${gradId})`} />
      <path d={d} fill="none" stroke={color} strokeWidth="1.6"
        strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
      {dSec && (
        <path d={dSec} fill="none" stroke={CDA_F_LIGHT} strokeWidth="1.2" strokeDasharray="2 2"
          vectorEffect="non-scaling-stroke" opacity="0.6" />
      )}
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="0.8" fill={color} vectorEffect="non-scaling-stroke" />
    </svg>
  );
}
function CDADonut({ segments, size = 180, thickness = 22, label, sublabel }) {
  const r = (size - thickness) / 2;
  const cx = size / 2, cy = size / 2;
  const C = 2 * Math.PI * r;
  const total = segments.reduce((a, s) => a + s.value, 0);
  let off = 0;
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke={CDA_RULE_S} strokeWidth={thickness} />
        {segments.map((s, i) => {
          const len = (s.value / total) * C;
          const dasharray = `${len} ${C - len}`;
          const dashoffset = -off;
          off += len;
          return (
            <circle key={i} cx={cx} cy={cy} r={r}
              fill="none" stroke={s.color} strokeWidth={thickness}
              strokeDasharray={dasharray} strokeDashoffset={dashoffset}
              style={{ transition: "stroke-dasharray 0.6s ease",
                       filter: i === 0 ? `drop-shadow(0 0 6px ${s.color}90)` : "none" }} />
          );
        })}
      </svg>
      <div style={{
        position: "absolute", inset: 0,
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        textAlign: "center",
      }}>
        <div style={{
          fontFamily: "'Source Serif 4', Georgia, serif",
          fontSize: 28, fontWeight: 500, color: CDA_INK,
          letterSpacing: "-0.02em", lineHeight: 1,
        }}>{label}</div>
        <CDAMono size={10.5} color={CDA_DIM} style={{ marginTop: 4 }}>{sublabel}</CDAMono>
      </div>
    </div>
  );
}
function CDABarChart({ data, color = CDA_FUCHSIA, format = (v) => v.toLocaleString() }) {
  const max = Math.max(...data.map(d => d.value));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {data.map((d, i) => {
        const w = (d.value / max) * 100;
        const c = d.color || color;
        return (
          <div key={i} style={{ animation: `gm-fadein 0.35s ease ${i * 0.04}s both` }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
              <span style={{ fontSize: 12.5, color: CDA_INK, fontWeight: 500 }}>{d.label}</span>
              <CDAMono size={11} color={c} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{format(d.value)}</CDAMono>
            </div>
            <div style={{ height: 6, background: CDA_RULE_S, borderRadius: 3, overflow: "hidden" }}>
              <div style={{
                height: "100%", width: `${w}%`,
                background: `linear-gradient(90deg, ${c}, ${c}aa)`,
                boxShadow: `0 0 8px ${c}60`,
                transition: "width 0.6s cubic-bezier(.2,.8,.2,1)",
              }} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

function CDAKPI({ lbl, value, delta, deltaColor = CDA_POS, suffix = "", spark, color = CDA_FUCHSIA, prefix = "", gid, valueFmt, sublabel }) {
  const display = valueFmt
    ? valueFmt(value)
    : (typeof value === "number" ? value.toLocaleString("en-US") : value);
  return (
    <div style={{
      background: CDA_PANEL,
      border: `1px solid ${CDA_RULE_S}`,
      borderRadius: 10,
      padding: "16px 18px 14px",
      position: "relative",
      overflow: "hidden",
      transition: "all 0.25s ease",
    }}>
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0, height: 1,
        background: `linear-gradient(90deg, transparent, ${color}80, transparent)`,
      }} />
      <CDAMono size={10.5} color={CDA_DIM} style={{ letterSpacing: "0.14em", textTransform: "uppercase", display: "block" }}>{lbl}</CDAMono>
      <div style={{
        fontFamily: "'JetBrains Mono', ui-monospace, monospace",
        fontSize: 26, fontWeight: 500, color: CDA_INK,
        letterSpacing: "-0.02em", lineHeight: 1.1,
        marginTop: 6, marginBottom: 4,
        fontVariantNumeric: "tabular-nums",
      }}>
        {prefix}{display}{suffix}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: spark ? 10 : 0 }}>
        <span style={{
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 11, color: deltaColor, fontWeight: 600,
        }}>{delta}</span>
        <CDAMono size={10.5} color={CDA_DIM}>{sublabel || "vs last 30d"}</CDAMono>
      </div>
      {spark && (
        <div style={{ marginTop: 4, marginBottom: -4 }}>
          <CDASparkline data={spark} color={color} height={32} gid={gid} />
        </div>
      )}
    </div>
  );
}

function CDACard({ title, subtitle, action, children, padBody = true, style = {} }) {
  return (
    <div style={{
      background: CDA_PANEL,
      border: `1px solid ${CDA_RULE_S}`,
      borderRadius: 10,
      ...style,
    }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "flex-start",
        padding: "16px 18px 12px",
        borderBottom: `1px solid ${CDA_RULE_S}`,
      }}>
        <div>
          <div style={{
            fontFamily: "'Inter', system-ui, sans-serif",
            fontSize: 14, fontWeight: 600, color: CDA_INK,
            letterSpacing: "-0.005em",
          }}>{title}</div>
          {subtitle && <CDAMono size={10.5} color={CDA_DIM} style={{ display: "block", marginTop: 3, letterSpacing: "0.1em", textTransform: "uppercase" }}>{subtitle}</CDAMono>}
        </div>
        {action}
      </div>
      <div style={{ padding: padBody ? "18px" : 0 }}>{children}</div>
    </div>
  );
}

function CDALegend({ items }) {
  return (
    <div style={{ display: "flex", gap: 12 }}>
      {items.map((i, k) => (
        <div key={k} style={{ display: "flex", alignItems: "center", gap: 6 }}>
          {i.dashed ? (
            <span style={{ width: 12, height: 0, borderTop: `1.5px dashed ${i.c}` }} />
          ) : (
            <span style={{ width: 8, height: 8, borderRadius: 2, background: i.c }} />
          )}
          <CDAMono size={10.5} color={CDA_MUTED}>{i.lbl}</CDAMono>
        </div>
      ))}
    </div>
  );
}

// PMS sources
const CDA_PMS = {
  apaleo:    { lbl: "Apaleo",     c: CDA_FUCHSIA },
  opera:     { lbl: "Opera Cloud",c: CDA_PINK    },
  mews:      { lbl: "Mews",       c: CDA_HOT     },
  cloudbeds: { lbl: "Cloudbeds",  c: CDA_ROSE    },
  protel:    { lbl: "Protel",     c: CDA_MAGENTA },
};

// ─────────────────── LIVE INGESTION STREAM ───────────────────
// Rotating live feed of checkout events arriving from PMS systems
const CDA_GUEST_POOL = [
  ["Marco Lindqvist","ML"], ["Anneliese de Vries","AV"], ["Lorenzo Marchetti","LM"],
  ["Sora Park","SP"], ["Adaeze Okafor","AO"], ["Dieter Richter","DR"],
  ["Jasmine Kerr","JK"], ["Henrik Nakamura","HN"], ["Camila Ferreira","CF"],
  ["Tomáš Bianchi","TB"], ["Kasper Rasmussen","KR"], ["Elke Schmitt","ES"],
  ["Ronan Gallagher","RG"], ["Pedro Almeida","PA"], ["Iman Khoury","IK"],
  ["Yara Saleh","YS"], ["Noa Goldberg","NG"], ["Mei Hanssen","MH"],
  ["Felix Becker","FB"], ["Hanna Wolff","HW"], ["Mira Reddy","MR"],
  ["Aisha Bakr","AB"], ["Diego Alvarez","DA"], ["Anya Petrov","AP"],
];
const CDA_PROPS = ["Sunset Beach","Zafira Marina","Olea Cliffside","Casa Verde","Atlantic House","Aurora Pines","Lumia Bay"];
const CDA_PMSL = ["apaleo","opera","mews","cloudbeds","protel"];

function cdaMakeEvent(idx) {
  const g = CDA_GUEST_POOL[idx % CDA_GUEST_POOL.length];
  const pms = CDA_PMSL[Math.floor(Math.random() * CDA_PMSL.length)];
  const prop = CDA_PROPS[Math.floor(Math.random() * CDA_PROPS.length)];
  const nights = 1 + Math.floor(Math.random() * 8);
  const value = 80 + Math.floor(Math.random() * 320);
  // Resolution outcome: weighted random
  const r = Math.random();
  let outcome;
  if (r < 0.46) outcome = "merged";       // existing record extended
  else if (r < 0.74) outcome = "new";      // new golden record
  else if (r < 0.92) outcome = "promoted"; // moved CDP → CRM (gained email/phone)
  else outcome = "review";                  // flagged for review
  // Channels available
  const hasEmail = Math.random() > 0.22;
  const hasPhone = Math.random() > 0.30;
  return {
    id: `EV-${10000 + idx}`,
    guest: g[0], init: g[1],
    pms, prop, nights, value: value * nights,
    outcome, hasEmail, hasPhone,
    t: Date.now(),
  };
}

function CDALiveIngestionStream() {
  const [events, setEvents] = cdaUseState(() => {
    return Array.from({ length: 8 }, (_, i) => cdaMakeEvent(i));
  });
  const idxRef = cdaUseRef(8);
  cdaUseEffect(() => {
    const t = setInterval(() => {
      setEvents(prev => {
        const next = cdaMakeEvent(idxRef.current++);
        return [next, ...prev].slice(0, 8);
      });
    }, 1600 + Math.random() * 800);
    return () => clearInterval(t);
  }, []);

  const outcomeStyle = (o) => {
    if (o === "merged")   return { c: CDA_FUCHSIA, lbl: "MERGED",   dot: "◆" };
    if (o === "new")      return { c: CDA_PINK,    lbl: "NEW",      dot: "+" };
    if (o === "promoted") return { c: CDA_POS,     lbl: "→ CRM",    dot: "↑" };
    return { c: CDA_AMBER, lbl: "REVIEW", dot: "!" };
  };

  return (
    <CDACard
      title="Live ingestion stream"
      subtitle="CHECKOUT EVENTS · ALL PROPERTIES · UTC+2"
      padBody={false}
      action={
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{
            width: 7, height: 7, borderRadius: "50%",
            background: CDA_POS, animation: "gm-dot-pulse 1.4s infinite",
          }} />
          <CDAMono size={11} color={CDA_POS}>streaming</CDAMono>
        </div>
      }
    >
      <div>
        {/* header row */}
        <div style={{
          display: "grid", gridTemplateColumns: "70px 1fr 130px 100px 90px 100px",
          gap: 12, padding: "10px 18px",
          borderBottom: `1px solid ${CDA_RULE_S}`,
          background: CDA_PANEL_2,
        }}>
          {["Event", "Guest · property", "Source PMS", "Stay value", "Reach", "Outcome"].map((h, i) => (
            <CDAMono key={h} size={10} color={CDA_DIM} style={{
              letterSpacing: "0.1em", textTransform: "uppercase",
            }}>{h}</CDAMono>
          ))}
        </div>
        {events.map((e, i) => {
          const pms = CDA_PMS[e.pms];
          const out = outcomeStyle(e.outcome);
          return (
            <div key={e.id} style={{
              display: "grid", gridTemplateColumns: "70px 1fr 130px 100px 90px 100px",
              gap: 12, padding: "10px 18px",
              borderBottom: i < events.length - 1 ? `1px solid ${CDA_RULE_S}` : "none",
              alignItems: "center",
              animation: i === 0 ? "gm-row-in 0.4s ease" : "none",
              background: i === 0 ? `${out.c}08` : "transparent",
            }}>
              <CDAMono size={10.5} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums" }}>{e.id}</CDAMono>
              <div style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
                <span style={{
                  width: 22, height: 22, borderRadius: "50%",
                  background: out.c, color: "#fff",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 9, fontWeight: 600,
                  boxShadow: `0 0 8px ${out.c}55`, flexShrink: 0,
                }}>{e.init}</span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 12, color: CDA_INK, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{e.guest}</div>
                  <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 1 }}>
                    {e.prop} · {e.nights}n
                  </CDAMono>
                </div>
              </div>
              <span style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                padding: "2px 8px", borderRadius: 4,
                background: `${pms.c}18`, border: `1px solid ${pms.c}40`,
              }}>
                <span style={{ width: 5, height: 5, borderRadius: "50%", background: pms.c }} />
                <CDAMono size={10} color={pms.c} style={{ fontWeight: 600 }}>{pms.lbl}</CDAMono>
              </span>
              <CDAMono size={11.5} color={CDA_INK} style={{ fontVariantNumeric: "tabular-nums", fontWeight: 500 }}>€{e.value.toLocaleString()}</CDAMono>
              <div style={{ display: "inline-flex", gap: 5 }}>
                <span title="email" style={{
                  width: 18, height: 18, borderRadius: 4,
                  background: e.hasEmail ? `${CDA_POS}25` : CDA_RULE_S,
                  border: `1px solid ${e.hasEmail ? CDA_POS : CDA_RULE}`,
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 9, fontWeight: 700,
                  color: e.hasEmail ? CDA_POS : CDA_DIM,
                }}>@</span>
                <span title="phone" style={{
                  width: 18, height: 18, borderRadius: 4,
                  background: e.hasPhone ? `${CDA_POS}25` : CDA_RULE_S,
                  border: `1px solid ${e.hasPhone ? CDA_POS : CDA_RULE}`,
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 9, fontWeight: 700,
                  color: e.hasPhone ? CDA_POS : CDA_DIM,
                }}>☎</span>
              </div>
              <span style={{
                display: "inline-flex", alignItems: "center", gap: 5,
                padding: "3px 8px", borderRadius: 999,
                background: `${out.c}22`, border: `1px solid ${out.c}50`,
                color: out.c,
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 10, fontWeight: 600, letterSpacing: "0.08em",
              }}>
                <span>{out.dot}</span>
                <span>{out.lbl}</span>
              </span>
            </div>
          );
        })}
      </div>
    </CDACard>
  );
}

// ─────────────────── OVERVIEW TAB ───────────────────
function CDAOverviewTab() {
  const guests   = cdaLiveNum(184_320, 7, 2200);
  const bookings = cdaLiveNum(287_640, 12, 1700);
  const resRate  = cdaLiveFloat(94.8, 0.05, 2500, 90, 99, 1);
  const latency  = cdaLiveFloat(4.2, 0.18, 1800, 2.0, 8.0, 1);

  const sparks = {
    guests:   [120,124,128,132,136,141,146,151,157,162,168,173,178,184,189,194],
    bookings: [180,196,212,228,244,261,278,296,314,332,350,368,386,404,422,440],
    res:      [88,89,90,90,91,91,92,93,93,93,94,94,94,94,94,94],
    lat:      [9,8,7,7,6,6,5,5,5,5,4,4,4,4,4,4],
  };

  // Golden records over time
  const recordsGrowth = [12,18,26,37,52,72,98,128,162,201,244,292,344,400,460,524,592,664,740,820,904,992,1083,1178];
  const bookingsGrowth = recordsGrowth.map(v => v * 1.55);

  // Source mix (PMS systems)
  const sourceMix = [
    { label: "Apaleo",      value: 84320, color: CDA_FUCHSIA },
    { label: "Opera Cloud", value: 71240, color: CDA_PINK    },
    { label: "Mews",        value: 56480, color: CDA_HOT     },
    { label: "Cloudbeds",   value: 42180, color: CDA_ROSE    },
    { label: "Protel",      value: 33420, color: CDA_MAGENTA },
  ];

  // Reach distribution
  const reachSplit = [
    { color: CDA_FUCHSIA, value: 142840, lbl: "Email + phone",  pct: 77.6 },
    { color: CDA_PINK,    value:  18720, lbl: "Email only",     pct: 10.2 },
    { color: CDA_MAGENTA, value:  13460, lbl: "Phone only",     pct:  7.3 },
    { color: CDA_PLUM,    value:   9300, lbl: "No reach (CDP)", pct:  5.0 },
  ];

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <CDAKPI lbl="Golden records" value={guests} delta="↑ 8.6%" spark={sparks.guests} color={CDA_FUCHSIA} gid="cdk1" />
        <CDAKPI lbl="Bookings indexed" value={bookings} delta="↑ 12.4%" spark={sparks.bookings} color={CDA_PINK} gid="cdk2" />
        <CDAKPI lbl="Resolution rate" value={resRate} suffix="%" valueFmt={v => v.toFixed(1)} delta="↑ 1.8 pts" spark={sparks.res} color={CDA_MAGENTA} gid="cdk3" />
        <CDAKPI lbl="Ingestion latency" value={latency} suffix="s" valueFmt={v => v.toFixed(1)} delta="↓ 56%" deltaColor={CDA_POS} spark={sparks.lat} color={CDA_HOT} gid="cdk4" sublabel="p95 · last hour" />
      </div>

      <CDALiveIngestionStream />

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18 }}>
        <CDACard
          title="Golden records · 24-month build"
          subtitle="POST-RESOLUTION · UNIQUE GUESTS VS BOOKINGS"
          action={<CDALegend items={[{c: CDA_FUCHSIA, lbl: "Records"}, {c: CDA_F_LIGHT, lbl: "Bookings", dashed: true}]} />}
        >
          <div style={{ height: 220, position: "relative" }}>
            <CDAAreaChart data={recordsGrowth} color={CDA_FUCHSIA} height={220} secondary={bookingsGrowth} gid="cdgrow" />
          </div>
          <div style={{
            display: "flex", justifyContent: "space-between",
            marginTop: 8, fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 10, color: CDA_DIM, letterSpacing: "0.04em",
          }}>
            <span>2024 Q2</span><span>Q3</span><span>Q4</span>
            <span>2025 Q1</span><span>Q2</span><span>Q3</span><span>Q4</span>
            <span>2026 Q1</span>
          </div>
        </CDACard>

        <CDACard title="Reachability mix" subtitle="ALL CDP RECORDS · LIVE">
          <div style={{ display: "flex", justifyContent: "center" }}>
            <CDADonut
              segments={reachSplit.map(t => ({ color: t.color, value: t.value }))}
              size={180} thickness={20}
              label="184k"
              sublabel="records"
            />
          </div>
          <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 6 }}>
            {reachSplit.map(r => (
              <div key={r.lbl} style={{
                display: "flex", justifyContent: "space-between", alignItems: "center",
                padding: "4px 0", borderBottom: `1px solid ${CDA_RULE_S}`,
              }}>
                <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: r.color }} />
                  <span style={{ fontSize: 12, color: CDA_MUTED }}>{r.lbl}</span>
                </span>
                <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <CDAMono size={10.5} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums" }}>{(r.value/1000).toFixed(1)}k</CDAMono>
                  <CDAMono size={11.5} color={r.color} style={{ fontWeight: 600 }}>{r.pct}%</CDAMono>
                </span>
              </div>
            ))}
          </div>
        </CDACard>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <CDACard title="Bookings by source PMS" subtitle="LAST 30 DAYS · NEW BOOKINGS INGESTED">
          <CDABarChart data={sourceMix} format={v => v >= 1e3 ? `${(v/1e3).toFixed(1)}k` : v.toLocaleString()} />
          <div style={{ marginTop: 14, paddingTop: 12, borderTop: `1px solid ${CDA_RULE_S}`, display: "flex", justifyContent: "space-between" }}>
            <CDAMono size={10.5} color={CDA_DIM}>5 of 5 PMS connectors healthy</CDAMono>
            <CDAMono size={10.5} color={CDA_POS} style={{ fontWeight: 600 }}>● all green</CDAMono>
          </div>
        </CDACard>

        <CDACard title="Resolution funnel · today" subtitle="DETERMINISTIC → FUZZY → AI" padBody={false}>
          <CDAResolutionFunnel />
        </CDACard>
      </div>
    </div>
  );
}

function CDAResolutionFunnel() {
  const stages = [
    { lbl: "Raw bookings ingested",    v: 8420, c: CDA_PINK,    pct: 100 },
    { lbl: "Deterministic match",      v: 6940, c: CDA_FUCHSIA, pct: 82.4 },
    { lbl: "Fuzzy similarity match",   v:  984, c: CDA_MAGENTA, pct: 11.7 },
    { lbl: "AI semantic match",        v:  342, c: CDA_HOT,     pct:  4.1 },
    { lbl: "Held for human review",    v:  154, c: CDA_AMBER,   pct:  1.8 },
  ];
  return (
    <div style={{ padding: 18 }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {stages.map((s, i) => (
          <div key={i} style={{ animation: `gm-fadein 0.3s ease ${i * 0.05}s both` }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
              <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <CDAMono size={10} color={CDA_DIM} style={{ width: 18 }}>0{i+1}</CDAMono>
                <span style={{ fontSize: 12.5, color: CDA_INK, fontWeight: 500 }}>{s.lbl}</span>
              </span>
              <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <CDAMono size={11} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums" }}>{s.v.toLocaleString()}</CDAMono>
                <CDAMono size={11} color={s.c} style={{ fontWeight: 600, minWidth: 42, textAlign: "right" }}>{s.pct}%</CDAMono>
              </span>
            </div>
            <div style={{ height: 8, background: CDA_RULE_S, borderRadius: 4, overflow: "hidden", position: "relative" }}>
              <div style={{
                height: "100%", width: `${s.pct}%`,
                background: `linear-gradient(90deg, ${s.c}, ${s.c}66)`,
                boxShadow: `0 0 8px ${s.c}80`,
                transition: "width 0.6s cubic-bezier(.2,.8,.2,1)",
                position: "relative", overflow: "hidden",
              }}>
                <span style={{
                  position: "absolute", top: 0, left: 0, bottom: 0,
                  width: "30%",
                  background: `linear-gradient(90deg, transparent, ${s.c}80, transparent)`,
                  animation: "gm-bar-scan 2.4s linear infinite",
                }} />
              </div>
            </div>
          </div>
        ))}
      </div>
      <div style={{
        marginTop: 14, paddingTop: 12, borderTop: `1px solid ${CDA_RULE_S}`,
        display: "flex", justifyContent: "space-between", alignItems: "center",
      }}>
        <CDAMono size={10.5} color={CDA_DIM}>throughput · 5.8/sec</CDAMono>
        <CDAMono size={10.5} color={CDA_F_LIGHT} style={{ fontWeight: 600 }}>98.2% auto-resolved</CDAMono>
      </div>
    </div>
  );
}

// ─────────────────── IDENTITY TAB ───────────────────
function CDAIdentityTab() {
  const mergesToday = cdaLiveNum(1480, 3, 1600);
  const dedupRatio  = cdaLiveFloat(2.84, 0.02, 2400, 2.5, 3.5, 2);
  const reviewQ     = cdaLiveNum(34, 1, 3000);
  const aiConf      = cdaLiveFloat(96.4, 0.06, 2200, 92, 99, 1);

  const sparks = {
    m: [120,136,148,160,176,188,204,220,238,256,278,298,322,348,376,406],
    d: [2.3, 2.4, 2.5, 2.55, 2.6, 2.65, 2.7, 2.72, 2.76, 2.78, 2.80, 2.82, 2.83, 2.84, 2.84, 2.84],
    r: [62, 58, 51, 46, 43, 41, 38, 36, 34, 35, 34, 33, 32, 33, 34, 34],
    a: [92, 93, 93, 94, 94, 95, 95, 95, 96, 96, 96, 96, 96, 96, 96, 96],
  };

  // Top merge patterns
  const patterns = [
    { label: "Same name + DOB + nationality", value: 38420, color: CDA_FUCHSIA },
    { label: "Same email · case insensitive", value: 28240, color: CDA_PINK    },
    { label: "Same phone · E.164 normalized", value: 21680, color: CDA_HOT     },
    { label: "Fuzzy name + same email domain",value: 12480, color: CDA_ROSE    },
    { label: "Loyalty ID match",              value:  8420, color: CDA_MAGENTA },
    { label: "AI semantic · address+nights",  value:  3940, color: CDA_AMBER   },
  ];

  // Live resolution events
  const liveEvents = [
    { who: "M. Lindqvist",   from: "BKG-87421", to: "GR-00128", conf: 0.98, kind: "deterministic", t: "0:04" },
    { who: "A. de Vries",    from: "BKG-87420", to: "GR-04812", conf: 0.94, kind: "fuzzy",         t: "0:11" },
    { who: "L. Marchetti",   from: "BKG-87419", to: "NEW",      conf: 1.0,  kind: "new",           t: "0:18" },
    { who: "S. Park",        from: "BKG-87418", to: "GR-07221", conf: 0.91, kind: "fuzzy",         t: "0:24" },
    { who: "A. Okafor",      from: "BKG-87417", to: "GR-02019", conf: 0.99, kind: "deterministic", t: "0:31" },
    { who: "J. Kerr",        from: "BKG-87416", to: "GR-12480", conf: 0.87, kind: "ai",            t: "0:38" },
    { who: "D. Richter",     from: "BKG-87415", to: "REVIEW",   conf: 0.66, kind: "review",        t: "0:44" },
  ];
  const kindStyle = (k) => ({
    deterministic: { c: CDA_FUCHSIA, lbl: "DET" },
    fuzzy:         { c: CDA_PINK,    lbl: "FUZZY" },
    ai:            { c: CDA_HOT,     lbl: "AI" },
    new:           { c: CDA_POS,     lbl: "NEW" },
    review:        { c: CDA_AMBER,   lbl: "REVIEW" },
  })[k];

  // Heat by hour - merges
  const mergeHeat = (() => {
    const days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
    return days.map((d, di) => ({
      day: d,
      cells: Array.from({ length: 24 }, (_, h) => {
        const base = 28 + Math.sin((h - 4) / 24 * Math.PI * 2) * 18;
        const checkout = h >= 9 && h <= 12 ? 22 : 0;
        const evening = h >= 19 && h <= 22 ? 14 : 0;
        const rand = Math.sin(di * 7 + h * 3.1) * 6;
        return Math.max(0, Math.round(base + checkout + evening + rand));
      }),
    }));
  })();
  const heatMax = Math.max(...mergeHeat.flatMap(d => d.cells));

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <CDAKPI lbl="Merges · today" value={mergesToday} delta="↑ 14%" spark={sparks.m} color={CDA_FUCHSIA} gid="ciden1" sublabel="vs avg day" />
        <CDAKPI lbl="Dedup ratio" value={dedupRatio} suffix=":1" valueFmt={v => v.toFixed(2)} delta="↑ 0.18" spark={sparks.d} color={CDA_PINK} gid="ciden2" sublabel="bookings per guest" />
        <CDAKPI lbl="Review queue" value={reviewQ} delta="↓ 42%" deltaColor={CDA_POS} spark={sparks.r} color={CDA_AMBER} gid="ciden3" sublabel="needs human" />
        <CDAKPI lbl="AI confidence" value={aiConf} suffix="%" valueFmt={v => v.toFixed(1)} delta="↑ 3.2 pts" spark={sparks.a} color={CDA_HOT} gid="ciden4" sublabel="avg · auto-merged" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 18 }}>
        <CDACard title="Top merge patterns" subtitle="HOW RECORDS WERE FUSED · 30D">
          <CDABarChart data={patterns} format={v => `${(v/1e3).toFixed(1)}k`} />
        </CDACard>

        <CDACard title="Live resolution stream" subtitle="REAL-TIME · LAST 60 SECONDS" padBody={false}
          action={
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 7, height: 7, borderRadius: "50%", background: CDA_POS, animation: "gm-dot-pulse 1.4s infinite" }} />
              <CDAMono size={11} color={CDA_POS}>live</CDAMono>
            </div>
          }>
          <div>
            {liveEvents.map((m, i) => {
              const k = kindStyle(m.kind);
              return (
                <div key={i} style={{
                  display: "grid", gridTemplateColumns: "1fr 100px 80px 90px 60px",
                  alignItems: "center", gap: 10,
                  padding: "9px 18px",
                  borderBottom: i < liveEvents.length - 1 ? `1px solid ${CDA_RULE_S}` : "none",
                  animation: `gm-fadein 0.3s ease ${i * 0.04}s both`,
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
                    <span style={{
                      width: 22, height: 22, borderRadius: "50%",
                      background: k.c, color: "#fff",
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                      fontSize: 9, fontWeight: 600,
                      boxShadow: `0 0 8px ${k.c}55`,
                    }}>{m.who.split(" ")[0][0]}{m.who.split(" ")[1][0]}</span>
                    <span style={{ fontSize: 12, color: CDA_INK, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.who}</span>
                  </div>
                  <CDAMono size={10.5} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums" }}>{m.from}</CDAMono>
                  <CDAMono size={10.5} color={m.to === "NEW" || m.to === "REVIEW" ? k.c : CDA_F_LIGHT} style={{ fontVariantNumeric: "tabular-nums", fontWeight: 600 }}>→ {m.to}</CDAMono>
                  <span style={{
                    padding: "2px 8px", borderRadius: 4,
                    background: `${k.c}22`, border: `1px solid ${k.c}50`,
                    color: k.c,
                    fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                    fontSize: 9.5, fontWeight: 600, letterSpacing: "0.1em",
                    textAlign: "center",
                  }}>{k.lbl}</span>
                  <CDAMono size={10.5} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums", textAlign: "right" }}>{m.t}</CDAMono>
                </div>
              );
            })}
          </div>
        </CDACard>
      </div>

      <CDACard title="Merge activity heatmap" subtitle="MERGES · DAY × HOUR · UTC+2 · LAST 7 DAYS">
        <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
          <div style={{ display: "grid", gridTemplateColumns: "32px repeat(24, 1fr)", gap: 2, marginBottom: 4 }}>
            <span />
            {Array.from({ length: 24 }, (_, h) => (
              <CDAMono key={h} size={8.5} color={CDA_DIM} style={{ textAlign: "center" }}>
                {h % 6 === 0 ? `${h}` : ""}
              </CDAMono>
            ))}
          </div>
          {mergeHeat.map(d => (
            <div key={d.day} style={{ display: "grid", gridTemplateColumns: "32px repeat(24, 1fr)", gap: 2 }}>
              <CDAMono size={10} color={CDA_MUTED} style={{ alignSelf: "center" }}>{d.day}</CDAMono>
              {d.cells.map((v, h) => {
                const op = v / heatMax;
                return (
                  <div key={h} title={`${d.day} ${h}:00 · ${v} merges`} style={{
                    height: 16, borderRadius: 2,
                    background: `rgba(255, 77, 151, ${op})`,
                    boxShadow: op > 0.7 ? `0 0 6px rgba(255, 77, 151, ${op * 0.6})` : "none",
                    transition: "background 0.18s ease",
                    cursor: "pointer",
                  }} />
                );
              })}
            </div>
          ))}
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 8 }}>
            <CDAMono size={9.5} color={CDA_DIM}>low</CDAMono>
            {[0.1, 0.25, 0.45, 0.7, 0.95].map((op, i) => (
              <span key={i} style={{ width: 14, height: 8, background: `rgba(255, 77, 151, ${op})`, borderRadius: 1 }} />
            ))}
            <CDAMono size={9.5} color={CDA_DIM}>high</CDAMono>
            <span style={{ flex: 1 }} />
            <CDAMono size={10.5} color={CDA_F_LIGHT}>peak · Mon 11:00–12:00 (PMS overnight push)</CDAMono>
          </div>
        </div>
      </CDACard>
    </div>
  );
}

// ─────────────────── DATA HEALTH TAB ───────────────────
function CDADataHealthTab() {
  // Field completeness · what % of records have each attribute populated
  const fields = [
    { name: "Full name",        pct: 100.0, n: 184320, c: CDA_FUCHSIA },
    { name: "Email · verified", pct:  86.7, n: 159820, c: CDA_PINK    },
    { name: "Phone · E.164",    pct:  78.4, n: 144510, c: CDA_HOT     },
    { name: "Date of birth",    pct:  72.1, n: 132950, c: CDA_ROSE    },
    { name: "Nationality",      pct:  68.3, n: 125940, c: CDA_MAGENTA },
    { name: "Marketing consent",pct:  54.2, n:  99940, c: CDA_PLUM    },
    { name: "Loyalty ID",       pct:  18.6, n:  34320, c: CDA_AMBER   },
    { name: "Address · full",   pct:  61.8, n: 113920, c: CDA_F_LIGHT },
  ];

  // Reach gate split (CRM-ready vs Held in CDP)
  const gateSplit = cdaLiveFloat(77.6, 0.04, 2400, 75, 80, 1);
  const crmReady = Math.round(184320 * (gateSplit / 100));
  const heldCdp  = 184320 - crmReady;

  // Data freshness · last sync per property
  const freshness = [
    { prop: "Sunset Beach",   pms: "apaleo",    lag: "3 s",   status: "ok",   live: true },
    { prop: "Zafira Marina",  pms: "opera",     lag: "8 s",   status: "ok",   live: true },
    { prop: "Olea Cliffside", pms: "mews",      lag: "12 s",  status: "ok",   live: true },
    { prop: "Casa Verde",     pms: "cloudbeds", lag: "1.4 m", status: "warn", live: false },
    { prop: "Atlantic House", pms: "apaleo",    lag: "6 s",   status: "ok",   live: true },
    { prop: "Aurora Pines",   pms: "protel",    lag: "9 s",   status: "ok",   live: true },
    { prop: "Lumia Bay",      pms: "mews",      lag: "11 s",  status: "ok",   live: true },
  ];

  // Validation issues breakdown
  const issues = [
    { name: "Invalid email format",      n: 1240, c: CDA_HOT },
    { name: "Phone failed E.164",        n:  840, c: CDA_PINK },
    { name: "Conflicting DOB across PMS",n:  316, c: CDA_AMBER },
    { name: "Future check-in date",      n:   84, c: CDA_ROSE },
    { name: "Duplicate loyalty ID",      n:   42, c: CDA_MAGENTA },
  ];

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      {/* gate split · big readout */}
      <CDACard title="Reach gate · live split" subtitle="HAS EMAIL ∨ PHONE → CRM · OTHERWISE → HELD IN CDP">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 22, alignItems: "center" }}>
          {/* numeric readout */}
          <div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 18 }}>
              <span style={{
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 52, fontWeight: 500, color: CDA_FUCHSIA,
                letterSpacing: "-0.025em", lineHeight: 1,
                fontVariantNumeric: "tabular-nums",
                textShadow: `0 0 24px ${CDA_FUCHSIA}66`,
              }}>{gateSplit.toFixed(1)}%</span>
              <CDAMono size={12} color={CDA_F_LIGHT}>auto-promoted to CRM</CDAMono>
            </div>
            <div style={{
              display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10,
            }}>
              <div style={{
                background: CDA_PANEL_2, border: `1px solid ${CDA_FUCHSIA}40`,
                borderRadius: 8, padding: "12px 14px",
              }}>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.12em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>CRM-ready</CDAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 22, fontWeight: 500, color: CDA_FUCHSIA,
                  fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em", lineHeight: 1,
                }}>{crmReady.toLocaleString()}</div>
                <CDAMono size={10} color={CDA_POS} style={{ display: "block", marginTop: 4, fontWeight: 600 }}>+184 today → CRM</CDAMono>
              </div>
              <div style={{
                background: CDA_PANEL_2, border: `1px solid ${CDA_RULE}`,
                borderRadius: 8, padding: "12px 14px",
              }}>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.12em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Held · CDP-only</CDAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 22, fontWeight: 500, color: CDA_INK,
                  fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em", lineHeight: 1,
                }}>{heldCdp.toLocaleString()}</div>
                <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 4 }}>awaiting next booking</CDAMono>
              </div>
            </div>
          </div>
          {/* visual bar */}
          <div>
            <div style={{ height: 56, display: "flex", borderRadius: 8, overflow: "hidden", border: `1px solid ${CDA_RULE}` }}>
              <div style={{
                width: `${gateSplit}%`,
                background: `linear-gradient(135deg, ${CDA_FUCHSIA}, ${CDA_F_DEEP})`,
                boxShadow: `inset 0 0 24px ${CDA_FUCHSIA}55`,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: "#fff",
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 11, fontWeight: 600, letterSpacing: "0.14em",
                transition: "width 0.6s ease",
              }}>PROMOTED · MARKETABLE</div>
              <div style={{
                width: `${100 - gateSplit}%`,
                background: CDA_PANEL_2,
                borderLeft: `1px dashed ${CDA_DIM}`,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: CDA_DIM,
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 10.5, fontWeight: 600, letterSpacing: "0.14em",
              }}>HELD</div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
              <CDAMono size={10} color={CDA_DIM}>0</CDAMono>
              <CDAMono size={10} color={CDA_DIM}>SLA target · {">"} 75%</CDAMono>
              <CDAMono size={10} color={CDA_DIM}>184k</CDAMono>
            </div>
            <div style={{
              marginTop: 14, padding: "10px 12px",
              background: CDA_PANEL_2, border: `1px solid ${CDA_RULE_S}`, borderRadius: 6,
              display: "flex", alignItems: "center", gap: 9,
            }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: CDA_POS, animation: "gm-dot-pulse 1.6s infinite" }} />
              <CDAMono size={11} color={CDA_INK}>+38 records crossed the gate in the last hour</CDAMono>
            </div>
          </div>
        </div>
      </CDACard>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
        <CDACard title="Field completeness" subtitle="POPULATED ATTRIBUTES ACROSS ALL RECORDS">
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {fields.map((f, i) => (
              <div key={f.name} style={{ animation: `gm-fadein 0.3s ease ${i * 0.04}s both` }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
                  <span style={{ fontSize: 12.5, color: CDA_INK, fontWeight: 500 }}>{f.name}</span>
                  <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <CDAMono size={10.5} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums" }}>{(f.n/1e3).toFixed(0)}k</CDAMono>
                    <CDAMono size={11.5} color={f.c} style={{ fontWeight: 600, minWidth: 50, textAlign: "right" }}>{f.pct.toFixed(1)}%</CDAMono>
                  </span>
                </div>
                <div style={{ height: 8, background: CDA_RULE_S, borderRadius: 4, overflow: "hidden" }}>
                  <div style={{
                    height: "100%", width: `${f.pct}%`,
                    background: `linear-gradient(90deg, ${f.c}, ${f.c}aa)`,
                    boxShadow: `0 0 6px ${f.c}50`,
                    transition: "width 0.6s ease",
                  }} />
                </div>
              </div>
            ))}
          </div>
        </CDACard>

        <CDACard title="Validation issues" subtitle="FLAGGED · LAST 7 DAYS">
          <CDABarChart data={issues.map(i => ({ label: i.name, value: i.n, color: i.c }))} format={v => v.toLocaleString()} />
          <div style={{
            marginTop: 14, padding: "10px 12px",
            background: CDA_PANEL_2, border: `1px solid ${CDA_AMBER}30`, borderRadius: 6,
            display: "flex", alignItems: "center", gap: 9,
          }}>
            <span style={{
              width: 18, height: 18, borderRadius: "50%",
              background: `${CDA_AMBER}25`, border: `1px solid ${CDA_AMBER}55`,
              color: CDA_AMBER, display: "inline-flex", alignItems: "center", justifyContent: "center",
              fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: 11, fontWeight: 700,
            }}>!</span>
            <CDAMono size={10.5} color={CDA_INK}>2,522 records · 1.37% of base · all surfaced to data steward</CDAMono>
          </div>
        </CDACard>
      </div>

      <CDACard title="Per-property data freshness" subtitle="LAST SYNC LAG · PMS → CDP · LIVE" padBody={false}>
        <div>
          <div style={{
            display: "grid", gridTemplateColumns: "1fr 130px 100px 80px 1fr",
            gap: 14, padding: "10px 18px",
            borderBottom: `1px solid ${CDA_RULE_S}`,
            background: CDA_PANEL_2,
          }}>
            {["Property", "Source PMS", "Sync lag", "Status", "Live heartbeat"].map(h => (
              <CDAMono key={h} size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase" }}>{h}</CDAMono>
            ))}
          </div>
          {freshness.map((f, i) => {
            const pms = CDA_PMS[f.pms];
            const ok = f.status === "ok";
            return (
              <div key={f.prop} style={{
                display: "grid", gridTemplateColumns: "1fr 130px 100px 80px 1fr",
                gap: 14, padding: "11px 18px",
                borderBottom: i < freshness.length - 1 ? `1px solid ${CDA_RULE_S}` : "none",
                alignItems: "center",
                animation: `gm-fadein 0.3s ease ${i * 0.03}s both`,
              }}>
                <span style={{ fontSize: 13, color: CDA_INK, fontWeight: 500 }}>{f.prop}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: pms.c }} />
                  <CDAMono size={11} color={pms.c} style={{ fontWeight: 600 }}>{pms.lbl}</CDAMono>
                </span>
                <CDAMono size={12} color={CDA_INK} style={{ fontVariantNumeric: "tabular-nums", fontWeight: 500 }}>{f.lag}</CDAMono>
                <span style={{
                  padding: "2px 9px", borderRadius: 999,
                  background: ok ? `${CDA_POS}20` : `${CDA_AMBER}20`,
                  border: `1px solid ${ok ? CDA_POS : CDA_AMBER}55`,
                  color: ok ? CDA_POS : CDA_AMBER,
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 9.5, fontWeight: 600, letterSpacing: "0.1em",
                  textAlign: "center", justifySelf: "start",
                }}>{ok ? "OK" : "DELAYED"}</span>
                <CDAHeartbeatBar live={f.live} color={ok ? CDA_POS : CDA_AMBER} />
              </div>
            );
          })}
        </div>
      </CDACard>
    </div>
  );
}

function CDAHeartbeatBar({ live, color }) {
  // 24 cells, last few pulsing
  return (
    <div style={{ display: "flex", gap: 2, alignItems: "center" }}>
      {Array.from({ length: 24 }, (_, i) => {
        const active = i >= 18;
        return (
          <span key={i} style={{
            width: 4, height: i % 3 === 0 ? 14 : 10,
            borderRadius: 1,
            background: active ? color : CDA_RULE_S,
            opacity: active ? 0.85 + (i - 18) * 0.025 : 0.45,
            animation: live && i >= 22 ? `gm-dot-pulse 1.2s infinite ${(i - 22) * 0.15}s` : "none",
          }} />
        );
      })}
    </div>
  );
}

// ─────────────────── BOOKINGS TAB ───────────────────
function CDABookingsTab() {
  const adr = cdaLiveFloat(284, 0.5, 2400, 240, 340, 0);
  const los = cdaLiveFloat(3.2, 0.02, 2200, 2.5, 4.2, 1);
  const occ = cdaLiveFloat(78.4, 0.15, 2600, 60, 92, 1);
  const cancel = cdaLiveFloat(8.2, 0.06, 2400, 5, 14, 1);

  // Booking volume per month
  const months = ["Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May"];
  const ny = [4200, 5800, 7900, 8400, 6200, 4800, 7800, 5600, 4800, 5400, 6800, 8200];
  const ly = [3800, 5100, 7100, 7800, 5600, 4200, 7200, 5100, 4400, 5000, 6100, 7500];

  // RFM segmentation
  const rfm = [
    { name: "Champions",     count: 8420,  c: CDA_FUCHSIA, descr: "high R/F/M · likely VIP" },
    { name: "Loyal",         count: 18240, c: CDA_PINK,    descr: "recent + frequent" },
    { name: "Potential",     count: 26480, c: CDA_HOT,     descr: "recent · low frequency" },
    { name: "At-risk",       count: 14820, c: CDA_AMBER,   descr: "missed last cycle" },
    { name: "Hibernating",   count: 32140, c: CDA_PLUM,    descr: "12+ months no stay" },
    { name: "New",           count: 22680, c: CDA_F_LIGHT, descr: "first booking · 60d" },
  ];

  // Top markets
  const markets = [
    { name: "🇩🇪 Germany",     pct: 28.4, n: 52340, c: CDA_FUCHSIA },
    { name: "🇬🇧 UK",          pct: 18.2, n: 33540, c: CDA_PINK },
    { name: "🇫🇷 France",      pct: 12.6, n: 23220, c: CDA_HOT },
    { name: "🇮🇹 Italy",       pct:  9.8, n: 18060, c: CDA_ROSE },
    { name: "🇳🇱 Netherlands", pct:  7.4, n: 13640, c: CDA_MAGENTA },
    { name: "🇺🇸 USA",         pct:  6.8, n: 12520, c: CDA_PLUM },
    { name: "Other · 38 markets", pct: 16.8, n: 31000, c: CDA_DIM },
  ];

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <CDAKPI lbl="ADR · trailing 30d" value={adr} prefix="€" valueFmt={v => Math.round(v).toLocaleString()} delta="↑ 8.4%" color={CDA_FUCHSIA} sublabel="avg daily rate" />
        <CDAKPI lbl="Length of stay" value={los} suffix=" nights" valueFmt={v => v.toFixed(1)} delta="↑ 0.3" color={CDA_PINK} sublabel="median · 30d" />
        <CDAKPI lbl="Occupancy" value={occ} suffix="%" valueFmt={v => v.toFixed(1)} delta="↑ 4.2 pts" color={CDA_MAGENTA} sublabel="7 properties" />
        <CDAKPI lbl="Cancel rate" value={cancel} suffix="%" valueFmt={v => v.toFixed(1)} delta="↓ 1.4 pts" deltaColor={CDA_POS} color={CDA_AMBER} sublabel="industry · 12.8%" />
      </div>

      <CDACard title="Booking volume · this year vs last" subtitle="MONTHLY · CONFIRMED CHECKOUTS · GROUP-WIDE"
        action={<CDALegend items={[{c: CDA_FUCHSIA, lbl: "This year"}, {c: CDA_F_LIGHT, lbl: "Last year", dashed: true}]} />}>
        <div style={{ height: 200 }}>
          <CDAAreaChart data={ny} color={CDA_FUCHSIA} secondary={ly} height={200} gid="cdayoy" />
        </div>
        <div style={{
          display: "grid", gridTemplateColumns: `repeat(${months.length}, 1fr)`,
          marginTop: 8, fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 10, color: CDA_DIM, letterSpacing: "0.04em",
        }}>
          {months.map(m => <span key={m} style={{ textAlign: "center" }}>{m}</span>)}
        </div>
      </CDACard>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <CDACard title="RFM segmentation" subtitle="RECENCY · FREQUENCY · MONETARY · ALL GUESTS">
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {rfm.map((r, i) => (
              <div key={r.name} style={{
                display: "grid", gridTemplateColumns: "16px 1fr auto auto",
                alignItems: "center", gap: 10,
                padding: "8px 10px",
                background: CDA_PANEL_2, border: `1px solid ${CDA_RULE_S}`,
                borderRadius: 6,
                animation: `gm-fadein 0.3s ease ${i * 0.04}s both`,
              }}>
                <span style={{ width: 10, height: 10, borderRadius: 2, background: r.c, boxShadow: `0 0 6px ${r.c}80` }} />
                <div>
                  <div style={{ fontSize: 12.5, color: CDA_INK, fontWeight: 500 }}>{r.name}</div>
                  <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 1 }}>{r.descr}</CDAMono>
                </div>
                <CDAMono size={11.5} color={r.c} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{(r.count/1e3).toFixed(1)}k</CDAMono>
                <CDAMono size={10.5} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums", minWidth: 44, textAlign: "right" }}>
                  {((r.count / rfm.reduce((a,b)=>a+b.count,0)) * 100).toFixed(1)}%
                </CDAMono>
              </div>
            ))}
          </div>
        </CDACard>

        <CDACard title="Markets" subtitle="GUESTS BY ORIGIN COUNTRY · LIFETIME">
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {markets.map((m, i) => (
              <div key={m.name} style={{ animation: `gm-fadein 0.3s ease ${i * 0.04}s both` }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
                  <span style={{ fontSize: 12.5, color: CDA_INK, fontWeight: 500 }}>{m.name}</span>
                  <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <CDAMono size={10.5} color={CDA_DIM} style={{ fontVariantNumeric: "tabular-nums" }}>{(m.n/1e3).toFixed(1)}k</CDAMono>
                    <CDAMono size={11} color={m.c} style={{ fontWeight: 600, minWidth: 48, textAlign: "right" }}>{m.pct.toFixed(1)}%</CDAMono>
                  </span>
                </div>
                <div style={{ height: 5, background: CDA_RULE_S, borderRadius: 3, overflow: "hidden" }}>
                  <div style={{
                    height: "100%", width: `${m.pct * 2.5}%`,
                    background: `linear-gradient(90deg, ${m.c}, ${m.c}aa)`,
                    boxShadow: `0 0 6px ${m.c}50`,
                  }} />
                </div>
              </div>
            ))}
          </div>
        </CDACard>
      </div>
    </div>
  );
}

// ─────────────────── SOURCES TAB ───────────────────
function CDASourcesTab() {
  const totalIngestedToday = cdaLiveNum(8420, 12, 1600);
  const eventsPerSec = cdaLiveFloat(5.8, 0.18, 1400, 3.0, 9.0, 1);

  const sources = [
    {
      pms: "apaleo",
      properties: 2, propertyNames: "Sunset Beach · Atlantic House",
      ingested30d: 84320, lag: "3 s", uptime: 99.98, lastSync: "now",
      throughput: 2.4, status: "ok",
      spark: [240, 268, 290, 312, 340, 372, 396, 422, 450, 478, 504, 528],
    },
    {
      pms: "opera",
      properties: 1, propertyNames: "Zafira Marina",
      ingested30d: 71240, lag: "8 s", uptime: 99.92, lastSync: "8s ago",
      throughput: 1.9, status: "ok",
      spark: [180, 198, 220, 244, 268, 286, 312, 336, 358, 384, 408, 432],
    },
    {
      pms: "mews",
      properties: 2, propertyNames: "Olea Cliffside · Lumia Bay",
      ingested30d: 56480, lag: "12 s", uptime: 99.86, lastSync: "12s ago",
      throughput: 1.5, status: "ok",
      spark: [140, 156, 174, 192, 210, 226, 244, 262, 280, 298, 316, 336],
    },
    {
      pms: "cloudbeds",
      properties: 1, propertyNames: "Casa Verde",
      ingested30d: 42180, lag: "1.4 m", uptime: 98.42, lastSync: "1.4m ago",
      throughput: 1.0, status: "warn",
      spark: [120, 132, 138, 124, 142, 156, 164, 138, 150, 162, 142, 132],
    },
    {
      pms: "protel",
      properties: 1, propertyNames: "Aurora Pines",
      ingested30d: 33420, lag: "9 s", uptime: 99.74, lastSync: "9s ago",
      throughput: 0.9, status: "ok",
      spark: [80, 88, 96, 106, 114, 124, 134, 144, 154, 164, 176, 188],
    },
  ];

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <CDAKPI lbl="Events ingested · today" value={totalIngestedToday} delta="↑ 16%" color={CDA_FUCHSIA} sublabel="all sources · since 00:00" />
        <CDAKPI lbl="Throughput" value={eventsPerSec} suffix=" /sec" valueFmt={v => v.toFixed(1)} delta="↑ 0.4" color={CDA_PINK} sublabel="rolling avg · 5 min" />
        <CDAKPI lbl="Connector uptime" value={99.86} suffix="%" valueFmt={v => v.toFixed(2)} delta="↑ 0.04" color={CDA_POS} sublabel="30-day avg · all 5" />
        <CDAKPI lbl="Bytes processed · 30d" value={142.6} suffix=" GB" valueFmt={v => v.toFixed(1)} delta="↑ 11%" color={CDA_HOT} sublabel="incl. enrichment data" />
      </div>

      {sources.map((s, i) => {
        const pms = CDA_PMS[s.pms];
        const ok = s.status === "ok";
        return (
          <CDACard key={s.pms}
            title={pms.lbl}
            subtitle={`${s.properties} ${s.properties === 1 ? "property" : "properties"} · ${s.propertyNames}`}
            action={
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{
                  padding: "3px 10px", borderRadius: 999,
                  background: ok ? `${CDA_POS}20` : `${CDA_AMBER}20`,
                  border: `1px solid ${ok ? CDA_POS : CDA_AMBER}55`,
                  color: ok ? CDA_POS : CDA_AMBER,
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase",
                  display: "inline-flex", alignItems: "center", gap: 6,
                }}>
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: ok ? CDA_POS : CDA_AMBER, animation: ok ? "gm-dot-pulse 1.6s infinite" : "none" }} />
                  {ok ? "Healthy" : "Lagging"}
                </span>
              </div>
            }
          >
            <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr) 1.6fr", gap: 18, alignItems: "center" }}>
              <div>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Ingested · 30d</CDAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 20, fontWeight: 500, color: CDA_INK,
                  fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em",
                }}>{(s.ingested30d/1e3).toFixed(1)}k</div>
                <CDAMono size={10} color={pms.c} style={{ display: "block", marginTop: 2 }}>bookings</CDAMono>
              </div>
              <div>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Sync lag</CDAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 20, fontWeight: 500, color: ok ? CDA_INK : CDA_AMBER,
                  fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em",
                }}>{s.lag}</div>
                <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>last sync · {s.lastSync}</CDAMono>
              </div>
              <div>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Uptime · 30d</CDAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 20, fontWeight: 500, color: CDA_POS,
                  fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em",
                }}>{s.uptime.toFixed(2)}%</div>
                <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>SLA · 99.5%</CDAMono>
              </div>
              <div>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Throughput</CDAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 20, fontWeight: 500, color: CDA_INK,
                  fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em",
                }}>{s.throughput.toFixed(1)}/s</div>
                <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>rolling 5m</CDAMono>
              </div>
              <div>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>API errors · 24h</CDAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 20, fontWeight: 500, color: ok ? CDA_INK : CDA_AMBER,
                  fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em",
                }}>{ok ? "0" : "12"}</div>
                <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>{ok ? "clean" : "rate-limit · retried"}</CDAMono>
              </div>
              <div>
                <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Hourly volume · 12h</CDAMono>
                <div style={{ height: 38 }}>
                  <CDASparkline data={s.spark} color={pms.c} height={38} gid={`src-${s.pms}`} />
                </div>
              </div>
            </div>
          </CDACard>
        );
      })}

      <CDACard title="Historical · day-0 big bang" subtitle="ONE-TIME BACKFILL · ALL CHECKED-OUT BOOKINGS BEFORE GO-LIVE">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 14, alignItems: "center" }}>
          <div>
            <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Historical bookings</CDAMono>
            <div style={{
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 28, fontWeight: 500, color: CDA_FUCHSIA,
              fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em",
            }}>147,420</div>
            <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>imported on Day 0</CDAMono>
          </div>
          <div>
            <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Records collapsed</CDAMono>
            <div style={{
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 28, fontWeight: 500, color: CDA_PINK,
              fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em",
            }}>−61.5%</div>
            <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>to 56,720 golden records</CDAMono>
          </div>
          <div>
            <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Single-run duration</CDAMono>
            <div style={{
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 28, fontWeight: 500, color: CDA_HOT,
              fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em",
            }}>4h 12m</div>
            <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>parallel · 5 connectors</CDAMono>
          </div>
          <div>
            <CDAMono size={10} color={CDA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase", display: "block", marginBottom: 4 }}>Daily delta · now</CDAMono>
            <div style={{
              fontFamily: "'JetBrains Mono', ui-monospace, monospace",
              fontSize: 28, fontWeight: 500, color: CDA_MAGENTA,
              fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em",
            }}>~480/d</div>
            <CDAMono size={10} color={CDA_DIM} style={{ display: "block", marginTop: 2 }}>ongoing · ~340 merges</CDAMono>
          </div>
        </div>
      </CDACard>
    </div>
  );
}

// ─────────────────── MAIN ───────────────────
function CDPAnalyticsSection() {
  const [tab, setTab] = cdaUseState("sources");
  const [range, setRange] = cdaUseState("30d");

  const tabs = [
    { id: "sources",    label: "Sources · PMS" },
    { id: "overview",   label: "Overview" },
    { id: "identity",   label: "Identity Resolution" },
    { id: "health",     label: "Data Health" },
    { id: "bookings",   label: "Bookings" },
  ];

  const Body = {
    overview: CDAOverviewTab,
    identity: CDAIdentityTab,
    health:   CDADataHealthTab,
    bookings: CDABookingsTab,
    sources:  CDASourcesTab,
  }[tab];

  return (
    <section data-screen-label="CDP Analytics" style={{
      background: CDA_BG, padding: "100px 40px 120px",
      minHeight: "100vh", color: CDA_INK,
      fontFamily: "'Inter', system-ui, sans-serif",
      position: "relative", overflow: "hidden",
    }}>
      {/* ambient glows */}
      <div style={{
        position: "absolute", top: -200, left: "18%", width: 600, height: 600,
        background: `radial-gradient(circle, ${CDA_FUCHSIA}18, transparent 65%)`,
        pointerEvents: "none",
      }} />
      <div style={{
        position: "absolute", bottom: -200, right: "8%", width: 700, height: 700,
        background: `radial-gradient(circle, ${CDA_MAGENTA}15, transparent 65%)`,
        pointerEvents: "none",
      }} />

      {/* header */}
      <div style={{ maxWidth: 1320, margin: "0 auto 48px", textAlign: "center", position: "relative" }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 10, marginBottom: 22 }}>
          <span style={{ display: "inline-block", width: 16, height: 1.5, background: CDA_FUCHSIA, boxShadow: `0 0 8px ${CDA_FUCHSIA}` }} />
          <CDAEyebrow>CDP ANALYTICS</CDAEyebrow>
        </div>
        <h1 style={{
          fontFamily: "'Source Serif 4', Georgia, serif",
          fontWeight: 400, fontSize: "clamp(30px, 3.7vw, 52px)", letterSpacing: "-0.02em",
          lineHeight: 1.05, margin: 0, maxWidth: 920,
          marginInline: "auto", color: CDA_INK,
        }}>
          Every booking, every record, every merge,{" "}
          <span style={{
            fontStyle: "italic", color: CDA_FUCHSIA, display: "block",
            textShadow: `0 0 30px ${CDA_FUCHSIA}50`,
          }}>
            measured the second it lands.
          </span>
        </h1>
        <p style={{
          fontSize: 15, color: CDA_MUTED, lineHeight: 1.65,
          maxWidth: 720, margin: "20px auto 0",
        }}>
          The data plane behind every guest profile, ingestion from five PMS systems,
          identity resolution, field-level data health and the reach gate that decides
          what flows into the CRM. Refreshed live as checkouts confirm.
        </p>
      </div>

      {/* dashboard frame */}
      <ScaleFrame nativeWidth={1320} style={{ maxWidth: 1320, margin: "0 auto" }}>
      <div style={{
        maxWidth: 1320, margin: "0 auto",
        background: CDA_PANEL,
        borderRadius: 14,
        border: `1px solid ${CDA_RULE}`,
        boxShadow: `0 30px 80px -30px rgba(0,0,0,0.7), 0 0 60px -20px ${CDA_FUCHSIA}25`,
        overflow: "hidden",
        position: "relative",
      }}>
        {/* tab bar */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "0 24px",
          borderBottom: `1px solid ${CDA_RULE_S}`,
          background: `linear-gradient(180deg, ${CDA_PANEL_2}, ${CDA_PANEL})`,
        }}>
          <div style={{ display: "flex" }}>
            {tabs.map(t => (
              <button key={t.id} onClick={() => setTab(t.id)} style={{
                padding: "16px 18px",
                background: "transparent",
                color: tab === t.id ? CDA_INK : CDA_MUTED,
                border: "none",
                cursor: "pointer", fontFamily: "inherit",
                fontSize: 13.5, fontWeight: tab === t.id ? 600 : 500,
                letterSpacing: "-0.005em",
                position: "relative",
                transition: "color 0.2s ease",
              }}>
                {t.label}
                {tab === t.id && (
                  <span style={{
                    position: "absolute", left: 18, right: 18, bottom: -1,
                    height: 2, background: CDA_FUCHSIA, borderRadius: 1,
                    boxShadow: `0 0 10px ${CDA_FUCHSIA}`,
                  }} />
                )}
              </button>
            ))}
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{
              display: "flex", padding: 2, borderRadius: 999,
              background: CDA_PANEL, border: `1px solid ${CDA_RULE_S}`,
            }}>
              {["7d", "30d", "90d", "YTD"].map(r => (
                <button key={r} onClick={() => setRange(r)} style={{
                  padding: "5px 12px", borderRadius: 999,
                  background: range === r ? CDA_FUCHSIA : "transparent",
                  color: range === r ? "#fff" : CDA_MUTED,
                  border: "none", cursor: "pointer", fontFamily: "inherit",
                  fontSize: 11, fontWeight: 500,
                  letterSpacing: "0.04em",
                  transition: "all 0.18s ease",
                  boxShadow: range === r ? `0 0 12px ${CDA_FUCHSIA}80` : "none",
                }}>{r}</button>
              ))}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{
                width: 7, height: 7, borderRadius: "50%",
                background: CDA_POS, animation: "gm-dot-pulse 2s infinite",
              }} />
              <CDAMono size={11} color={CDA_POS}>Live</CDAMono>
            </div>
          </div>
        </div>

        {/* Subtle dark-fuchsia scrollbar for the body region */}
        <style>{`
          .cda-body { scrollbar-width: thin; scrollbar-color: ${CDA_F_DEEP}88 transparent; }
          .cda-body::-webkit-scrollbar { width: 8px; }
          .cda-body::-webkit-scrollbar-track { background: transparent; }
          .cda-body::-webkit-scrollbar-thumb { background: ${CDA_F_DEEP}55; border-radius: 4px; border: 2px solid transparent; background-clip: padding-box; }
          .cda-body::-webkit-scrollbar-thumb:hover { background: ${CDA_FUCHSIA}aa; background-clip: padding-box; border: 2px solid transparent; }
        `}</style>
        <div key={tab} className="cda-body" style={{
          animation: "gm-fadein 0.3s ease",
          height: 1180,
          overflowY: "auto",
          overflowX: "hidden",
        }}>
          <Body />
        </div>

        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "12px 24px",
          background: CDA_PANEL_2, borderTop: `1px solid ${CDA_RULE_S}`,
        }}>
          <div style={{ display: "flex", gap: 18 }}>
            <CDAMono size={10.5} color={CDA_DIM}><span style={{ color: CDA_FUCHSIA }}>●</span> snapshot · {range}</CDAMono>
            <CDAMono size={10.5} color={CDA_DIM}><span style={{ color: CDA_POS }}>●</span> sync · {`<`} 5s ago</CDAMono>
            <CDAMono size={10.5} color={CDA_DIM}><span style={{ color: CDA_PINK }}>●</span> 7 properties</CDAMono>
            <CDAMono size={10.5} color={CDA_DIM}><span style={{ color: CDA_HOT }}>●</span> 5 PMS connectors</CDAMono>
          </div>
          <CDAMono size={10.5} color={CDA_DIM}>Export · CSV · PDF · Schedule report</CDAMono>
        </div>
      </div>
      </ScaleFrame>
    </section>
  );
}

window.CDPAnalyticsSection = CDPAnalyticsSection;
