/* ===== ArbitrajZ — Sparkline (the hero) + brand mark ===== */
const { useState, useRef, useEffect, useMemo } = React;

/* The radar mark, reused from the ArbitrajZ favicon. `live` adds a slow sweep. */
function RadarMark({ size = 30, live = false, glow = false }) {
  const uid = useMemo(() => "rm" + Math.random().toString(36).slice(2, 7), []);
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ display: "block" }}>
      <defs>
        <linearGradient id={uid + "tile"} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#16202b" />
          <stop offset="1" stopColor="#0a0e14" />
        </linearGradient>
        <linearGradient id={uid + "ring"} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#2DEDA8" />
          <stop offset="1" stopColor="#0E9A63" />
        </linearGradient>
        <linearGradient id={uid + "sw"} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#27EAA4" stopOpacity=".55" />
          <stop offset="1" stopColor="#27EAA4" stopOpacity="0" />
        </linearGradient>
      </defs>
      <rect x="2" y="2" width="96" height="96" rx="26" fill={`url(#${uid}tile)`} />
      <rect x="3" y="3" width="94" height="94" rx="25" fill="none" stroke="rgba(39,234,164,.32)" strokeWidth="1.6" />
      <circle cx="50" cy="50" r="31" fill="#06140e" stroke={`url(#${uid}ring)`} strokeWidth="2.4" />
      <circle cx="50" cy="50" r="19" fill="none" stroke="#27EAA4" strokeWidth="1.2" opacity=".32" />
      <line x1="19" y1="50" x2="81" y2="50" stroke="#27EAA4" strokeWidth="1.1" opacity=".24" />
      <line x1="50" y1="19" x2="50" y2="81" stroke="#27EAA4" strokeWidth="1.1" opacity=".24" />
      <g style={live ? { transformOrigin: "50% 50%", animation: "arbz-sweep 4.4s linear infinite" } : undefined}>
        <path d="M50 50 L50 19 A31 31 0 0 1 79 39 Z" fill={`url(#${uid}sw)`} />
      </g>
      <circle cx="65" cy="36" r="4" fill="#5dffc0" />
    </svg>
  );
}

