// Corridor Overview charts — hand-rolled SVG, restrained infra style.
// Hairline gridlines, tabular mono numerals, soft indigo fills, red
// denial bars. Tooltips render in the popover card style. 60fps; no
// 3D, no drop-shadows on bars, no legend clutter.
const D_chart = window.CorridorDemo;

// Measure a container's width so the SVG renders at true px (tooltips
// need real coordinates).
function useMeasure() {
  const ref = React.useRef(null);
  const [w, setW] = React.useState(720);
  React.useEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver((entries) => {
      const cw = entries[0].contentRect.width;
      if (cw > 0) setW(cw);
    });
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);
  return [ref, w];
}

const reduceMotion = () =>
  window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

// ── Spend over time + denied calls overlaid ───────────────────────
function SpendChart() {
  const { days, spend, denied } = D_chart.series;
  const [ref, W] = useMeasure();
  const [hover, setHover] = React.useState(null);
  const H = 188, padL = 14, padR = 14, padT = 18, padB = 30;
  const plotW = Math.max(W - padL - padR, 10);
  const plotH = H - padT - padB;
  const n = days.length;
  const spendMax = Math.max(...spend) * 1.18;
  const denMax = Math.max(...denied, 1);
  const xFor = (i) => padL + (n === 1 ? 0 : (i / (n - 1)) * plotW);
  const yFor = (v) => padT + plotH - (v / spendMax) * plotH;
  const barH = (v) => (v / denMax) * (plotH * 0.42);

  const linePts = spend.map((v, i) => [xFor(i), yFor(v)]);
  const linePath = linePts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const areaPath = linePath + ` L ${xFor(n - 1).toFixed(1)} ${(padT + plotH).toFixed(1)} L ${xFor(0).toFixed(1)} ${(padT + plotH).toFixed(1)} Z`;
  const grids = [0, 0.25, 0.5, 0.75, 1];

  return (
    <div ref={ref} style={{ position: "relative", width: "100%" }}>
      <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} role="img"
        aria-label="Per-agent spend over the last 7 days, with denied calls overlaid.">
        {/* gridlines */}
        {grids.map((g, i) => {
          const y = padT + plotH - g * plotH;
          return <line key={i} x1={padL} y1={y} x2={W - padR} y2={y}
            stroke="var(--hairline)" strokeWidth="1" />;
        })}
        {/* y max label, mono */}
        <text x={padL} y={padT - 6} fontFamily="var(--font-mono)" fontSize="10.5"
          fill="var(--text-muted)">{D_chart.fmtUSD(Math.round(spendMax))}</text>

        {/* denial bars (red) at each day */}
        {denied.map((v, i) => {
          if (v === 0) return null;
          const bw = 9, h = barH(v);
          return <rect key={i} x={xFor(i) - bw / 2} y={padT + plotH - h} width={bw} height={h}
            rx="1.5" fill="var(--danger-ink)" opacity={hover === i ? 0.95 : 0.78} />;
        })}

        {/* spend area + line */}
        <path d={areaPath} fill="var(--brand)" opacity="0.12" />
        <path d={linePath} fill="none" stroke="var(--brand)" strokeWidth="2"
          strokeLinejoin="round" strokeLinecap="round"
          style={reduceMotion() ? undefined : { strokeDasharray: 1200, animation: "cor-draw 900ms var(--ease-out) forwards" }} />

        {/* hover guide + point */}
        {hover != null ? (
          <g>
            <line x1={xFor(hover)} y1={padT} x2={xFor(hover)} y2={padT + plotH}
              stroke="var(--brand)" strokeWidth="1" opacity="0.35" />
            <circle cx={xFor(hover)} cy={yFor(spend[hover])} r="4"
              fill="var(--surface-card)" stroke="var(--brand)" strokeWidth="2" />
          </g>
        ) : null}

        {/* dots */}
        {linePts.map((p, i) => (
          <circle key={i} cx={p[0]} cy={p[1]} r="2.4" fill="var(--brand)" />
        ))}

        {/* x labels, mono */}
        {days.map((d, i) => (
          <text key={i} x={xFor(i)} y={H - 10} textAnchor="middle"
            fontFamily="var(--font-mono)" fontSize="10.5" fill="var(--text-muted)">{d}</text>
        ))}

        {/* hover capture columns */}
        {days.map((d, i) => {
          const half = plotW / (n - 1) / 2;
          const x = xFor(i) - half;
          return <rect key={i} x={i === 0 ? 0 : x} y={padT}
            width={i === 0 || i === n - 1 ? half + padL : half * 2} height={plotH}
            fill="transparent" style={{ cursor: "crosshair" }}
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} />;
        })}
      </svg>

      {hover != null ? (
        <div style={{
          position: "absolute", left: xFor(hover), top: yFor(spend[hover]) - 12,
          transform: "translate(-50%, -100%)", pointerEvents: "none",
          background: "var(--surface-card)", border: "1px solid var(--hairline)",
          borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-md)",
          padding: "8px 11px", minWidth: 120, zIndex: 3,
        }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)", marginBottom: 4 }}>{days[hover]}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5 }}>
            <span style={{ width: 7, height: 7, borderRadius: 2, background: "var(--brand)" }}></span>
            <span style={{ color: "var(--text-muted)" }}>spend</span>
            <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--text-strong)" }}>{D_chart.fmtUSD(spend[hover])}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, marginTop: 3 }}>
            <span style={{ width: 7, height: 7, borderRadius: 2, background: "var(--danger-ink)" }}></span>
            <span style={{ color: "var(--text-muted)" }}>denied</span>
            <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontWeight: 600, color: denied[hover] ? "var(--danger-ink)" : "var(--text-muted)" }}>{denied[hover]}</span>
          </div>
        </div>
      ) : null}
    </div>
  );
}

// ── Two stat tiles — big mono numerals ────────────────────────────
function StatTile({ label, value, accent }) {
  return (
    <div style={{
      flex: 1, minWidth: 0, padding: "14px 16px", border: "1px solid var(--hairline)",
      borderRadius: "var(--radius-md)", background: "var(--surface-card)",
    }}>
      <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{label}</div>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 30, fontWeight: 600, letterSpacing: "-0.01em",
        fontVariantNumeric: "tabular-nums", marginTop: 4,
        color: accent === "danger" ? "var(--danger-ink)" : "var(--text-strong)",
      }}>{value}</div>
    </div>
  );
}

// ── Settlement funnel — authorized → captured → settled ───────────
function SettlementFunnel() {
  const f = D_chart.funnel;
  const max = f[0].count;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
      {f.map((row, i) => {
        const pct = (row.count / max) * 100;
        return (
          <div key={row.phase} style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 78, flexShrink: 0, fontSize: 12.5, color: "var(--text-muted)" }}>{row.phase}</span>
            <div style={{ flex: 1, height: 22, borderRadius: 5, background: "var(--surface-muted)", overflow: "hidden" }}>
              <div style={{
                width: pct + "%", height: "100%", borderRadius: 5,
                background: "var(--brand)", opacity: 0.16 + (f.length - i) * 0.08,
                transition: reduceMotion() ? "none" : "width 600ms var(--ease-out)",
              }}></div>
            </div>
            <span style={{ width: 46, flexShrink: 0, textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums", color: "var(--text-strong)" }}>{row.count}</span>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { SpendChart, StatTile, SettlementFunnel, useChartMeasure: useMeasure, reduceMotion });
