// Chart mocks — synthetic, hand-tuned visuals that look like real orderflow studies.
// All SVG, no images. Used as product hero shots until user provides real screenshots.

const { useMemo } = React;

// ============== Volume Profile ==============
function VolumeProfileMock({ width = 720, height = 420, palette = 'green' }) {
  const acc = palette === 'green' ? '#00E599' : '#4D9CFF';
  // Generate candles
  const candles = useMemo(() => {
    let p = 5825;
    const arr = [];
    for (let i = 0; i < 60; i++) {
      const o = p;
      const c = p + (Math.sin(i * 0.4) + (Math.random() - 0.5) * 1.4) * 4;
      const h = Math.max(o, c) + Math.random() * 2.5;
      const l = Math.min(o, c) - Math.random() * 2.5;
      arr.push({ o, h, l, c });
      p = c;
    }
    return arr;
  }, []);

  const ymin = Math.min(...candles.map(c => c.l)) - 4;
  const ymax = Math.max(...candles.map(c => c.h)) + 4;
  const yToPx = (v) => 30 + ((ymax - v) / (ymax - ymin)) * (height - 60);

  // Volume profile bars
  const bins = 28;
  const profile = useMemo(() => {
    const arr = new Array(bins).fill(0);
    candles.forEach(c => {
      const mid = (c.h + c.l) / 2;
      const idx = Math.floor(((mid - ymin) / (ymax - ymin)) * bins);
      const range = c.h - c.l;
      arr[Math.max(0, Math.min(bins - 1, idx))] += range * 8 + Math.random() * 30;
    });
    const max = Math.max(...arr);
    return arr.map(v => v / max);
  }, [candles]);

  const profileX = width - 130;
  const profileW = 110;
  const pocIdx = profile.indexOf(Math.max(...profile));

  const candleW = (profileX - 50) / candles.length;

  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="vp-grid" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#0F1114" />
          <stop offset="1" stopColor="#0A0B0D" />
        </linearGradient>
        <linearGradient id="vp-bar" x1="0" x2="1" y1="0" y2="0">
          <stop offset="0" stopColor={acc} stopOpacity="0.55" />
          <stop offset="1" stopColor={acc} stopOpacity="0.15" />
        </linearGradient>
      </defs>
      <rect x="0" y="0" width={width} height={height} fill="url(#vp-grid)" />
      {/* horizontal grid */}
      {[0, 1, 2, 3, 4, 5].map(i => (
        <line key={i} x1="50" x2={profileX} y1={30 + (i * (height - 60) / 5)} y2={30 + (i * (height - 60) / 5)}
          stroke="rgba(255,255,255,0.04)" strokeWidth="1" />
      ))}
      {/* y axis labels */}
      {[0, 1, 2, 3, 4, 5].map(i => {
        const v = ymax - (i / 5) * (ymax - ymin);
        return <text key={i} x="44" y={34 + (i * (height - 60) / 5)} fill="#6E7682" fontSize="9" fontFamily="JetBrains Mono, monospace" textAnchor="end">{v.toFixed(2)}</text>;
      })}
      {/* candles */}
      {candles.map((c, i) => {
        const x = 50 + i * candleW + candleW * 0.15;
        const w = candleW * 0.7;
        const up = c.c >= c.o;
        const color = up ? '#00E599' : '#FF4D6A';
        return (
          <g key={i}>
            <line x1={x + w/2} x2={x + w/2} y1={yToPx(c.h)} y2={yToPx(c.l)} stroke={color} strokeWidth="1" opacity="0.7" />
            <rect x={x} y={yToPx(Math.max(c.o, c.c))} width={w} height={Math.max(1, Math.abs(yToPx(c.o) - yToPx(c.c)))} fill={color} opacity="0.85" />
          </g>
        );
      })}
      {/* Volume profile */}
      {profile.map((v, i) => {
        const y = 30 + (height - 60) - (i / bins) * (height - 60);
        const h = (height - 60) / bins - 1;
        const w = v * profileW;
        const isPoc = i === pocIdx;
        return (
          <g key={i}>
            <rect x={profileX} y={y - h} width={w} height={h} fill={isPoc ? acc : 'url(#vp-bar)'} opacity={isPoc ? 0.95 : 1} />
          </g>
        );
      })}
      {/* POC line */}
      <line x1="50" x2={profileX + profileW} y1={30 + (height - 60) - (pocIdx / bins) * (height - 60) - ((height - 60) / bins) / 2}
        y2={30 + (height - 60) - (pocIdx / bins) * (height - 60) - ((height - 60) / bins) / 2}
        stroke={acc} strokeWidth="1" strokeDasharray="3 3" opacity="0.7" />
      {/* labels */}
      <text x="60" y="22" fill="#E7EAEE" fontSize="11" fontFamily="JetBrains Mono, monospace" fontWeight="600">ES 03-26 · 1m</text>
      <text x="160" y="22" fill={acc} fontSize="11" fontFamily="JetBrains Mono, monospace">VP · POC 5832.25</text>
      <text x={profileX + 4} y={30 + (height - 60) - (pocIdx / bins) * (height - 60) - ((height - 60) / bins) / 2 - 4}
        fill={acc} fontSize="9" fontFamily="JetBrains Mono, monospace">POC</text>
    </svg>
  );
}

