import { Pitch } from './Pitch';
import { teamFlag } from '@/lib/teams';
import type { PassNetwork as PassNet } from '@/lib/types';

const surname = (name: string) => name.split(' ').slice(-1)[0] ?? name;

/** A team's passing shape (before its first substitution): nodes ∝ involvement,
 *  links ∝ completed passes between the pair. The team attacks right. */
export function PassNetwork({
  net,
  team,
  color = 'var(--app-accent)',
}: {
  net: PassNet;
  team: string;
  color?: string;
}) {
  const pos = new Map(net.players.map((p) => [p.player, p]));
  const maxPass = Math.max(...net.players.map((p) => p.passes), 1);
  const maxEdge = Math.max(...net.edges.map((e) => e.count), 1);

  return (
    <div>
      <div className="mb-2 flex items-center gap-2 text-sm font-medium text-ink">
        <span aria-hidden>{teamFlag(team)}</span> {team}
      </div>
      <Pitch className="w-full">
        {net.edges.map((e, i) => {
          const a = pos.get(e.a);
          const b = pos.get(e.b);
          if (!a || !b) return null;
          return (
            <line
              key={i}
              x1={a.x} y1={a.y} x2={b.x} y2={b.y}
              stroke={color}
              strokeOpacity={0.15 + 0.5 * (e.count / maxEdge)}
              strokeWidth={0.2 + 1.4 * (e.count / maxEdge)}
            />
          );
        })}
        {net.players.map((p) => (
          <g key={p.player}>
            <circle
              cx={p.x} cy={p.y} r={1.6 + 3.4 * (p.passes / maxPass)}
              fill={color} fillOpacity={0.85} stroke="var(--app-surface)" strokeWidth={0.4}
            >
              <title>{`${p.player} · ${p.passes} passes`}</title>
            </circle>
            <text
              x={p.x} y={p.y - 3.6} textAnchor="middle"
              fontSize="2.6" fill="var(--app-ink)" stroke="var(--app-surface)" strokeWidth={0.5}
              paintOrder="stroke" style={{ fontWeight: 600 }}
            >
              {surname(p.player)}
            </text>
          </g>
        ))}
      </Pitch>
    </div>
  );
}
