// Guestmaker · CRM Analytics, DARK FUCHSIA
// Live, world-class analytics focused on contact data — pairs with the
// CRM hero/contact/data-layer/bookings/segments sections in Hotel CRM.html.
// All data is fictional seed data.

const { useState: caUseState, useEffect: caUseEffect, useRef: caUseRef, useMemo: caUseMemo } = React;

// ── palette ──
const CA_BG       = "#120912";
const CA_PANEL    = "#1a0f1a";
const CA_PANEL_2  = "#22142a";
const CA_RULE     = "#3a1f3a";
const CA_RULE_S   = "#2a172a";

const CA_INK      = "#f5e6f0";
const CA_MUTED    = "#a896a6";
const CA_DIM      = "#7a6a78";

const CA_FUCHSIA  = "#ff4d97";
const CA_F_DEEP   = "#d63d80";
const CA_F_LIGHT  = "#ff8fbc";
const CA_F_SOFT   = "#3d1a2c";

const CA_PINK     = "#ff7ab8";
const CA_MAGENTA  = "#c235a3";
const CA_ROSE     = "#ff5577";
const CA_PLUM     = "#8a3a78";
const CA_HOT      = "#ff2d7c";

const CA_POS = "#5cd0a0";
const CA_NEG = "#ff8068";

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

function caAnimNum(target, dur = 600) {
  const [v, setV] = caUseState(target);
  const fromRef = caUseRef(target);
  caUseEffect(() => {
    fromRef.current = v;
    const start = performance.now();
    let raf;
    const loop = () => {
      const t = Math.min(1, (performance.now() - start) / dur);
      const e = 1 - Math.pow(1 - t, 3);
      setV(fromRef.current + (target - fromRef.current) * e);
      if (t < 1) raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [target]);
  return v;
}

function caLiveNum(seed, jitter = 4, interval = 1800) {
  const [v, setV] = caUseState(seed);
  caUseEffect(() => {
    const t = setInterval(() => {
      setV(x => x + Math.floor(Math.random() * jitter * 2));
    }, interval);
    return () => clearInterval(t);
  }, [jitter, interval]);
  return v;
}

function caLiveFloat(seed, jitter = 0.05, interval = 2200, min = 0, max = 100, decimals = 1) {
  const [v, setV] = caUseState(seed);
  caUseEffect(() => {
    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;
}

// ── chart helpers ──
function caBuildPath(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 CASparkline({ data, color, height = 28, gid }) {
  const pts = caBuildPath(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 = `cas-${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>
  );
}

// ── KPI card ──
function CAKPI({ lbl, value, delta, deltaColor = CA_POS, suffix = "", spark, color = CA_FUCHSIA, prefix = "", gid, valueFmt }) {
  const display = valueFmt
    ? valueFmt(value)
    : (typeof value === "number" ? value.toLocaleString("en-US") : value);
  return (
    <div style={{
      background: CA_PANEL,
      border: `1px solid ${CA_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)`,
      }} />
      <CAMono size={10.5} color={CA_DIM} style={{ letterSpacing: "0.14em", textTransform: "uppercase", display: "block" }}>{lbl}</CAMono>
      <div style={{
        fontFamily: "'JetBrains Mono', ui-monospace, monospace",
        fontSize: 26, fontWeight: 500, color: CA_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>
        <CAMono size={10.5} color={CA_DIM}>vs last 30d</CAMono>
      </div>
      {spark && (
        <div style={{ marginTop: 4, marginBottom: -4 }}>
          <CASparkline data={spark} color={color} height={32} gid={gid} />
        </div>
      )}
    </div>
  );
}

// ── area chart ──
function CAAreaChart({ data, color, height = 200, secondary, gid }) {
  const w = 100;
  const max = Math.max(...data, ...(secondary || []));
  const min = 0;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = height - 24 - ((v - min) / (max - min || 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 - min) / (max - min || 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 = `caac-${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={CA_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={CA_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>
  );
}

// ── donut ──
function CADonut({ 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={CA_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: CA_INK,
          letterSpacing: "-0.02em", lineHeight: 1,
        }}>{label}</div>
        <CAMono size={10.5} color={CA_DIM} style={{ marginTop: 4 }}>{sublabel}</CAMono>
      </div>
    </div>
  );
}

// ── bar chart ──
function CABarChart({ data, color = CA_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: CA_INK, fontWeight: 500 }}>{d.label}</span>
              <CAMono size={11} color={c} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>
                {format(d.value)}
              </CAMono>
            </div>
            <div style={{ height: 6, background: CA_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>
  );
}

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

function CALegend({ 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 }} />
          )}
          <CAMono size={10.5} color={CA_MUTED}>{i.lbl}</CAMono>
        </div>
      ))}
    </div>
  );
}

// segment tag styling
function caSegBg(s) {
  return ({ Prospect: `${CA_PLUM}30`, Engaged: `${CA_MAGENTA}25`, Booked: `${CA_PINK}25`, Returning: `${CA_FUCHSIA}25`, VIP: `${CA_HOT}25`, Dormant: `${CA_MUTED}20` })[s] || `${CA_PLUM}30`;
}
function caSegFg(s) {
  return ({ Prospect: CA_PINK, Engaged: CA_MAGENTA, Booked: CA_F_LIGHT, Returning: CA_FUCHSIA, VIP: CA_HOT, Dormant: CA_MUTED })[s] || CA_PINK;
}

// channel colors (mapped to CRM's CHANNELS)
const CA_CH = {
  whatsapp:  { lbl: "WhatsApp",     c: CA_FUCHSIA },
  webchat:   { lbl: "Web Chatbot",  c: CA_PINK    },
  voice:     { lbl: "Voice",        c: CA_MAGENTA },
  instagram: { lbl: "Instagram DM", c: CA_HOT     },
  facebook:  { lbl: "Facebook Msgr",c: CA_ROSE    },
  email:     { lbl: "Email",        c: CA_PLUM    },
  sms:       { lbl: "SMS",          c: CA_F_LIGHT },
};