/*
  Sparkline — funding-rate path with a visible ZERO baseline.
  Above the baseline = short earns; a crossing below = a negative-funding event.
  Stable series read as a calm flat line; volatile ones visibly stab below zero.
*/
function Sparkline({ series, width = 224, height = 60, stable }) {
  const uid = useMemo(() => "sp" + Math.random().toString(36).slice(2, 7), []);
  const padY = 9;
  const stroke = stable ? "#2EE6A6" : "#F5B544";

  const geom = useMemo(() => {
    const max = Math.max(...series, 0);
    const min = Math.min(...series, 0);
    const span = max - min || 1;
    const x = (i) => (i / (series.length - 1)) * (width - 2) + 1;
    const y = (v) => padY + (1 - (v - min) / span) * (height - padY * 2);
    const zeroY = y(0);
    const pts = series.map((v, i) => [x(i), y(v), v]);
    const line = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
    const area = `M${pts[0][0].toFixed(1)} ${zeroY.toFixed(1)} ` +
      pts.map((p) => "L" + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ") +
      ` L${pts[pts.length - 1][0].toFixed(1)} ${zeroY.toFixed(1)} Z`;
    const negs = pts.filter((p) => p[2] < 0);
    return { pts, line, area, zeroY, negs, last: pts[pts.length - 1] };
  }, [series, width, height]);

  const [hover, setHover] = useState(null);

  return (
    <svg
      width={width}
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      style={{ display: "block", overflow: "visible" }}
      onMouseLeave={() => setHover(null)}
      onMouseMove={(e) => {
        const r = e.currentTarget.getBoundingClientRect();
        const rel = (e.clientX - r.left) / r.width * width;
        let best = 0, bd = 1e9;
        geom.pts.forEach((p, i) => { const d = Math.abs(p[0] - rel); if (d < bd) { bd = d; best = i; } });
        setHover(best);
      }}
    >
      <defs>
        <linearGradient id={uid + "fill"} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={stroke} stopOpacity={stable ? ".20" : ".16"} />
          <stop offset="1" stopColor={stroke} stopOpacity="0" />
        </linearGradient>
      </defs>

      {/* zero baseline — the reference that makes "negative" legible */}
      <line x1="1" y1={geom.zeroY} x2={width - 1} y2={geom.zeroY}
        stroke="#3a4456" strokeWidth="1" strokeDasharray="2 3" />
      <text x="1" y={geom.zeroY - 4} fill="#5A6276"
        style={{ font: "600 8px 'JetBrains Mono', monospace", letterSpacing: ".04em" }}>0</text>

      <path d={geom.area} fill={`url(#${uid}fill)`} />
      <path d={geom.line} fill="none" stroke={stroke} strokeWidth="1.9"
        strokeLinejoin="round" strokeLinecap="round" />

      {/* mark the negative-funding events on the volatile lines */}
      {geom.negs.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r="2.6" fill="#0a0e14" stroke="#FF5C6C" strokeWidth="1.4" />
      ))}

      {/* live end-point */}
      <circle cx={geom.last[0]} cy={geom.last[1]} r="3" fill={stroke} />
      <circle cx={geom.last[0]} cy={geom.last[1]} r="3" fill="none" stroke={stroke} strokeOpacity=".35" strokeWidth="3">
        <animate attributeName="r" from="3" to="8" dur="2.4s" repeatCount="indefinite" />
        <animate attributeName="stroke-opacity" from=".35" to="0" dur="2.4s" repeatCount="indefinite" />
      </circle>

      {/* hover readout */}
      {hover != null && (() => {
        const p = geom.pts[hover];
        const tx = Math.min(Math.max(p[0], 26), width - 26);
        return (
          <g pointerEvents="none">
            <line x1={p[0]} y1="2" x2={p[0]} y2={height - 2} stroke="#3a4456" strokeWidth="1" />
            <circle cx={p[0]} cy={p[1]} r="3.4" fill={p[2] < 0 ? "#FF5C6C" : stroke} stroke="#0a0e14" strokeWidth="1.5" />
            <rect x={tx - 24} y={p[1] - 22} width="48" height="15" rx="3" fill="#11161f" stroke="#262e3d" />
            <text x={tx} y={p[1] - 11.5} textAnchor="middle"
              fill={p[2] < 0 ? "#FF8089" : "#cdd4e0"}
              style={{ font: "600 8.5px 'JetBrains Mono', monospace" }}>
              {(p[2] >= 0 ? "+" : "") + p[2].toFixed(4) + "%"}
            </text>
          </g>
        );
      })()}
    </svg>
  );
}

window.RadarMark = RadarMark;
window.Sparkline = Sparkline;

/* Colorful candlestick mark — same rounded-tile chrome as the radar, but a
   green/red OHLC chart for a more "chart-forward" brand read. */
function ChartMark({ size = 32 }) {
  const uid = useMemo(() => "cm" + Math.random().toString(36).slice(2, 7), []);
  const G = "#2EE6A6", R = "#FF5C6C";
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ display: "block" }}>
      <defs>
        <linearGradient id={uid + "tile"} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#16202b" />
          <stop offset="1" stopColor="#0a0e14" />
        </linearGradient>
        <linearGradient id={uid + "gg"} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#5dffc0" />
          <stop offset="1" stopColor="#0FAE6E" />
        </linearGradient>
      </defs>
      <rect x="2" y="2" width="96" height="96" rx="26" fill={`url(#${uid}tile)`} />
      <rect x="3" y="3" width="94" height="94" rx="25" fill="none" stroke="rgba(46,230,166,.32)" strokeWidth="1.6" />
      {/* down candle */}
      <line x1="27" y1="40" x2="27" y2="74" stroke={R} strokeWidth="3.4" strokeLinecap="round" />
      <rect x="20" y="48" width="14" height="20" rx="3" fill={R} />
      {/* up candle (hero, tall) */}
      <line x1="50" y1="20" x2="50" y2="82" stroke={`url(#${uid}gg)`} strokeWidth="3.8" strokeLinecap="round" />
      <rect x="42" y="32" width="16" height="40" rx="3" fill={`url(#${uid}gg)`} />
      {/* up candle */}
      <line x1="73" y1="34" x2="73" y2="66" stroke={G} strokeWidth="3.4" strokeLinecap="round" />
      <rect x="66" y="42" width="14" height="18" rx="3" fill={G} />
    </svg>
  );
}

window.ChartMark = ChartMark;