// ============== Gradient Map (delta heatmap) ==============
function GradientMapMock({ width = 720, height = 420 }) {
  const cols = 60, rows = 18;
  const cells = useMemo(() => {
    const arr = [];
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        // delta wave pattern
        const v = Math.sin(c * 0.18 + r * 0.3) * 0.5 +
                  Math.cos(c * 0.05 - r * 0.12) * 0.4 +
                  (Math.random() - 0.5) * 0.4;
        arr.push({ r, c, v: Math.max(-1, Math.min(1, v)) });
      }
    }
    return arr;
  }, []);

  const cw = (width - 100) / cols;
  const ch = (height - 60) / rows;

  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect x="0" y="0" width={width} height={height} fill="#0A0B0D" />
      {cells.map((cell, i) => {
        const x = 50 + cell.c * cw;
        const y = 30 + cell.r * ch;
        const intensity = Math.abs(cell.v);
        const color = cell.v > 0
          ? `rgba(0, 229, 153, ${intensity * 0.85})`
          : `rgba(255, 77, 106, ${intensity * 0.85})`;
        return <rect key={i} x={x} y={y} width={cw - 0.5} height={ch - 0.5} fill={color} />;
      })}
      {/* price line overlay */}
      <path d={`M 50 ${30 + (height-60)/2} ` +
        Array.from({length: cols}, (_, i) => {
          const x = 50 + i * cw + cw/2;
          const y = 30 + (height-60)/2 + Math.sin(i * 0.25) * 60 + Math.cos(i * 0.1) * 30;
          return `L ${x} ${y}`;
        }).join(' ')}
        stroke="#FFFFFF" strokeWidth="1.5" fill="none" opacity="0.85" />
      <text x="60" y="22" fill="#E7EAEE" fontSize="11" fontFamily="JetBrains Mono, monospace" fontWeight="600">NQ 03-26 · Δ Heatmap</text>
      <text x="220" y="22" fill="#00E599" fontSize="11" fontFamily="JetBrains Mono, monospace">+CVD 12,485</text>
      <text x="320" y="22" fill="#FF4D6A" fontSize="11" fontFamily="JetBrains Mono, monospace">-CVD 8,210</text>
    </svg>
  );
}

