import { Pitch } from './Pitch';
import { teamFlag } from '@/lib/teams';
import type { StoryViz } from '@/lib/types';

const r = (xg: number) => 1.3 + Math.sqrt(Math.max(0, xg)) * 4.2;

/** Both teams' shots on one pitch — home attacks right, away mirrored to attack
 *  left. Dot area ∝ xG; goals are filled and ringed. */
export function ShotMap({ viz }: { viz: StoryViz }) {
  const homeColor = 'var(--app-accent)';
  const awayColor = 'var(--app-info)';

  return (
    <div>
      <Pitch className="w-full">
        {viz.shots.map((s, i) => {
          const isHome = s.team === viz.home;
          const x = isHome ? s.x : 120 - s.x;
          const y = isHome ? s.y : 80 - s.y;
          const color = isHome ? homeColor : awayColor;
          return (
            <circle
              key={i}
              cx={x}
              cy={y}
              r={r(s.xg)}
              fill={color}
              fillOpacity={s.goal ? 0.95 : 0.18}
              stroke={color}
              strokeWidth={s.goal ? 0.8 : 0.5}
            >
              <title>{`${s.player} · ${s.minute}' · xG ${s.xg.toFixed(2)}${s.goal ? ' · GOAL' : ` · ${s.outcome}`}`}</title>
            </circle>
          );
        })}
      </Pitch>

      <div className="mt-3 flex flex-wrap items-center justify-between gap-3 text-sm">
        <span className="flex items-center gap-2">
          <span aria-hidden>{teamFlag(viz.away)}</span>
          <span className="font-medium text-info">{viz.away}</span>
          <span className="text-faint">← attacking</span>
        </span>
        <span className="flex items-center gap-3 text-xs text-muted">
          <span className="flex items-center gap-1">
            <span className="inline-block h-3 w-3 rounded-full bg-accent" /> goal
          </span>
          <span className="flex items-center gap-1">
            <span className="inline-block h-3 w-3 rounded-full border border-accent bg-accent/20" /> shot
          </span>
          <span>· dot size = xG</span>
        </span>
        <span className="flex items-center gap-2">
          <span className="text-faint">attacking →</span>
          <span className="font-medium text-accent">{viz.home}</span>
          <span aria-hidden>{teamFlag(viz.home)}</span>
        </span>
      </div>
    </div>
  );
}
