// LossChart — SVG line chart with hover crosshair, tooltip, and optional smoothing.
const { useState, useMemo, useRef, useEffect } = React;

function fmt(n, p = 4) {
  if (n == null || isNaN(n)) return '—';
  return n.toFixed(p);
}

function LossChart({ data, metric, palette }) {
  const showPoints = true;
  const showAnnotations = true;
  const W = 880,H = 440;
  const M = { t: 24, r: 24, b: 44, l: 60 };
  const iw = W - M.l - M.r;
  const ih = H - M.t - M.b;

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

  // Series selection
  const series = useMemo(() => {
    if (metric === 'loss') {
      return [
      { key: 'train', label: 'Training', color: palette.train, values: data.map((d) => d.train) },
      { key: 'val', label: 'Validation', color: palette.val, values: data.map((d) => d.val) }];

    }
    if (metric === 'acc') {
      return [{ key: 'acc', label: 'Accuracy', color: palette.train, values: data.map((d) => d.acc) }];
    }
    return [{ key: 'dice', label: 'Dice', color: palette.val, values: data.map((d) => d.dice) }];
  }, [data, metric, palette]);

  // No smoothing — render raw values directly. Keep `.smooth` field for downstream code.
  const smoothed = useMemo(
    () => series.map((s) => ({ ...s, smooth: s.values.slice() })),
    [series]
  );

  const xs = data.map((d) => d.epoch);
  const xMin = Math.min(...xs),xMax = Math.max(...xs);

  const allY = smoothed.flatMap((s) => s.smooth).concat(smoothed.flatMap((s) => s.values));
  let yMin, yMax;
  if (metric === 'loss') {
    yMin = 0;
    yMax = Math.max(...allY) * 1.05;
  } else {
    yMin = Math.min(...allY) * 0.98;
    yMax = 1;
  }

  const yLo = yMin;
  const yHi = yMax;

  const sx = (e) => M.l + (e - xMin) / (xMax - xMin) * iw;
  const sy = (v) => {
    const t = (v - yLo) / (yHi - yLo);
    return M.t + (1 - t) * ih;
  };

  const path = (vals) => vals.map((v, i) => `${i === 0 ? 'M' : 'L'} ${sx(xs[i]).toFixed(2)} ${sy(v).toFixed(2)}`).join(' ');
  const area = (vals) => `${path(vals)} L ${sx(xs[xs.length - 1]).toFixed(2)} ${(M.t + ih).toFixed(2)} L ${sx(xs[0]).toFixed(2)} ${(M.t + ih).toFixed(2)} Z`;

  // Ticks
  const xTicks = xs.filter((_, i) => i % 4 === 0 || i === xs.length - 1);
  const yTickCount = 6;
  const yTicks = Array.from({ length: yTickCount + 1 }, (_, i) => {
    const t = i / yTickCount;
    return yLo + t * (yHi - yLo);
  });

  // Best-epoch marker (min val loss / max metric)
  const annot = useMemo(() => {
    if (!showAnnotations) return null;
    if (metric === 'loss') {
      const arr = data.map((d) => d.val);
      const idx = arr.indexOf(Math.min(...arr));
      return { idx, label: 'Min val loss', value: arr[idx], series: 'val' };
    }
    const arr = data.map((d) => metric === 'acc' ? d.acc : d.dice);
    const idx = arr.indexOf(Math.max(...arr));
    return { idx, label: metric === 'acc' ? 'Peak accuracy' : 'Peak Dice', value: arr[idx], series: metric === 'acc' ? 'acc' : 'dice' };
  }, [data, metric, showAnnotations]);

  const onMove = (e) => {
    const rect = svgRef.current.getBoundingClientRect();
    const scaleX = W / rect.width;
    const x = (e.clientX - rect.left) * scaleX;
    const eF = xMin + (x - M.l) / iw * (xMax - xMin);
    const idx = Math.max(0, Math.min(xs.length - 1, Math.round(eF)));
    setHover(idx);
  };

  const yLabel = metric === 'loss' ? 'Loss' : metric === 'acc' ? 'Accuracy' : 'Dice coefficient';

  return (
    <div className="chart-wrap">
      <svg
        ref={svgRef}
        viewBox={`0 0 ${W} ${H}`}
        className="chart-svg"
        onMouseMove={onMove}
        onMouseLeave={() => setHover(null)}>
        
        <defs>
          <linearGradient id="grad-train" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor={palette.train} stopOpacity="0.18" />
            <stop offset="100%" stopColor={palette.train} stopOpacity="0" />
          </linearGradient>
          <linearGradient id="grad-val" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor={palette.val} stopOpacity="0.18" />
            <stop offset="100%" stopColor={palette.val} stopOpacity="0" />
          </linearGradient>
        </defs>

        {/* Grid */}
        {yTicks.map((v, i) =>
        <g key={'yt' + i}>
            <line x1={M.l} x2={W - M.r} y1={sy(v)} y2={sy(v)} className="grid" />
            <text x={M.l - 10} y={sy(v) + 4} textAnchor="end" className="ax-label">
              {metric === 'loss' ? v.toFixed(2) : v.toFixed(3)}
            </text>
          </g>
        )}
        {xTicks.map((e) =>
        <g key={'xt' + e}>
            <line x1={sx(e)} x2={sx(e)} y1={M.t} y2={H - M.b} className="grid grid-v" />
            <text x={sx(e)} y={H - M.b + 18} textAnchor="middle" className="ax-label">{e}</text>
          </g>
        )}

        {/* Y axis label */}
        <text transform={`translate(16 ${M.t + ih / 2}) rotate(-90)`} textAnchor="middle" className="axis-title">{yLabel}</text>
        <text x={M.l + iw / 2} y={H - 8} textAnchor="middle" className="axis-title">Epoch</text>

        {/* Optimum vertical line (rendered behind series so points sit on top) */}
        {annot && (() => {
          const optColor = palette.optimum || 'oklch(52% 0.17 145)';
          const x = sx(xs[annot.idx]);
          return (
            <g>
              <line x1={x} x2={x} y1={M.t} y2={H - M.b} stroke={optColor} strokeWidth="2.5" strokeOpacity="0.9" />
              <text x={x} y={M.t - 6} textAnchor="middle" className="opt-tag" fill={optColor}>epoch {xs[annot.idx]}</text>
            </g>);
        })()}

        {/* Series */}
        {smoothed.map((s) =>
        <g key={s.key}>
            {metric === 'loss' &&
          <path d={area(s.smooth)} fill={`url(#grad-${s.key === 'val' ? 'val' : 'train'})`} />
          }
            <path d={path(s.smooth)} fill="none" stroke={s.color} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
            {showPoints && s.smooth.map((v, i) =>
          <circle key={i} cx={sx(xs[i])} cy={sy(v)} r="3.2" fill={s.color} stroke="var(--bg)" strokeWidth="1.4" />
          )}
          </g>
        )}

        {/* Hover crosshair */}
        {hover != null &&
        <g>
            <line x1={sx(xs[hover])} x2={sx(xs[hover])} y1={M.t} y2={H - M.b} className="crosshair" />
            {smoothed.map((s) =>
          <circle key={s.key} cx={sx(xs[hover])} cy={sy(s.smooth[hover])} r="4.5" fill={s.color} stroke="var(--bg)" strokeWidth="2" />
          )}
          </g>
        }
      </svg>

      {/* Tooltip */}
      {hover != null && (() => {
        const d = data[hover];
        return (
          <div className="tip" style={{
            left: `${sx(xs[hover]) / W * 100}%`
          }}>
            <div className="tip-hd">Epoch {d.epoch} <span className="tip-time">· {d.time}</span></div>
            {metric === 'loss' &&
            <>
                <div className="tip-row"><span className="dot" style={{ background: palette.train }} />Training<b>{fmt(d.train)}</b></div>
                <div className="tip-row"><span className="dot" style={{ background: palette.val }} />Validation<b>{fmt(d.val)}</b></div>
              </>
            }
            {metric === 'acc' && <div className="tip-row"><span className="dot" style={{ background: palette.train }} />Accuracy<b>{fmt(d.acc)}</b></div>}
            {metric === 'dice' && <div className="tip-row"><span className="dot" style={{ background: palette.val }} />Dice<b>{fmt(d.dice)}</b></div>}
            <div className="tip-sub">acc {fmt(d.acc, 3)} · dice {fmt(d.dice, 3)}</div>
          </div>);

      })()}
    </div>);

}

window.LossChart = LossChart;
window.lossFmt = fmt;