import type { TeamStanding } from '@pintrush/engine';
import { UsersIcon } from '@/components/ui/icons';
import { cn } from '@/lib/cn';
import { formatTeamScore } from '@/lib/tv/format';

/** Table standings: team score = mean points of members who answered (shown with members count). */
export function TeamStandings({
  title,
  teams,
  limit = 5,
  className,
  note,
  markSolos = false,
}: {
  title: string;
  teams: readonly TeamStanding[];
  limit?: number;
  className?: string;
  note?: string;
  /** On a merged tables-and-solos board, tag solo players so they read differently from tables. */
  markSolos?: boolean;
}) {
  if (teams.length === 0) return null;
  return (
    <section aria-label={title} className={cn('flex flex-col gap-[12px]', className)}>
      <h3 className="flex items-center gap-[12px] text-[22px] font-bold tracking-[0.18em] text-cyan-soft uppercase">
        <UsersIcon className="size-[28px]" />
        {title}
      </h3>
      <ol className="flex flex-col gap-[8px]">
        {teams.slice(0, limit).map((t) => (
          <li key={t.teamId} className={cn('flex h-[60px] items-center gap-[16px] rounded-[14px] px-[14px]', t.rank === 1 ? 'bg-cyan/12 ring-1 ring-cyan/40' : 'bg-raised/45')}>
            <span className="num grid size-[42px] shrink-0 place-items-center rounded-[10px] bg-raised font-display text-[22px] font-bold text-muted">{t.rank}</span>
            <span className="min-w-0 flex-1 truncate text-[28px] font-semibold">{t.name}</span>
            {!t.isSolo && (
              <span className="num shrink-0 text-[20px] text-subtle">
                {t.members} {t.members === 1 ? 'player' : 'players'}
              </span>
            )}
            {t.isSolo && markSolos && <span className="shrink-0 text-[18px] font-bold tracking-[0.14em] text-subtle uppercase">Solo</span>}
            <span className="num shrink-0 font-display text-[28px] font-bold">{formatTeamScore(t.score)}</span>
          </li>
        ))}
      </ol>
      {note && <p className="text-[18px] text-subtle">{note}</p>}
    </section>
  );
}