// ── stay state strip ──
function CAStayStateStrip() {
  const preStay  = caLiveNum(842,  3, 2400);
  const inStay   = caLiveNum(318,  2, 1900);
  const postStay = caLiveNum(2640, 4, 2600);

  const states = [
    {
      key: "pre",
      lbl: "Pre-stay",
      sub: "Arriving in next 14 days",
      value: preStay,
      color: CA_PINK,
      dot: "PRE",
      spark: [62, 68, 74, 79, 86, 92, 98, 104, 112, 118, 124, 132, 138, 144, 152, 158],
      meta: "avg lead time · 23 days",
      guests: [
        { who: "M. Lindqvist", when: "in 2 d",  hotel: "Sunset Beach",   nights: 5 },
        { who: "A. de Vries",  when: "in 4 d",  hotel: "Zafira Marina",  nights: 7 },
        { who: "L. Marchetti", when: "in 6 d",  hotel: "Olea Cliffside", nights: 4 },
        { who: "S. Park",      when: "in 9 d",  hotel: "Casa Verde",     nights: 3 },
        { who: "A. Okafor",    when: "in 12 d", hotel: "Atlantic House", nights: 6 },
      ],
    },
    {
      key: "in",
      lbl: "In-stay",
      sub: "Currently checked in",
      value: inStay,
      color: CA_FUCHSIA,
      dot: "NOW",
      live: true,
      spark: [28, 32, 36, 31, 34, 38, 42, 40, 44, 46, 48, 45, 47, 49, 51, 53],
      meta: "across 7 properties · 14 VIP",
      guests: [
        { who: "D. Richter",   when: "until Sun",  hotel: "Zafira Marina · 412", nights: 4 },
        { who: "J. Kerr",      when: "until Sat",  hotel: "Sunset Beach · 218",  nights: 3 },
        { who: "H. Nakamura",  when: "until Mon",  hotel: "Olea Cliffside · 7B", nights: 5 },
        { who: "C. Ferreira",  when: "until Fri",  hotel: "Casa Verde · 104",    nights: 2 },
        { who: "T. Bianchi",   when: "until Tue",  hotel: "Atlantic House · 312",nights: 6 },
      ],
    },
    {
      key: "post",
      lbl: "Post-stay",
      sub: "Checked out · last 30 days",
      value: postStay,
      color: CA_MAGENTA,
      dot: "POST",
      spark: [180, 196, 212, 228, 244, 261, 278, 296, 314, 332, 350, 368, 386, 404, 422, 440],
      meta: "NPS window · 7-day review",
      guests: [
        { who: "K. Rasmussen", when: "1 d ago",  hotel: "Sunset Beach",   nights: 4 },
        { who: "E. Schmitt",   when: "2 d ago",  hotel: "Zafira Marina",  nights: 6 },
        { who: "R. Gallagher", when: "4 d ago",  hotel: "Olea Cliffside", nights: 3 },
        { who: "P. Almeida",   when: "6 d ago",  hotel: "Atlantic House", nights: 5 },
        { who: "I. Khoury",    when: "8 d ago",  hotel: "Casa Verde",     nights: 7 },
      ],
    },
  ];

  const total = preStay + inStay + postStay;

  return (
    <CACard
      title="Guests by stay state"
      subtitle="LIVE · GROUP-WIDE"
      action={
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <CAMono size={10.5} color={CA_DIM}>total addressable</CAMono>
          <CAMono size={13} color={CA_F_LIGHT} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>
            {total.toLocaleString()}
          </CAMono>
        </div>
      }
    >
      {/* journey rail */}
      <div style={{
        position: "relative",
        display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
        gap: 0,
        marginBottom: 14,
      }}>
        <div style={{
          position: "absolute", left: "16.66%", right: "16.66%", top: 11,
          height: 1, background: `linear-gradient(90deg, ${CA_PINK}55, ${CA_FUCHSIA}80, ${CA_MAGENTA}55)`,
        }} />
        {states.map((s, i) => (
          <div key={s.key} style={{ display: "flex", flexDirection: "column", alignItems: "center", position: "relative", zIndex: 1 }}>
            <span style={{
              width: 22, height: 22, borderRadius: "50%",
              background: CA_PANEL,
              border: `1.5px solid ${s.color}`,
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              boxShadow: `0 0 14px ${s.color}90`,
              position: "relative",
            }}>
              <span style={{
                width: 8, height: 8, borderRadius: "50%",
                background: s.color,
                animation: s.live ? "gm-dot-pulse 1.6s infinite" : "none",
              }} />
            </span>
            <CAMono size={9.5} color={s.color} style={{ marginTop: 6, letterSpacing: "0.16em", fontWeight: 600 }}>
              {s.dot}
            </CAMono>
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
        {states.map((s, i) => (
          <div key={s.key} style={{
            background: CA_PANEL_2,
            border: `1px solid ${CA_RULE_S}`,
            borderRadius: 8,
            padding: "14px 16px",
            position: "relative",
            overflow: "hidden",
            animation: `gm-fadein 0.35s ease ${i * 0.06}s both`,
          }}>
            {/* top accent */}
            <div style={{
              position: "absolute", top: 0, left: 0, right: 0, height: 2,
              background: `linear-gradient(90deg, transparent, ${s.color}, transparent)`,
            }} />

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <div>
                <div style={{
                  fontFamily: "'Inter', system-ui, sans-serif",
                  fontSize: 13, fontWeight: 600, color: CA_INK,
                  letterSpacing: "-0.005em",
                }}>{s.lbl}</div>
                <CAMono size={10} color={CA_DIM} style={{ marginTop: 3, letterSpacing: "0.08em", textTransform: "uppercase", display: "block" }}>
                  {s.sub}
                </CAMono>
              </div>
              {s.live && (
                <span style={{
                  padding: "2px 8px", borderRadius: 999,
                  background: `${s.color}25`,
                  border: `1px solid ${s.color}55`,
                  color: s.color,
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 9, letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 600,
                  display: "inline-flex", alignItems: "center", gap: 5,
                }}>
                  <span style={{ width: 5, height: 5, borderRadius: "50%", background: s.color, animation: "gm-dot-pulse 1.6s infinite" }} />
                  Live
                </span>
              )}
            </div>

            <div style={{
              display: "flex", alignItems: "baseline", justifyContent: "space-between",
              marginTop: 10,
            }}>
              <div style={{
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 30, fontWeight: 500, color: s.color,
                letterSpacing: "-0.02em", lineHeight: 1,
                fontVariantNumeric: "tabular-nums",
                textShadow: `0 0 14px ${s.color}50`,
              }}>{s.value.toLocaleString()}</div>
              <CAMono size={10.5} color={CA_F_LIGHT} style={{ fontWeight: 600 }}>
                {((s.value / total) * 100).toFixed(1)}%
              </CAMono>
            </div>

            <div style={{ marginTop: 6, height: 28 }}>
              <CASparkline data={s.spark} color={s.color} height={28} gid={`stay-${s.key}`} />
            </div>

            <CAMono size={10} color={CA_DIM} style={{ display: "block", marginTop: 2 }}>{s.meta}</CAMono>

            <div style={{
              marginTop: 10, paddingTop: 10,
              borderTop: `1px solid ${CA_RULE_S}`,
            }}>
              {s.guests.map((g, k) => (
                <div key={k} style={{
                  display: "grid", gridTemplateColumns: "auto 1fr auto",
                  alignItems: "center", gap: 8,
                  padding: "5px 0",
                  borderBottom: k < s.guests.length - 1 ? `1px dashed ${CA_RULE_S}` : "none",
                }}>
                  <span style={{
                    width: 20, height: 20, borderRadius: "50%",
                    background: s.color, color: "#fff",
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                    fontSize: 8.5, fontWeight: 600,
                    boxShadow: `0 0 6px ${s.color}55`,
                  }}>{g.who.split(" ")[0][0]}{g.who.split(" ")[1][0]}</span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 11.5, color: CA_INK, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {g.who}
                    </div>
                    <CAMono size={9.5} color={CA_DIM} style={{ display: "block", marginTop: 1 }}>
                      {g.hotel} · {g.nights}n
                    </CAMono>
                  </div>
                  <CAMono size={10} color={s.color} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>
                    {g.when}
                  </CAMono>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </CACard>
  );
}

// ────────────────────────── OVERVIEW ──────────────────────────
function CAOverviewTab() {
  const contacts   = caLiveNum(184_320, 6, 2200);
  const messages   = caLiveNum(48_240, 14, 1700);
  const aiRate     = caLiveFloat(94.2, 0.06, 2400, 90, 99, 1);
  const respSec    = caLiveFloat(8.4, 0.2, 2000, 5, 14, 1);

  const sparks = {
    contacts: [120,124,127,131,134,138,141,145,148,153,158,162,167,172,178,184],
    messages: [180,210,205,240,260,255,280,295,310,330,350,345,370,395,420,440],
    ai:       [88,89,90,90,91,91,92,93,93,93,94,94,94,94,94,94],
    resp:     [22,20,19,17,16,14,13,12,11,11,10,9,9,8,8,8],
  };

  const contactGrowth = [120,160,210,260,320,380,440,510,590,680,780,890,1010,1140,1280,1430,1590,1760,1940,2130,2330,2540,2760,2990];
  const forecast = contactGrowth.map((v, i) => v * (1 + i * 0.006));

  const sourceMix = [
    { label: "Website · captive portal", value: 38420, color: CA_FUCHSIA },
    { label: "WhatsApp inbound",         value: 32180, color: CA_PINK    },
    { label: "Booking.com / OTA",        value: 27640, color: CA_HOT     },
    { label: "Meta Ads · IG · FB",       value: 19460, color: CA_ROSE    },
    { label: "Voice agent",              value: 14820, color: CA_MAGENTA },
    { label: "Front desk · walk-in",     value:  8930, color: CA_PLUM    },
  ];

  const recentActivity = [
    { who: "A. de Vries",      ch: "whatsapp",  evt: "Late checkout req.", seg: "Returning", t: "0:08" },
    { who: "D. Richter",       ch: "voice",     evt: "Spa booking",         seg: "VIP",       t: "0:34" },
    { who: "M. Lindqvist",     ch: "instagram", evt: "Cabana upsell click", seg: "Engaged",   t: "1:12" },
    { who: "L. Marchetti",     ch: "email",     evt: "Pre-stay opened",     seg: "Booked",    t: "2:06" },
    { who: "S. Park",          ch: "webchat",   evt: "Bike rental",         seg: "Booked",    t: "3:41" },
    { who: "J. Kerr",          ch: "whatsapp",  evt: "F&B reservation",     seg: "Returning", t: "4:18" },
    { who: "A. Okafor",        ch: "facebook",  evt: "First message",       seg: "Prospect",  t: "5:02" },
  ];

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <CAKPI lbl="Active contacts" value={contacts} delta="↑ 11.2%" spark={sparks.contacts} color={CA_FUCHSIA} gid="cak1" />
        <CAKPI lbl="Messages handled · 30d" value={messages} delta="↑ 18.6%" spark={sparks.messages} color={CA_PINK} gid="cak2" />
        <CAKPI lbl="AI resolution rate" value={aiRate} suffix="%" valueFmt={v => v.toFixed(1)} delta="↑ 2.4 pts" spark={sparks.ai} color={CA_MAGENTA} gid="cak3" />
        <CAKPI lbl="Avg first response" value={respSec} suffix="s" valueFmt={v => v.toFixed(1)} delta="↓ 38%" deltaColor={CA_POS} spark={sparks.resp} color={CA_HOT} gid="cak4" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18 }}>
        <CACard
          title="Contact growth"
          subtitle="LAST 24 MONTHS · NET NEW UNIFIED PROFILES"
          action={<CALegend items={[{c: CA_FUCHSIA, lbl: "Contacts"}, {c: CA_F_LIGHT, lbl: "Forecast", dashed: true}]} />}
        >
          <div style={{ height: 220, position: "relative" }}>
            <CAAreaChart data={contactGrowth} color={CA_FUCHSIA} height={220} secondary={forecast} gid="cagrow" />
          </div>
          <div style={{
            display: "flex", justifyContent: "space-between",
            marginTop: 8, fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 10, color: CA_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>
        </CACard>

        <CACard title="Channel mix" subtitle="MESSAGES · LAST 30D">
          <div style={{ display: "flex", justifyContent: "center" }}>
            <CADonut
              segments={[
                { color: CA_FUCHSIA, value: 46 },
                { color: CA_PINK,    value: 22 },
                { color: CA_HOT,     value: 14 },
                { color: CA_ROSE,    value: 9 },
                { color: CA_MAGENTA, value: 6 },
                { color: CA_PLUM,    value: 3 },
              ]}
              size={180} thickness={20}
              label="48.2k"
              sublabel="messages · 30d"
            />
          </div>
          <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 6 }}>
            {[
              { c: CA_FUCHSIA, lbl: "WhatsApp",     v: "46%" },
              { c: CA_PINK,    lbl: "Web Chatbot",  v: "22%" },
              { c: CA_HOT,     lbl: "Instagram DM", v: "14%" },
              { c: CA_ROSE,    lbl: "Facebook Msgr",v: "9%"  },
              { c: CA_MAGENTA, lbl: "Voice",        v: "6%"  },
              { c: CA_PLUM,    lbl: "Email · SMS",  v: "3%"  },
            ].map(r => (
              <div key={r.lbl} style={{
                display: "flex", justifyContent: "space-between", alignItems: "center",
                padding: "4px 0", borderBottom: `1px solid ${CA_RULE_S}`,
              }}>
                <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: r.c }} />
                  <span style={{ fontSize: 12, color: CA_MUTED }}>{r.lbl}</span>
                </span>
                <CAMono size={11.5} color={r.c} style={{ fontWeight: 600 }}>{r.v}</CAMono>
              </div>
            ))}
          </div>
        </CACard>
      </div>

      <CAStayStateStrip />

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <CACard title="Top acquisition sources" subtitle="NEW CONTACTS · 30D">
          <CABarChart data={sourceMix} format={v => v >= 1e3 ? `${(v/1e3).toFixed(1)}k` : v.toLocaleString()} />
        </CACard>

        <CACard title="Live activity" subtitle="LAST 5 MINUTES · ALL CHANNELS" padBody={false}>
          <div>
            {recentActivity.map((m, i) => {
              const ch = CA_CH[m.ch];
              return (
                <div key={i} style={{
                  display: "grid", gridTemplateColumns: "1fr auto auto",
                  alignItems: "center", gap: 12,
                  padding: "9px 18px",
                  borderBottom: i < recentActivity.length - 1 ? `1px solid ${CA_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: 24, height: 24, borderRadius: "50%",
                      background: ch.c, color: "#fff",
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                      fontSize: 9.5, fontWeight: 600,
                      boxShadow: `0 0 10px ${ch.c}50`,
                    }}>{m.who.split(" ")[0][0]}{m.who.split(" ")[1][0]}</span>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, color: CA_INK, fontWeight: 500 }}>{m.who}</div>
                      <CAMono size={10} color={CA_DIM} style={{ display: "block", marginTop: 2 }}>
                        {ch.lbl} · {m.evt}
                      </CAMono>
                    </div>
                  </div>
                  <span style={{
                    padding: "2px 8px", borderRadius: 999,
                    background: caSegBg(m.seg), color: caSegFg(m.seg),
                    border: `1px solid ${caSegFg(m.seg)}40`,
                    fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                    fontSize: 9.5, fontWeight: 500, letterSpacing: "0.06em",
                    textTransform: "uppercase",
                  }}>{m.seg}</span>
                  <CAMono size={10.5} color={CA_DIM} style={{ fontVariantNumeric: "tabular-nums" }}>{m.t} ago</CAMono>
                </div>
              );
            })}
          </div>
        </CACard>
      </div>
    </div>
  );
}

// ────────────────────────── CONTACTS ──────────────────────────
function CAContactsTab() {
  const segments = [
    { name: "Prospect",  value: 62400, color: CA_PLUM,    pct: 33.9 },
    { name: "Engaged",   value: 48200, color: CA_MAGENTA, pct: 26.2 },
    { name: "Booked",    value: 32800, color: CA_PINK,    pct: 17.8 },
    { name: "Returning", value: 24600, color: CA_FUCHSIA, pct: 13.4 },
    { name: "VIP",       value:  4820, color: CA_HOT,     pct:  2.6 },
    { name: "Dormant",   value: 11500, color: CA_MUTED,   pct:  6.1 },
  ];
  const total = segments.reduce((a, t) => a + t.value, 0);

  const cohorts = [
    { month: "Aug 24", new: 3240, ret30: 88, ret60: 71, ret90: 58 },
    { month: "Sep 24", new: 3580, ret30: 90, ret60: 74, ret90: 60 },
    { month: "Oct 24", new: 3910, ret30: 87, ret60: 70, ret90: 55 },
    { month: "Nov 24", new: 4260, ret30: 92, ret60: 78, ret90: 64 },
    { month: "Dec 24", new: 4840, ret30: 94, ret60: 81, ret90: 68 },
    { month: "Jan 25", new: 4220, ret30: 89, ret60: 73, ret90: 60 },
    { month: "Feb 25", new: 4050, ret30: 88, ret60: 72, ret90: 58 },
    { month: "Mar 25", new: 4680, ret30: 93, ret60: 79, ret90: 65 },
  ];

  const top = [
    { name: "D. Richter",   seg: "VIP",       msgs: 412, rev: 28400, last: "8m"  },
    { name: "S. Park",      seg: "VIP",       msgs: 386, rev: 24180, last: "21m" },
    { name: "M. Lindqvist", seg: "Returning", msgs: 318, rev: 18900, last: "34m" },
    { name: "L. Marchetti", seg: "Returning", msgs: 282, rev: 16240, last: "1h"  },
    { name: "A. Okafor",    seg: "Booked",    msgs: 254, rev: 14800, last: "1h"  },
    { name: "J. Kerr",      seg: "Booked",    msgs: 228, rev: 11200, last: "2h"  },
  ];

  const cellStyle = {
    padding: "10px 16px", borderBottom: `1px solid ${CA_RULE_S}`,
    fontFamily: "'Inter', system-ui, sans-serif", fontSize: 12.5, color: CA_MUTED,
  };

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 18 }}>
        <CACard title="Lifecycle segments" subtitle="ALL CONTACTS · MTD">
          <div style={{ display: "flex", gap: 24, alignItems: "center" }}>
            <CADonut
              segments={segments.map(t => ({ color: t.color, value: t.value }))}
              size={180} thickness={22}
              label={(total/1e3).toFixed(1) + "k"}
              sublabel="contacts"
            />
            <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
              {segments.map(t => (
                <div key={t.name} style={{
                  display: "grid", gridTemplateColumns: "auto 1fr auto auto",
                  alignItems: "center", gap: 10,
                }}>
                  <span style={{ width: 10, height: 10, borderRadius: 2, background: t.color, boxShadow: `0 0 6px ${t.color}80` }} />
                  <span style={{ fontSize: 12.5, color: CA_INK, fontWeight: 500 }}>{t.name}</span>
                  <CAMono size={11} color={CA_MUTED} style={{ fontVariantNumeric: "tabular-nums" }}>
                    {t.value.toLocaleString()}
                  </CAMono>
                  <CAMono size={11} color={t.color} style={{ fontWeight: 600, minWidth: 44, textAlign: "right" }}>
                    {t.pct}%
                  </CAMono>
                </div>
              ))}
            </div>
          </div>
        </CACard>

        <CACard title="Cohort retention" subtitle="% RETURNING WITHIN 30 / 60 / 90 DAYS" padBody={false}>
          <div style={{ overflowX: "auto" }}>
            <table style={{
              width: "100%", borderCollapse: "collapse",
              fontFamily: "'Inter', system-ui, sans-serif",
            }}>
              <thead>
                <tr>
                  {["Cohort", "New", "30d", "60d", "90d"].map(h => (
                    <th key={h} style={{
                      textAlign: h === "Cohort" || h === "New" ? "left" : "center",
                      padding: "10px 16px",
                      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                      fontSize: 10, color: CA_DIM, fontWeight: 500,
                      letterSpacing: "0.1em", textTransform: "uppercase",
                      borderBottom: `1px solid ${CA_RULE_S}`,
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {cohorts.map((c, i) => (
                  <tr key={i} style={{ animation: `gm-fadein 0.25s ease ${i * 0.03}s both` }}>
                    <td style={{...cellStyle, color: CA_INK, fontWeight: 500}}>{c.month}</td>
                    <td style={{ ...cellStyle, fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontSize: 11.5 }}>{c.new.toLocaleString()}</td>
                    <td style={{ textAlign: "center", padding: "8px 16px", borderBottom: `1px solid ${CA_RULE_S}` }}><CAHeat v={c.ret30} /></td>
                    <td style={{ textAlign: "center", padding: "8px 16px", borderBottom: `1px solid ${CA_RULE_S}` }}><CAHeat v={c.ret60} /></td>
                    <td style={{ textAlign: "center", padding: "8px 16px", borderBottom: `1px solid ${CA_RULE_S}` }}><CAHeat v={c.ret90} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CACard>
      </div>

      <CACard title="Most engaged contacts" subtitle="BY MESSAGES · LAST 90 DAYS" padBody={false}>
        <div>
          <div style={{
            display: "grid",
            gridTemplateColumns: "32px 1fr auto auto auto auto",
            gap: 18, padding: "10px 18px",
            borderBottom: `1px solid ${CA_RULE_S}`,
            background: CA_PANEL_2,
          }}>
            {["#", "Contact", "Segment", "Msgs", "Lifetime €", "Last seen"].map((h, i) => (
              <CAMono key={h} size={10} color={CA_DIM} style={{
                letterSpacing: "0.1em", textTransform: "uppercase",
                textAlign: i >= 3 ? "right" : "left",
              }}>{h}</CAMono>
            ))}
          </div>
          {top.map((m, i) => (
            <div key={i} style={{
              display: "grid",
              gridTemplateColumns: "32px 1fr auto auto auto auto",
              gap: 18, padding: "12px 18px",
              borderBottom: i < top.length - 1 ? `1px solid ${CA_RULE_S}` : "none",
              alignItems: "center",
              transition: "background 0.18s ease",
            }} onMouseEnter={e => e.currentTarget.style.background = CA_PANEL_2}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
              <CAMono size={11} color={CA_DIM}>0{i+1}</CAMono>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{
                  width: 26, height: 26, borderRadius: "50%",
                  background: [CA_FUCHSIA, CA_PINK, CA_HOT, CA_ROSE, CA_MAGENTA, CA_PLUM][i % 6],
                  color: "#fff",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 10, fontWeight: 600,
                  boxShadow: `0 0 10px ${[CA_FUCHSIA, CA_PINK, CA_HOT, CA_ROSE, CA_MAGENTA, CA_PLUM][i % 6]}55`,
                }}>{m.name.split(" ")[0][0]}{m.name.split(" ")[1][0]}</span>
                <span style={{ fontSize: 13, color: CA_INK, fontWeight: 500 }}>{m.name}</span>
              </div>
              <span style={{
                padding: "2px 9px", borderRadius: 999,
                background: caSegBg(m.seg), color: caSegFg(m.seg),
                border: `1px solid ${caSegFg(m.seg)}40`,
                fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                fontSize: 10, fontWeight: 500, letterSpacing: "0.06em",
                textTransform: "uppercase",
              }}>{m.seg}</span>
              <CAMono size={11.5} color={CA_MUTED} style={{ fontVariantNumeric: "tabular-nums", textAlign: "right" }}>{m.msgs}</CAMono>
              <CAMono size={11.5} color={CA_MUTED} style={{ fontVariantNumeric: "tabular-nums", textAlign: "right" }}>€{m.rev.toLocaleString()}</CAMono>
              <CAMono size={11.5} color={CA_FUCHSIA} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums", textAlign: "right" }}>{m.last} ago</CAMono>
            </div>
          ))}
        </div>
      </CACard>
    </div>
  );
}

function CAHeat({ v }) {
  const opacity = Math.max(0.06, Math.min(1, v / 100));
  return (
    <span style={{
      display: "inline-block",
      padding: "5px 10px", borderRadius: 4,
      background: `rgba(255, 77, 151, ${opacity * 0.55})`,
      color: opacity > 0.7 ? "#fff" : CA_F_LIGHT,
      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
      fontSize: 11.5, fontWeight: 500,
      fontVariantNumeric: "tabular-nums",
      minWidth: 36,
      border: `1px solid rgba(255, 77, 151, ${opacity * 0.5})`,
    }}>{v}%</span>
  );
}

// ────────────────────────── CHANNELS ──────────────────────────
function CAChannelsTab() {
  const channels = [
    { id: "whatsapp",  msgs: 22180, aiHandled: 21390, esc: 790, color: CA_FUCHSIA, resp: 6.2 },
    { id: "webchat",   msgs: 10620, aiHandled: 10180, esc: 440, color: CA_PINK,    resp: 4.1 },
    { id: "instagram", msgs:  6740, aiHandled:  6160, esc: 580, color: CA_HOT,     resp: 9.4 },
    { id: "facebook",  msgs:  4340, aiHandled:  3920, esc: 420, color: CA_ROSE,    resp: 11.8 },
    { id: "voice",     msgs:  2890, aiHandled:  2240, esc: 650, color: CA_MAGENTA, resp: 0.0 },
    { id: "email",     msgs:  1470, aiHandled:   980, esc: 490, color: CA_PLUM,    resp: 184.0 },
  ];

  const heatmap = (() => {
    const days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
    return days.map((d, di) => ({
      day: d,
      cells: Array.from({ length: 24 }, (_, h) => {
        const base = 10 + Math.sin((h - 9) / 24 * Math.PI * 2) * 14;
        const weekend = di >= 5 ? 4 : 0;
        const evening = h >= 18 && h <= 22 ? 16 : 0;
        const morning = h >= 8 && h <= 11 ? 10 : 0;
        const rand = Math.sin(di * 11 + h * 2.7) * 5;
        return Math.max(0, Math.round(base + weekend + evening + morning + rand));
      }),
    }));
  })();
  const heatMax = Math.max(...heatmap.flatMap(d => d.cells));

  const respBars = channels.map(c => {
    const ch = CA_CH[c.id];
    return {
      label: ch.lbl,
      value: c.resp,
      color: ch.c,
    };
  });

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <CACard title="Channel performance" subtitle="MESSAGES → AI HANDLED → ESCALATED · 30D">
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {channels.map((j, i) => {
            const ch = CA_CH[j.id];
            const stages = [
              { lbl: "Inbound",     val: j.msgs,       pct: 100 },
              { lbl: "AI handled",  val: j.aiHandled,  pct: (j.aiHandled / j.msgs) * 100 },
              { lbl: "Escalated",   val: j.esc,        pct: (j.esc / j.msgs) * 100 },
              { lbl: "AI rate",     val: ((j.aiHandled / j.msgs) * 100).toFixed(1) + "%", pct: (j.aiHandled / j.msgs) * 100, mono: true },
            ];
            return (
              <div key={j.id} style={{ animation: `gm-fadein 0.3s ease ${i * 0.05}s both` }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: ch.c, boxShadow: `0 0 6px ${ch.c}90` }} />
                    <span style={{ fontSize: 13, color: CA_INK, fontWeight: 500 }}>{ch.lbl}</span>
                  </span>
                  <CAMono size={11} color={ch.c} style={{ fontWeight: 600 }}>
                    {j.resp === 0 ? "live · 0s" : j.resp >= 60 ? `${(j.resp/60).toFixed(1)} min` : `${j.resp.toFixed(1)}s avg`}
                  </CAMono>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 4 }}>
                  {stages.map((s, k) => (
                    <div key={k} style={{
                      background: CA_PANEL_2,
                      border: `1px solid ${CA_RULE_S}`,
                      borderRadius: 4, padding: "6px 10px",
                      position: "relative", overflow: "hidden",
                    }}>
                      <div style={{
                        position: "absolute", inset: 0,
                        width: `${s.pct}%`,
                        background: `linear-gradient(90deg, ${ch.c}55, ${ch.c}22)`,
                        transition: "width 0.6s ease",
                      }} />
                      <div style={{ position: "relative" }}>
                        <CAMono size={9.5} color={CA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase" }}>{s.lbl}</CAMono>
                        <div style={{
                          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                          fontSize: 13, fontWeight: 500, color: CA_INK,
                          fontVariantNumeric: "tabular-nums",
                        }}>{typeof s.val === "number" ? s.val.toLocaleString() : s.val}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </CACard>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: 18 }}>
        <CACard title="Response time" subtitle="MEDIAN · BY CHANNEL">
          <CABarChart
            data={respBars}
            format={v => v === 0 ? "live" : v >= 60 ? `${(v/60).toFixed(1)} min` : `${v.toFixed(1)}s`}
          />
          <div style={{ marginTop: 12, paddingTop: 10, borderTop: `1px solid ${CA_RULE_S}`, display: "flex", gap: 14, alignItems: "center", justifyContent: "space-between" }}>
            <CAMono size={10.5} color={CA_DIM}>SLA · 60s threshold</CAMono>
            <CAMono size={11} color={CA_POS} style={{ fontWeight: 600 }}>5 of 6 channels within SLA</CAMono>
          </div>
        </CACard>

        <CACard title="Message volume" subtitle="OPENS + REPLIES · DAY × HOUR · UTC+2">
          <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) => (
                <CAMono key={h} size={8.5} color={CA_DIM} style={{ textAlign: "center" }}>
                  {h % 6 === 0 ? `${h}` : ""}
                </CAMono>
              ))}
            </div>
            {heatmap.map(d => (
              <div key={d.day} style={{ display: "grid", gridTemplateColumns: "32px repeat(24, 1fr)", gap: 2 }}>
                <CAMono size={10} color={CA_MUTED} style={{ alignSelf: "center" }}>{d.day}</CAMono>
                {d.cells.map((v, h) => {
                  const op = v / heatMax;
                  return (
                    <div key={h} title={`${d.day} ${h}:00 · ${v} msg`} 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 }}>
              <CAMono size={9.5} color={CA_DIM}>low</CAMono>
              {[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 }} />
              ))}
              <CAMono size={9.5} color={CA_DIM}>high</CAMono>
              <span style={{ flex: 1 }} />
              <CAMono size={10.5} color={CA_F_LIGHT}>peak · Fri 20:00–22:00</CAMono>
            </div>
          </div>
        </CACard>
      </div>
    </div>
  );
}

// ────────────────────────── AI PERFORMANCE ──────────────────────────
function CAAITab() {
  const intents = [
    { label: "Booking · modify",     value: 8420, color: CA_FUCHSIA },
    { label: "Room service / F&B",   value: 6210, color: CA_PINK    },
    { label: "Spa & wellness",       value: 4680, color: CA_HOT     },
    { label: "Information · stay",   value: 4140, color: CA_ROSE    },
    { label: "Upsell · upgrade",     value: 2960, color: CA_MAGENTA },
    { label: "Complaint · issue",    value: 1440, color: CA_PLUM    },
  ];

  const issued =   [620, 710, 820, 940, 1060, 1180, 1290, 1410, 1540, 1680, 1820, 1980];
  const handled =  [560, 660, 770, 890, 1010, 1130, 1240, 1360, 1490, 1630, 1770, 1930];

  const animRate = caAnimNum(94, 800);
  const liveActiveAI = caLiveNum(312, 3, 1600);

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 0.8fr", gap: 18 }}>
        <CACard title="Top intents" subtitle="LAST 30 DAYS · CONVERSATIONS">
          <CABarChart data={intents} format={v => v.toLocaleString()} />
        </CACard>

        <CACard title="Inbound vs AI-handled" subtitle="MESSAGES · LAST 12 MONTHS">
          <div style={{ height: 180 }}>
            <CAAreaChart data={issued} color={CA_FUCHSIA} height={180} secondary={handled} gid="caih" />
          </div>
          <div style={{
            display: "flex", justifyContent: "space-between",
            marginTop: 8, fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 10, color: CA_DIM,
          }}>
            <span>Jun</span><span>Jul</span><span>Aug</span><span>Sep</span>
            <span>Oct</span><span>Nov</span><span>Dec</span><span>Jan</span>
            <span>Feb</span><span>Mar</span><span>Apr</span><span>May</span>
          </div>
          <div style={{
            display: "flex", gap: 14, marginTop: 12,
            paddingTop: 10, borderTop: `1px solid ${CA_RULE_S}`,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 10, height: 10, borderRadius: 2, background: CA_FUCHSIA }} />
              <CAMono size={11} color={CA_MUTED}>Inbound</CAMono>
              <CAMono size={11.5} color={CA_FUCHSIA} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>15.9k</CAMono>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 10, height: 0, borderTop: `1.5px dashed ${CA_F_LIGHT}` }} />
              <CAMono size={11} color={CA_MUTED}>AI handled</CAMono>
              <CAMono size={11.5} color={CA_F_LIGHT} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>14.9k</CAMono>
            </div>
          </div>
        </CACard>

        <CACard title="AI resolution rate" subtitle="HANDLED / INBOUND · 30D">
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
            <CAGauge value={animRate} max={100} color={CA_FUCHSIA} />
            <div style={{
              display: "flex", justifyContent: "space-between", width: "100%",
              marginTop: 12, paddingTop: 10, borderTop: `1px solid ${CA_RULE_S}`,
            }}>
              <div>
                <CAMono size={9.5} color={CA_DIM} style={{ letterSpacing: "0.1em", textTransform: "uppercase" }}>ACTIVE NOW</CAMono>
                <div style={{ fontSize: 13.5, color: CA_F_LIGHT, marginTop: 2, fontFamily: "'JetBrains Mono', ui-monospace, monospace", fontVariantNumeric: "tabular-nums" }}>
                  {liveActiveAI} convos
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <CAMono size={9.5} color={CA_POS} style={{ letterSpacing: "0.1em", textTransform: "uppercase" }}>BENCHMARK</CAMono>
                <div style={{ fontSize: 13.5, color: CA_POS, marginTop: 2, fontWeight: 600 }}>↑ +12 pts</div>
              </div>
            </div>
          </div>
        </CACard>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 18 }}>
        <CACard title="Conversation funnel" subtitle="ALL CHANNELS · MESSAGE LIFECYCLE">
          <CAFunnel />
        </CACard>
        <CACard title="Intent health" subtitle="LIVE · ESCALATION & CSAT BY INTENT">
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {[
              { name: "Booking · modify",   esc:  3, cap: 100, color: CA_FUCHSIA, csat: 4.8 },
              { name: "Room service / F&B", esc:  4, cap: 100, color: CA_PINK,    csat: 4.7 },
              { name: "Spa & wellness",     esc:  6, cap: 100, color: CA_HOT,     csat: 4.7 },
              { name: "Information · stay", esc:  2, cap: 100, color: CA_ROSE,    csat: 4.9 },
              { name: "Upsell · upgrade",   esc:  8, cap: 100, color: CA_MAGENTA, csat: 4.5 },
              { name: "Complaint · issue",  esc: 34, cap: 100, color: CA_PLUM,    csat: 4.2 },
            ].map((r, i) => {
              const w = (r.esc / r.cap) * 100;
              const high = r.esc >= 25;
              return (
                <div key={i} style={{
                  display: "grid", gridTemplateColumns: "1.4fr 1fr auto auto",
                  gap: 12, alignItems: "center",
                  padding: "8px 0",
                  borderBottom: `1px solid ${CA_RULE_S}`,
                }}>
                  <div>
                    <div style={{ fontSize: 12.5, color: CA_INK, fontWeight: 500 }}>{r.name}</div>
                    <CAMono size={10} color={CA_DIM} style={{ marginTop: 2 }}>escalation rate</CAMono>
                  </div>
                  <div>
                    <div style={{ height: 5, background: CA_RULE_S, borderRadius: 3, overflow: "hidden" }}>
                      <div style={{
                        height: "100%", width: `${Math.max(w, 2)}%`,
                        background: high ? CA_NEG : r.color,
                        boxShadow: high ? `0 0 6px ${CA_NEG}80` : `0 0 6px ${r.color}60`,
                        transition: "width 0.6s ease",
                      }} />
                    </div>
                  </div>
                  <CAMono size={11} color={high ? CA_NEG : CA_MUTED} style={{ fontWeight: 600 }}>
                    {r.esc}%
                  </CAMono>
                  <CAMono size={11} color={CA_F_LIGHT} style={{ fontVariantNumeric: "tabular-nums", textAlign: "right" }}>
                    {r.csat.toFixed(1)} ★
                  </CAMono>
                </div>
              );
            })}
          </div>
        </CACard>
      </div>
    </div>
  );
}

function CAGauge({ value, max, color }) {
  const pct = value / max;
  const r = 70;
  const C = Math.PI * r;
  const off = C * (1 - pct);
  return (
    <div style={{ position: "relative", width: 180, height: 100, marginTop: 4 }}>
      <svg width="180" height="100" viewBox="0 0 180 100">
        <path d={`M 20 90 A 70 70 0 0 1 160 90`}
          fill="none" stroke={CA_RULE_S} strokeWidth="14" strokeLinecap="round" />
        <path d={`M 20 90 A 70 70 0 0 1 160 90`}
          fill="none" stroke={color} strokeWidth="14" strokeLinecap="round"
          strokeDasharray={C} strokeDashoffset={off}
          style={{
            transition: "stroke-dashoffset 0.8s cubic-bezier(.2,.8,.2,1)",
            filter: `drop-shadow(0 0 8px ${color}80)`,
          }} />
      </svg>
      <div style={{
        position: "absolute", inset: 0, display: "flex",
        flexDirection: "column", alignItems: "center", justifyContent: "flex-end",
        paddingBottom: 4,
      }}>
        <div style={{
          fontFamily: "'Source Serif 4', Georgia, serif",
          fontSize: 32, fontWeight: 500, color: CA_INK,
          letterSpacing: "-0.02em", lineHeight: 1,
        }}>{Math.round(value)}<span style={{ fontSize: 16, color: CA_DIM }}>%</span></div>
      </div>
    </div>
  );
}

function CAFunnel() {
  const stages = [
    { lbl: "Inbound messages",     val: 48_240, color: CA_FUCHSIA },
    { lbl: "Intent classified",    val: 47_120, color: CA_PINK    },
    { lbl: "AI drafted reply",     val: 46_180, color: CA_HOT     },
    { lbl: "Sent autonomously",    val: 44_948, color: CA_ROSE    },
    { lbl: "Escalated to human",   val:  3_292, color: CA_PLUM    },
  ];
  const max = Math.max(...stages.map(s => s.val));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {stages.map((s, i) => {
        const w = (s.val / max) * 100;
        return (
          <div key={i} style={{ animation: `gm-fadein 0.3s ease ${i * 0.05}s both` }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
              <span style={{ fontSize: 12.5, color: CA_INK, fontWeight: 500 }}>{s.lbl}</span>
              <CAMono size={11} color={s.color} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>
                {s.val.toLocaleString()}
              </CAMono>
            </div>
            <div style={{ height: 18, background: CA_PANEL_2, border: `1px solid ${CA_RULE_S}`, borderRadius: 4, overflow: "hidden", position: "relative" }}>
              <div style={{
                height: "100%", width: `${w}%`,
                background: `linear-gradient(90deg, ${s.color}, ${s.color}aa)`,
                boxShadow: `0 0 10px ${s.color}50`,
                transition: "width 0.7s cubic-bezier(.2,.8,.2,1)",
                position: "relative", overflow: "hidden",
              }}>
                <div style={{
                  position: "absolute", inset: 0,
                  background: "linear-gradient(90deg, transparent, rgba(255,255,255,0.18), transparent)",
                  animation: "gm-shimmer 3s ease-in-out infinite",
                }} />
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ────────────────────────── PROPERTIES ──────────────────────────
function CAPropertiesTab() {
  const props = [
    { name: "Sunset Beach",    loc: "Mallorca", contacts: 38420, msgs: 12_240, ai: 95.4, growth: 12.4, csat: 4.8, color: CA_FUCHSIA },
    { name: "Olea Cliffside",  loc: "Crete",    contacts: 32100, msgs:  9_980, ai: 94.1, growth:  8.6, csat: 4.7, color: CA_PINK    },
    { name: "Zafira Marina",   loc: "Ibiza",    contacts: 29840, msgs:  8_840, ai: 96.2, growth: 14.2, csat: 4.9, color: CA_HOT     },
    { name: "Casa Verde",      loc: "Algarve",  contacts: 24560, msgs:  7_280, ai: 92.8, growth:  6.1, csat: 4.6, color: CA_ROSE    },
    { name: "Sierra Lodge",    loc: "Andorra",  contacts: 18200, msgs:  5_410, ai: 91.4, growth:  4.8, csat: 4.5, color: CA_MAGENTA },
    { name: "Costa Blanca",    loc: "Alicante", contacts: 22600, msgs:  6_280, ai: 89.6, growth: -2.1, csat: 4.3, color: CA_F_LIGHT },
    { name: "Atlantic House",  loc: "Lisbon",   contacts: 18860, msgs:  4_840, ai: 93.7, growth: 10.3, csat: 4.7, color: CA_PLUM    },
  ];
  const maxContacts = Math.max(...props.map(p => p.contacts));
  const maxMsgs    = Math.max(...props.map(p => p.msgs));

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      <CACard title="Property comparison" subtitle="ALL PROPERTIES · MTD" padBody={false}>
        <div>
          <div style={{
            display: "grid",
            gridTemplateColumns: "1.4fr 1.2fr 1.4fr 0.9fr 0.8fr 0.7fr",
            gap: 18, padding: "10px 18px",
            borderBottom: `1px solid ${CA_RULE_S}`,
            background: CA_PANEL_2,
          }}>
            {["Property", "Contacts", "Messages · 30d", "AI rate", "Growth", "CSAT"].map((h, i) => (
              <CAMono key={h} size={10} color={CA_DIM} style={{
                letterSpacing: "0.1em", textTransform: "uppercase",
                textAlign: i >= 4 ? "right" : "left",
              }}>{h}</CAMono>
            ))}
          </div>
          {props.map((p, i) => {
            const wC = (p.contacts / maxContacts) * 100;
            const wM = (p.msgs / maxMsgs) * 100;
            return (
              <div key={p.name} style={{
                display: "grid",
                gridTemplateColumns: "1.4fr 1.2fr 1.4fr 0.9fr 0.8fr 0.7fr",
                gap: 18, padding: "12px 18px",
                borderBottom: i < props.length - 1 ? `1px solid ${CA_RULE_S}` : "none",
                alignItems: "center",
                animation: `gm-fadein 0.3s ease ${i * 0.04}s both`,
                transition: "background 0.18s ease",
              }} onMouseEnter={e => e.currentTarget.style.background = CA_PANEL_2}
                onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                <div>
                  <div style={{ fontSize: 13, color: CA_INK, fontWeight: 600 }}>{p.name}</div>
                  <CAMono size={10.5} color={CA_DIM} style={{ marginTop: 2 }}>{p.loc}</CAMono>
                </div>
                <div>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
                    <CAMono size={11} color={CA_MUTED} style={{ fontVariantNumeric: "tabular-nums" }}>{p.contacts.toLocaleString()}</CAMono>
                  </div>
                  <div style={{ height: 4, background: CA_RULE_S, borderRadius: 2, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: `${wC}%`, background: p.color, boxShadow: `0 0 6px ${p.color}60`, transition: "width 0.6s ease" }} />
                  </div>
                </div>
                <div>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
                    <CAMono size={11} color={CA_MUTED} style={{ fontVariantNumeric: "tabular-nums" }}>
                      {p.msgs.toLocaleString()}
                    </CAMono>
                  </div>
                  <div style={{ height: 4, background: CA_RULE_S, borderRadius: 2, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: `${wM}%`, background: CA_FUCHSIA, boxShadow: `0 0 6px ${CA_FUCHSIA}60`, transition: "width 0.6s ease" }} />
                  </div>
                </div>
                <CAMono size={11.5} color={p.ai >= 93 ? CA_F_LIGHT : CA_MUTED} style={{ fontWeight: 600, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{p.ai.toFixed(1)}%</CAMono>
                <CAMono size={11.5} color={p.growth >= 0 ? CA_POS : CA_NEG} style={{ fontWeight: 600, textAlign: "right" }}>
                  {p.growth >= 0 ? "↑" : "↓"} {Math.abs(p.growth).toFixed(1)}%
                </CAMono>
                <CAMono size={11.5} color={CA_INK} style={{ fontWeight: 600, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>
                  {p.csat.toFixed(1)} ★
                </CAMono>
              </div>
            );
          })}
        </div>
      </CACard>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <CACard title="Cross-property contact reach" subtitle="GROUP-WIDE UNIFIED PROFILES">
          <div style={{
            fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontSize: 11, color: CA_MUTED, lineHeight: 1.6,
            marginBottom: 10,
          }}>
            <span style={{ color: CA_FUCHSIA }}>34%</span> of contacts have engaged with more
            than one property in the group within the last 12 months.
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {[
              { from: "Sunset Beach",    to: "Olea Cliffside",   v: 1820 },
              { from: "Zafira Marina",   to: "Sunset Beach",     v: 1640 },
              { from: "Casa Verde",      to: "Zafira Marina",    v: 1290 },
              { from: "Olea Cliffside",  to: "Atlantic House",   v:  980 },
              { from: "Costa Blanca",    to: "Sierra Lodge",     v:  740 },
            ].map((r, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "8px 10px",
                background: CA_PANEL_2, borderRadius: 4,
                border: `1px solid ${CA_RULE_S}`,
                animation: `gm-fadein 0.3s ease ${i * 0.05}s both`,
              }}>
                <CAMono size={11.5} color={CA_INK} style={{ flex: 1, fontWeight: 500 }}>{r.from}</CAMono>
                <CAMono size={10} color={CA_F_LIGHT}>→</CAMono>
                <CAMono size={11.5} color={CA_INK} style={{ flex: 1, fontWeight: 500 }}>{r.to}</CAMono>
                <CAMono size={11} color={CA_FUCHSIA} style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums", minWidth: 56, textAlign: "right" }}>
                  {r.v.toLocaleString()}
                </CAMono>
              </div>
            ))}
          </div>
        </CACard>

        <CACard title="Group rollup" subtitle="LAST 30 DAYS · ALL PROPERTIES">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10 }}>
            {[
              { lbl: "Unified contacts",  val: "184,580",  c: CA_FUCHSIA },
              { lbl: "Messages handled",  val: "48,240",   c: CA_PINK    },
              { lbl: "Avg AI rate",       val: "94.2%",    c: CA_MAGENTA },
              { lbl: "Avg first reply",   val: "8.4s",     c: CA_HOT     },
              { lbl: "Booking conv. lift",val: "+18.4%",   c: CA_F_LIGHT },
              { lbl: "Net CSAT",          val: "4.7 ★",    c: CA_ROSE    },
              { lbl: "Active journeys",   val: "26",       c: CA_PLUM    },
              { lbl: "Repeat contact rt.",val: "42%",      c: CA_FUCHSIA },
            ].map((s, i) => (
              <div key={i} style={{
                background: CA_PANEL_2, border: `1px solid ${CA_RULE_S}`,
                borderRadius: 6, padding: "12px 14px",
                animation: `gm-fadein 0.3s ease ${i * 0.04}s both`,
              }}>
                <CAMono size={9.5} color={CA_DIM} style={{ letterSpacing: "0.12em", textTransform: "uppercase", display: "block" }}>{s.lbl}</CAMono>
                <div style={{
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 18, fontWeight: 500, color: s.c,
                  marginTop: 4, fontVariantNumeric: "tabular-nums",
                  textShadow: `0 0 12px ${s.c}40`,
                }}>{s.val}</div>
              </div>
            ))}
          </div>
        </CACard>
      </div>
    </div>
  );
}

// ────────────────────────── MAIN ──────────────────────────
function CRMAnalyticsSection() {
  const [tab, setTab] = caUseState("overview");
  const [range, setRange] = caUseState("30d");

  const tabs = [
    { id: "overview",   label: "Overview" },
    { id: "contacts",   label: "Contacts" },
    { id: "channels",   label: "Channels" },
    { id: "ai",         label: "AI Performance" },
    { id: "properties", label: "Properties" },
  ];

  const Body = {
    overview:   CAOverviewTab,
    contacts:   CAContactsTab,
    channels:   CAChannelsTab,
    ai:         CAAITab,
    properties: CAPropertiesTab,
  }[tab];

  return (
    <section data-screen-label="CRM Analytics" style={{
      background: CA_BG, padding: "100px clamp(20px,4vw,48px) 120px",
      minHeight: "100vh", color: CA_INK,
      fontFamily: "'Inter', system-ui, sans-serif",
      position: "relative", overflow: "hidden",
    }}>
      <style>{`
        .ca-tab-scroll::-webkit-scrollbar { width: 6px; }
        .ca-tab-scroll::-webkit-scrollbar-track { background: transparent; }
        .ca-tab-scroll::-webkit-scrollbar-thumb {
          background: ${CA_RULE};
          border-radius: 3px;
        }
        .ca-tab-scroll::-webkit-scrollbar-thumb:hover { background: ${CA_FUCHSIA}66; }
      `}</style>
      {/* ambient glows */}
      <div style={{
        position: "absolute", top: -200, left: "18%", width: 600, height: 600,
        background: `radial-gradient(circle, ${CA_FUCHSIA}18, transparent 65%)`,
        pointerEvents: "none",
      }} />
      <div style={{
        position: "absolute", bottom: -200, right: "8%", width: 700, height: 700,
        background: `radial-gradient(circle, ${CA_MAGENTA}15, transparent 65%)`,
        pointerEvents: "none",
      }} />

      {/* header */}
      <div style={{ maxWidth: "var(--rail)", 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: CA_FUCHSIA, boxShadow: `0 0 8px ${CA_FUCHSIA}` }} />
          <CAEyebrow>CRM ANALYTICS</CAEyebrow>
        </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: CA_INK,
        }}>
          Every contact, every conversation,{" "}
          <span style={{
            fontStyle: "italic", color: CA_FUCHSIA, display: "block",
            textShadow: `0 0 30px ${CA_FUCHSIA}50`,
          }}>
            measured in real time.
          </span>
        </h1>
        <p style={{
          fontSize: 15, color: CA_MUTED, lineHeight: 1.65,
          maxWidth: 680, margin: "20px auto 0",
        }}>
          Unified profiles, channel performance, AI resolution, lifecycle segments
          and per-property breakdowns, all in one dashboard, refreshed live as
          messages land.
        </p>
      </div>

      {/* dashboard frame */}
      <ScaleFrame nativeWidth={1216} style={{ maxWidth: 1216, margin: "0 auto" }}>
      <div style={{
        maxWidth: "var(--rail)", margin: "0 auto",
        background: CA_PANEL,
        borderRadius: 14,
        border: `1px solid ${CA_RULE}`,
        boxShadow: `0 30px 80px -30px rgba(0,0,0,0.7), 0 0 60px -20px ${CA_FUCHSIA}25`,
        overflow: "hidden",
        position: "relative",
      }}>
        {/* tab bar */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "0 24px",
          borderBottom: `1px solid ${CA_RULE_S}`,
          background: `linear-gradient(180deg, ${CA_PANEL_2}, ${CA_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 ? CA_INK : CA_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: CA_FUCHSIA, borderRadius: 1,
                    boxShadow: `0 0 10px ${CA_FUCHSIA}`,
                  }} />
                )}
              </button>
            ))}
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{
              display: "flex", padding: 2, borderRadius: 999,
              background: CA_PANEL, border: `1px solid ${CA_RULE_S}`,
            }}>
              {["7d", "30d", "90d", "YTD"].map(r => (
                <button key={r} onClick={() => setRange(r)} style={{
                  padding: "5px 12px", borderRadius: 999,
                  background: range === r ? CA_FUCHSIA : "transparent",
                  color: range === r ? "#fff" : CA_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 ${CA_FUCHSIA}80` : "none",
                }}>{r}</button>
              ))}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{
                width: 7, height: 7, borderRadius: "50%",
                background: CA_POS, animation: "gm-dot-pulse 2s infinite",
              }} />
              <CAMono size={11} color={CA_POS}>Live</CAMono>
            </div>
          </div>
        </div>

        <div key={tab} className="ca-tab-scroll" style={{
          animation: "gm-fadein 0.3s ease",
          height: 920,
          overflowY: "auto",
          scrollbarWidth: "thin",
          scrollbarColor: `${CA_RULE} transparent`,
        }}>
          <Body />
        </div>

        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "12px 24px",
          background: CA_PANEL_2, borderTop: `1px solid ${CA_RULE_S}`,
        }}>
          <div style={{ display: "flex", gap: 18 }}>
            <CAMono size={10.5} color={CA_DIM}><span style={{ color: CA_FUCHSIA }}>●</span> snapshot · {range}</CAMono>
            <CAMono size={10.5} color={CA_DIM}><span style={{ color: CA_POS }}>●</span> sync · 2s ago</CAMono>
            <CAMono size={10.5} color={CA_DIM}><span style={{ color: CA_PINK }}>●</span> 7 properties</CAMono>
            <CAMono size={10.5} color={CA_DIM}><span style={{ color: CA_HOT }}>●</span> 9 channels</CAMono>
          </div>
          <CAMono size={10.5} color={CA_DIM}>Export · CSV · PDF · Schedule report</CAMono>
        </div>
      </div>
      </ScaleFrame>
    </section>
  );
}

window.CRMAnalyticsSection = CRMAnalyticsSection;