// ============== Order Book / DOM Ladder ==============
function OrderBookMock({ width = 360, height = 420, rows = 18 }) {
  const data = useMemo(() => {
    const arr = [];
    for (let i = 0; i < rows; i++) {
      const isAsk = i < rows / 2;
      const distance = isAsk ? (rows/2 - i) : (i - rows/2 + 1);
      const size = Math.floor(Math.random() * 800 + 80) * (1 + distance * 0.3);
      arr.push({
        price: 5832.50 - i * 0.25,
        size: Math.floor(size),
        isAsk,
      });
    }
    return arr;
  }, []);
  const maxSize = Math.max(...data.map(d => d.size));
  const rowH = (height - 50) / rows;

  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect x="0" y="0" width={width} height={height} fill="#0F1114" />
      <text x="14" y="22" fill="#E7EAEE" fontSize="11" fontFamily="JetBrains Mono, monospace" fontWeight="600">DOM · ES 03-26</text>
      <text x="14" y="40" fill="#6E7682" fontSize="9" fontFamily="JetBrains Mono, monospace">PRICE</text>
      <text x={width/2 - 20} y="40" fill="#6E7682" fontSize="9" fontFamily="JetBrains Mono, monospace">BID</text>
      <text x={width - 60} y="40" fill="#6E7682" fontSize="9" fontFamily="JetBrains Mono, monospace">ASK</text>
      {data.map((d, i) => {
        const y = 50 + i * rowH;
        const w = (d.size / maxSize) * (width / 2 - 20);
        const color = d.isAsk ? '#FF4D6A' : '#00E599';
        return (
          <g key={i}>
            {d.isAsk ? (
              <rect x={width - 14 - w} y={y} width={w} height={rowH - 1} fill={color} opacity="0.18" />
            ) : (
              <rect x="14" y={y} width={w} height={rowH - 1} fill={color} opacity="0.18" />
            )}
            <text x="14" y={y + rowH * 0.7} fill="#A2A9B4" fontSize="10" fontFamily="JetBrains Mono, monospace">{d.price.toFixed(2)}</text>
            <text x={d.isAsk ? width - 14 : width/2 - 12} y={y + rowH * 0.7}
              fill={color} fontSize="10" fontFamily="JetBrains Mono, monospace" textAnchor="end" fontWeight="500">{d.size.toLocaleString()}</text>
          </g>
        );
      })}
      {/* mid price separator */}
      <line x1="14" x2={width - 14} y1={50 + (rows/2) * rowH} y2={50 + (rows/2) * rowH} stroke="#262B33" strokeWidth="1" />
    </svg>
  );
}

// ============== CVD line ==============
function CVDMock({ width = 720, height = 200 }) {
  const points = useMemo(() => {
    let v = 0;
    return Array.from({ length: 80 }, (_, i) => {
      v += (Math.random() - 0.45) * 200 + Math.sin(i * 0.3) * 80;
      return v;
    });
  }, []);
  const min = Math.min(...points), max = Math.max(...points);
  const xStep = (width - 60) / (points.length - 1);
  const path = points.map((v, i) => {
    const x = 30 + i * xStep;
    const y = 30 + ((max - v) / (max - min)) * (height - 60);
    return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;
  }).join(' ');
  const last = points[points.length - 1];
  const lastY = 30 + ((max - last) / (max - min)) * (height - 60);

  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="cvd-fill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#00E599" stopOpacity="0.4" />
          <stop offset="1" stopColor="#00E599" stopOpacity="0" />
        </linearGradient>
      </defs>
      <rect x="0" y="0" width={width} height={height} fill="#0F1114" />
      <path d={`${path} L ${width - 30} ${height - 30} L 30 ${height - 30} Z`} fill="url(#cvd-fill)" />
      <path d={path} stroke="#00E599" strokeWidth="1.5" fill="none" />
      <circle cx={width - 30} cy={lastY} r="3" fill="#00E599" />
      <text x="14" y="20" fill="#E7EAEE" fontSize="10" fontFamily="JetBrains Mono, monospace" fontWeight="600">CVD · cumulative delta</text>
      <text x={width - 14} y="20" fill="#00E599" fontSize="10" fontFamily="JetBrains Mono, monospace" textAnchor="end" fontWeight="600">+{Math.round(last).toLocaleString()}</text>
    </svg>
  );
}

// Make global
Object.assign(window, { VolumeProfileMock, GradientMapMock, OrderBookMock, CVDMock });
