/* FinPulse charts — hand-rolled responsive SVG. Exports to window. */
const { useRef, useState, useEffect, useLayoutEffect } = React;

// measure container width
function useWidth() {
  const ref = useRef(null);
  const [w, setW] = useState(600);
  useLayoutEffect(() => {
    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];
}

function buildPath(data, w, h, padTop, padBottom) {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const usableH = h - padTop - padBottom;
  const step = data.length > 1 ? w / (data.length - 1) : 0;
  const pts = data.map((v, i) => [i * step, padTop + usableH - ((v - min) / range) * usableH]);
  const line = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const area = `${line} L${pts[pts.length - 1][0]},${h - padBottom} L0,${h - padBottom} Z`;
  return { line, area, pts, min, max };
}

// ---------- Sparkline ----------
function Sparkline({ data, up, width = 80, height = 32, strokeWidth = 1.5 }) {
  const { line } = buildPath(data, width, height, 3, 3);
  const color = up ? 'var(--up)' : 'var(--down)';
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block', overflow: 'visible' }}>
      <path d={line} fill="none" stroke={color} strokeWidth={strokeWidth} strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}

// ---------- Area chart ----------
function AreaChart({ data, color = 'var(--accent)', height = 260, labels }) {
  const [ref, w] = useWidth();
  const [hover, setHover] = useState(null);
  const padTop = 12, padBottom = 26, padRight = 0;
  const cw = Math.max(w - padRight, 10);
  const { line, area, pts, min, max } = buildPath(data, cw, height, padTop, padBottom);
  const gid = 'ag-' + Math.round(min);
  const gridVals = [max, (max + min) / 2, min];
  const usableH = height - padTop - padBottom;

  function onMove(e) {
    const rect = ref.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const step = cw / (data.length - 1);
    let idx = Math.round(x / step);
    idx = Math.max(0, Math.min(data.length - 1, idx));
    setHover(idx);
  }
  const last = data.length;
  const xLabels = labels || ['9:15', '11:00', '12:45', '14:30', '15:30'];

  return (
    <div ref={ref} style={{ position: 'relative', width: '100%' }} onMouseMove={onMove} onMouseLeave={() => setHover(null)}>
      <svg width="100%" height={height} viewBox={`0 0 ${cw} ${height}`} preserveAspectRatio="none" style={{ display: 'block', overflow: 'visible' }}>
        <defs>
          <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.14" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        {gridVals.map((gv, i) => {
          const y = padTop + usableH - ((gv - min) / (max - min || 1)) * usableH;
          return <line key={i} x1="0" y1={y} x2={cw} y2={y} stroke="var(--chart-grid, #f1f5f9)" strokeWidth="1" strokeDasharray="3 3" />;
        })}
        <path d={area} fill={`url(#${gid})`} />
        <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
        {hover != null && (
          <g>
            <line x1={pts[hover][0]} y1={padTop} x2={pts[hover][0]} y2={height - padBottom} stroke="var(--border-strong)" strokeWidth="1" strokeDasharray="3 3" vectorEffect="non-scaling-stroke" />
            <circle cx={pts[hover][0]} cy={pts[hover][1]} r="4" fill={color} stroke="var(--bg-primary)" strokeWidth="2" />
          </g>
        )}
      </svg>
      {/* x axis labels */}
      <div style={{ display: 'flex', justifyContent: 'space-between', position: 'absolute', left: 0, right: 0, bottom: 4, fontSize: 11, color: 'var(--text-muted)', fontFamily: 'var(--font-body)', pointerEvents: 'none' }}>
        {xLabels.map((l, i) => <span key={i}>{l}</span>)}
      </div>
      {hover != null && (
        <div className="chart-tip" style={{
          left: Math.min(Math.max((pts[hover][0] / cw) * w, 8), w - 90),
          top: pts[hover][1] - 44,
        }}>
          <div className="ct-val">₹{data[hover].toLocaleString('en-IN')}</div>
          <div className="ct-date">{xLabels[Math.min(Math.floor(hover / data.length * xLabels.length), xLabels.length - 1)] || ''}</div>
        </div>
      )}
    </div>
  );
}

// ---------- Bar chart ----------
function BarChart({ data, height = 120, color = 'var(--accent)' }) {
  const [ref, w] = useWidth();
  const [hover, setHover] = useState(null);
  const max = Math.max(...data) || 1;
  const n = data.length;
  const gap = 3;
  const bw = (w - gap * (n - 1)) / n;
  const r = Math.min(4, bw / 2);
  return (
    <div ref={ref} style={{ width: '100%' }}>
      <svg width="100%" height={height} viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" style={{ display: 'block' }}>
        {data.map((v, i) => {
          const bh = Math.max((v / max) * (height - 4), 2);
          const x = i * (bw + gap);
          const y = height - bh;
          return (
            <path key={i}
              d={`M${x},${height} L${x},${y + r} Q${x},${y} ${x + r},${y} L${x + bw - r},${y} Q${x + bw},${y} ${x + bw},${y + r} L${x + bw},${height} Z`}
              fill={hover === i ? 'var(--accent)' : color}
              onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
            />
          );
        })}
      </svg>
    </div>
  );
}

Object.assign(window, { Sparkline, AreaChart, BarChart });
