import { useMemo } from 'react';
import { useT } from '@/lib/i18n';
import type { RichShot } from '@/lib/types';

interface Step {
  min: number;
  cum: number;
  goal: boolean;
  player: string;
  xg: number;
}

/** Cumulative xG step lines built from the captured shot list — home in accent,
 *  away in info. The line holds its level and jumps at each shot; goals are
 *  marked as dots on the line. */
export function XgRace({ shots, home, away }: { shots: RichShot[]; home: string; away: string }) {
  const t = useT();
  const W = 600;
  const H = 200;
  const PAD = { l: 34, r: 8, t: 8, b: 20 };

  const data = useMemo(() => {
    const usable = shots
      .filter((s): s is RichShot & { isHome: boolean; min: number; xg: number } => s.isHome != null && s.min != null && s.xg != null)
      .sort((a, b) => a.min - b.min);
    if (!usable.length) return null;

    const accumulate = (side: boolean): Step[] => {
      let cum = 0;
      return usable
        .filter((s) => s.isHome === side)
        .map((s) => {
          cum += s.xg;
          return { min: s.min, cum, goal: s.type === 'Goal', player: s.player, xg: s.xg };
        });
    };
    const homeSteps = accumulate(true);
    const awaySteps = accumulate(false);
    const homeTotal = homeSteps[homeSteps.length - 1]?.cum ?? 0;
    const awayTotal = awaySteps[awaySteps.length - 1]?.cum ?? 0;

    const maxMin = Math.max(90, usable[usable.length - 1]!.min);
    const maxXg = Math.max(homeTotal, awayTotal, 0.4) * 1.1;
    const x = (min: number) => PAD.l + (min / maxMin) * (W - PAD.l - PAD.r);
    const y = (c: number) => PAD.t + (1 - c / maxXg) * (H - PAD.t - PAD.b);

    // stepAfter: hold the level, jump at each shot, then run out to maxMin.
    const path = (steps: Step[]) => {
      let d = `M ${x(0).toFixed(1)},${y(0).toFixed(1)}`;
      let prev = 0;
      for (const s of steps) {
        d += ` L ${x(s.min).toFixed(1)},${y(prev).toFixed(1)} L ${x(s.min).toFixed(1)},${y(s.cum).toFixed(1)}`;
        prev = s.cum;
      }
      d += ` L ${x(maxMin).toFixed(1)},${y(prev).toFixed(1)}`;
      return d;
    };
    const goalDots = (steps: Step[], isHome: boolean) =>
      steps.filter((s) => s.goal).map((s) => ({ px: x(s.min), py: y(s.cum), isHome, label: `${s.player} ${s.min}' · xG ${s.xg.toFixed(2)}` }));

    const ticks = [0, 15, 30, 45, 60, 75, 90].filter((m) => m <= maxMin).map((m) => ({ m, px: x(m) }));
    const yStep = maxXg > 3 ? 1 : maxXg > 1.2 ? 0.5 : 0.25;
    const yTicks: { py: number; label: string }[] = [];
    for (let v = yStep; v < maxXg; v += yStep) yTicks.push({ py: y(v), label: String(+v.toFixed(2)) });

    return {
      homePath: path(homeSteps),
      awayPath: path(awaySteps),
      goals: [...goalDots(homeSteps, true), ...goalDots(awaySteps, false)],
      ticks,
      yTicks,
    };
  }, [shots]);

  if (!data) return null;

  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} className="w-full" role="img" aria-label={`${t.match.xgRace}: ${home} / ${away}`}>
        <rect x={PAD.l} y={PAD.t} width={W - PAD.l - PAD.r} height={H - PAD.t - PAD.b} className="fill-[var(--app-elevated)]" rx={4} />
        {data.yTicks.map((yt) => (
          <g key={yt.label}>
            <line x1={PAD.l} x2={W - PAD.r} y1={yt.py} y2={yt.py} className="stroke-[var(--app-line)]" strokeWidth={1} />
            <text x={PAD.l - 4} y={yt.py + 3} textAnchor="end" className="fill-[var(--app-faint)] text-[10px]">{yt.label}</text>
          </g>
        ))}
        <path d={data.awayPath} fill="none" className="stroke-[var(--app-info)]" strokeWidth={2.5} />
        <path d={data.homePath} fill="none" className="stroke-[var(--app-accent)]" strokeWidth={2.5} />
        {data.goals.map((g, i) => (
          <circle key={i} cx={g.px} cy={g.py} r={4} className={`${g.isHome ? 'fill-[var(--app-accent)]' : 'fill-[var(--app-info)]'} stroke-[var(--app-panel)]`} strokeWidth={1.5}>
            <title>{g.label}</title>
          </circle>
        ))}
        {data.ticks.map(({ m, px }) => (
          <g key={m}>
            <line x1={px} x2={px} y1={H - PAD.b} y2={H - PAD.b + 4} className="stroke-[var(--app-line-strong)]" strokeWidth={1} />
            <text x={px} y={H - 6} textAnchor="middle" className="fill-[var(--app-faint)] text-[10px]">{m}'</text>
          </g>
        ))}
      </svg>
      <div className="mt-1.5 flex items-center justify-between text-[11px]">
        <span className="font-semibold text-accent">{home}</span>
        <span className="font-semibold text-info">{away}</span>
      </div>
    </div>
  );
}
