/* Sparkline with optional time x-axis.
   Loaded after charts.jsx so this replaces window.Sparkline.
   Time-label helper lives on window.sparkTimeLabels (charts.jsx). */

const { useMemo, useRef, useState, useEffect } = React;

function Sparkline({ values, height = 36, color = 'var(--gold)', fill = true, baseline, times }) {
  const wrapRef = useRef(null);
  const [w, setW] = useState(180);
  useEffect(() => {
    if (!wrapRef.current) return;
    const ro = new ResizeObserver(es => setW(es[0].contentRect.width));
    ro.observe(wrapRef.current);
    return () => ro.disconnect();
  }, []);

  const scaleLinear = window.scaleLinear;
  const showX = Array.isArray(times) && times.length >= 2 && values.length >= 2;
  const axisH = showX ? 16 : 0;
  const svgH  = height + axisH;
  const padL  = showX ? 4 : 1;
  const padR  = showX ? 4 : 1;
  const padT  = 2;
  const plotB = height - 2;

  const [mn, mx] = useMemo(() => {
    let mn = Infinity, mx = -Infinity;
    values.forEach(v => { if (v < mn) mn = v; if (v > mx) mx = v; });
    if (!isFinite(mn)) return [0, 1];
    return [mn, mx];
  }, [values]);

  const xs = scaleLinear([0, Math.max(1, values.length - 1)], [padL, w - padR]);
  const ys = scaleLinear([mn, mx], [plotB, padT]);

  let line = '';
  values.forEach((v, i) => { line += (i === 0 ? 'M' : 'L') + xs(i).toFixed(1) + ' ' + ys(v).toFixed(1) + ' '; });
  const area = line + `L${xs(values.length-1).toFixed(1)} ${plotB} L${xs(0).toFixed(1)} ${plotB} Z`;

  const baseY = baseline != null ? ys(baseline) : null;
  const xLabels = useMemo(
    () => showX && typeof window.sparkTimeLabels === 'function'
      ? window.sparkTimeLabels(times.slice(0, values.length))
      : [],
    [showX, times, values.length]
  );

  return (
    <div ref={wrapRef} style={{ width: '100%' }}>
      <svg width={w} height={svgH} style={{ display: 'block', overflow: 'visible' }}>
        {fill && <path d={area} fill={color} opacity="0.12" />}
        {baseY != null && <line x1={padL} x2={w - padR} y1={baseY} y2={baseY} stroke="var(--text-4)" strokeDasharray="2 3" opacity="0.5" />}
        <path className="chart-draw" pathLength="1" d={line} fill="none" stroke={color} strokeWidth="1.4" />
        {showX && (
          <>
            <line x1={padL} x2={w - padR} y1={height - 0.5} y2={height - 0.5} stroke="var(--border-soft)" />
            {xLabels.map((dl, i) => (
              <g key={'x'+i}>
                <line x1={xs(dl.i)} x2={xs(dl.i)} y1={height} y2={height + 3} stroke="var(--text-4)" />
                <text
                  x={xs(dl.i)} y={svgH - 3}
                  fontSize="9" fontFamily="var(--font-mono)" fill="var(--text-4)"
                  textAnchor={i === 0 ? 'start' : i === xLabels.length - 1 ? 'end' : 'middle'}
                >
                  {dl.label}
                </text>
              </g>
            ))}
          </>
        )}
      </svg>
    </div>
  );
}

Object.assign(window, { Sparkline });
