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

/** Attack-momentum strip: one bar per sampled minute, up (accent) when the
 *  home side is pressing, down (info) for the away side, baseline at center. */
export function MomentumStrip({ points, home, away }: { points: MatchRich['momentum']; home: string; away: string }) {
  const t = useT();
  const W = 600;
  const H = 150;
  const PAD = { l: 6, r: 6, t: 6, b: 20 };

  const data = useMemo(() => {
    const pts = [...points].sort((a, b) => a.minute - b.minute);
    if (!pts.length) return null;
    const maxMin = Math.max(90, pts[pts.length - 1]!.minute);
    const maxAbs = Math.max(...pts.map((p) => Math.abs(p.value)), 1);
    const innerW = W - PAD.l - PAD.r;
    const halfH = (H - PAD.t - PAD.b) / 2;
    const mid = PAD.t + halfH;
    const x = (min: number) => PAD.l + (min / maxMin) * innerW;
    const barW = Math.max(1.5, (innerW / pts.length) * 0.65);
    const bars = pts
      .filter((p) => p.value !== 0)
      .map((p) => {
        const h = (Math.abs(p.value) / maxAbs) * halfH;
        return { x: x(p.minute) - barW / 2, y: p.value > 0 ? mid - h : mid, h, up: p.value > 0 };
      });
    const ticks = [45, 90].filter((m) => m <= maxMin).map((m) => ({ m, px: x(m) }));
    return { bars, barW, mid, ticks };
  }, [points]);

  if (!data) return null;

  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} className="w-full" role="img" aria-label={`${t.match.momentumTitle}: ${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.bars.map((b, i) => (
          <rect key={i} x={b.x} y={b.y} width={data.barW} height={b.h} className={b.up ? 'fill-[var(--app-accent)]' : 'fill-[var(--app-info)]'} opacity={0.85} />
        ))}
        <line x1={PAD.l} x2={W - PAD.r} y1={data.mid} y2={data.mid} className="stroke-[var(--app-line-strong)]" strokeWidth={1} />
        {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>
  );
}
