// Inline chart primitives — small SVG charts to match the editorial aesthetic.
// No external dependencies. Render at any size.

// Deterministic seedable pseudo-random for reproducible mock series
function seedRand(seed) {
  let s = seed;
  return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
}

// ─── Area / line chart ──────────────────────────────────────────────
function AreaChart({ data, height = 220, accent, comparison, labels = [] }) {
  const W = 800, H = height, pad = { t: 20, r: 16, b: 28, l: 44 };
  const innerW = W - pad.l - pad.r;
  const innerH = H - pad.t - pad.b;
  const max = Math.max(...data, ...(comparison || [0])) * 1.15 || 1;
  const x = (i) => pad.l + (i / (data.length - 1)) * innerW;
  const y = (v) => pad.t + innerH - (v / max) * innerH;
  const path = data.map((v, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${y(v)}`).join(" ");
  const fill = `${path} L ${x(data.length - 1)} ${pad.t + innerH} L ${x(0)} ${pad.t + innerH} Z`;
  const cmpPath = comparison ? comparison.map((v, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${y(v)}`).join(" ") : null;
  const ticks = 4;
  const accentCol = accent || "var(--accent)";
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ display: "block" }}>
      <defs>
        <linearGradient id="ac-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={accentCol} stopOpacity="0.22" />
          <stop offset="100%" stopColor={accentCol} stopOpacity="0" />
        </linearGradient>
      </defs>
      {[...Array(ticks)].map((_, i) => {
        const v = max * (i / (ticks - 1));
        const yy = y(v);
        return (
          <g key={i}>
            <line x1={pad.l} x2={W - pad.r} y1={yy} y2={yy} stroke="var(--border)" strokeWidth="1" strokeDasharray="2 4" />
            <text x={pad.l - 8} y={yy + 4} fill="var(--text-3)" fontSize="10" fontFamily="var(--mono)" textAnchor="end" letterSpacing="0.04em">
              {v >= 1000 ? `${(v / 1000).toFixed(1)}k` : Math.round(v)}
            </text>
          </g>
        );
      })}
      {cmpPath && <path d={cmpPath} stroke="var(--text-3)" strokeWidth="1.2" strokeDasharray="4 4" fill="none" />}
      <path d={fill} fill="url(#ac-fill)" />
      <path d={path} stroke={accentCol} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      {data.map((v, i) => i % Math.ceil(data.length / 8) === 0 && (
        <circle key={i} cx={x(i)} cy={y(v)} r="2.5" fill={accentCol} />
      ))}
      {labels.map((l, i) => i % Math.ceil(labels.length / 6) === 0 && (
        <text key={i} x={x(i)} y={H - 8} fill="var(--text-3)" fontSize="10" fontFamily="var(--mono)" textAnchor="middle" letterSpacing="0.04em">{l.toUpperCase()}</text>
      ))}
    </svg>
  );
}

// ─── Sparkline ──────────────────────────────────────────────────────
function Sparkline({ data, height = 36, color }) {
  const W = 120, H = height;
  const max = Math.max(...data) || 1;
  const min = Math.min(...data);
  const norm = (v) => (v - min) / (max - min || 1);
  const x = (i) => (i / (data.length - 1)) * W;
  const y = (v) => H - 2 - norm(v) * (H - 6);
  const path = data.map((v, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${y(v)}`).join(" ");
  const c = color || "var(--accent)";
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H} style={{ display: "block" }}>
      <path d={path} stroke={c} strokeWidth="1.6" fill="none" strokeLinecap="round" />
      <circle cx={x(data.length - 1)} cy={y(data[data.length - 1])} r="2.5" fill={c} />
    </svg>
  );
}

// ─── Bar chart (horizontal) ────────────────────────────────────────
function BarRow({ label, value, max, sub, accent }) {
  const pct = (value / max) * 100;
  return (
    <div style={{ padding: "12px 0", borderTop: "1px solid var(--border)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 6 }}>
        <span>{label}</span>
        <span style={{ display: "flex", gap: 12, fontFamily: "var(--mono)", color: "var(--text-3)", fontSize: 12 }}>
          {sub && <span>{sub}</span>}
          <span style={{ color: "var(--text)" }}>{value}</span>
        </span>
      </div>
      <div style={{ height: 6, background: "var(--surface-2)", borderRadius: 2, overflow: "hidden" }}>
        <div style={{ height: "100%", width: `${pct}%`, background: accent || "var(--accent)", transition: "width 0.6s ease" }} />
      </div>
    </div>
  );
}

// ─── Donut ─────────────────────────────────────────────────────────
function Donut({ data, size = 200, thickness = 28 }) {
  const r = size / 2;
  const inner = r - thickness;
  const total = data.reduce((s, d) => s + d.value, 0);
  let cum = 0;
  const colors = [
    "var(--accent)", "color-mix(in oklab, var(--accent) 70%, var(--text))",
    "var(--text)", "color-mix(in oklab, var(--text) 70%, var(--text-3))",
    "var(--text-3)", "var(--border-strong)", "var(--border)",
  ];
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
      {data.map((d, i) => {
        const startA = (cum / total) * Math.PI * 2 - Math.PI / 2;
        cum += d.value;
        const endA = (cum / total) * Math.PI * 2 - Math.PI / 2;
        const large = endA - startA > Math.PI ? 1 : 0;
        const x1 = r + r * Math.cos(startA), y1 = r + r * Math.sin(startA);
        const x2 = r + r * Math.cos(endA),   y2 = r + r * Math.sin(endA);
        const x3 = r + inner * Math.cos(endA),   y3 = r + inner * Math.sin(endA);
        const x4 = r + inner * Math.cos(startA), y4 = r + inner * Math.sin(startA);
        const path = `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} L ${x3} ${y3} A ${inner} ${inner} 0 ${large} 0 ${x4} ${y4} Z`;
        return <path key={i} d={path} fill={d.color || colors[i % colors.length]} stroke="var(--bg)" strokeWidth="2" />;
      })}
      <text x={r} y={r - 4} fontSize="11" fontFamily="var(--mono)" fill="var(--text-3)" textAnchor="middle" letterSpacing="0.1em">TOTAL</text>
      <text x={r} y={r + 18} fontSize="22" fontFamily="var(--serif)" fontStyle="italic" fill="var(--text)" textAnchor="middle">{total.toLocaleString()}</text>
    </svg>
  );
}

// ─── Funnel ────────────────────────────────────────────────────────
function Funnel({ stages }) {
  const max = Math.max(...stages.map(s => s.value));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      {stages.map((s, i) => {
        const pct = (s.value / max) * 100;
        const drop = i > 0 ? Math.round(((stages[i - 1].value - s.value) / stages[i - 1].value) * 100) : null;
        return (
          <div key={i} style={{ position: "relative", display: "flex", gap: 16, alignItems: "center" }}>
            <div style={{ width: 110, fontSize: 13, color: "var(--text-2)" }}>{s.label}</div>
            <div style={{ flex: 1, height: 40, position: "relative" }}>
              <div style={{
                height: "100%", width: `${pct}%`,
                background: `linear-gradient(90deg, var(--accent), color-mix(in oklab, var(--accent) 60%, transparent))`,
                borderRadius: 4,
                display: "flex", alignItems: "center", paddingLeft: 14,
                fontFamily: "var(--mono)", fontSize: 12, color: "var(--accent-fg)", fontWeight: 600,
                transition: "width 0.6s ease",
              }}>
                {s.value.toLocaleString()}
              </div>
              {drop != null && (
                <span style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", fontFamily: "var(--mono)", fontSize: 11, color: drop > 30 ? "var(--danger, #d97757)" : "var(--text-3)", letterSpacing: "0.06em" }}>
                  −{drop}%
                </span>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Cohort heatmap ────────────────────────────────────────────────
function CohortGrid({ rows, cols }) {
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: `120px repeat(${cols.length}, 1fr)`, gap: 4, marginBottom: 6 }}>
        <span />
        {cols.map((c, i) => (
          <span key={i} className="mono" style={{ fontSize: 10, color: "var(--text-3)", textAlign: "center", letterSpacing: "0.06em" }}>{c}</span>
        ))}
      </div>
      {rows.map((row, ri) => (
        <div key={ri} style={{ display: "grid", gridTemplateColumns: `120px repeat(${cols.length}, 1fr)`, gap: 4, marginBottom: 4 }}>
          <span className="mono" style={{ fontSize: 11, color: "var(--text-2)", letterSpacing: "0.04em", display: "flex", alignItems: "center" }}>{row.label}</span>
          {row.values.map((v, vi) => (
            <div key={vi} title={`${v}%`} style={{
              height: 30,
              background: v === null ? "transparent" : `color-mix(in oklab, var(--accent) ${Math.min(v, 100)}%, transparent)`,
              border: v === null ? "1px dashed var(--border)" : "1px solid var(--border)",
              borderRadius: 3,
              display: "flex", alignItems: "center", justifyContent: "center",
              fontFamily: "var(--mono)", fontSize: 11,
              color: v !== null && v > 30 ? "var(--accent-fg)" : "var(--text-2)",
            }}>{v === null ? "—" : `${v}%`}</div>
          ))}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { AreaChart, Sparkline, BarRow, Donut, Funnel, CohortGrid, seedRand });
