import type { ReactNode } from 'react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';

export type StatTone = 'default' | 'positive' | 'warning' | 'danger' | 'info' | 'brand';

export interface Stat {
  /** Short. Two or three words; it sits above the number. */
  label: string;
  value: ReactNode;
  /** One clarifying line, shown under the number at a smaller size. */
  hint?: string;
  tone?: StatTone;
  /** Set when this number was derived under an edited reward, not recorded. */
  edited?: boolean;
}

export interface StatStripProps {
  stats: Stat[];
  className?: string;
  /** Announce changes as they happen. Off by default — the shell owns the
   *  page's single live region and two competing ones talk over each other. */
  live?: boolean;
}

const TONE: Record<StatTone, string> = {
  default: 'text-fg',
  positive: 'text-positive',
  warning: 'text-warning',
  danger: 'text-danger',
  info: 'text-info',
  brand: 'text-accent-fg',
};

/**
 * A row of headline numbers. Scrolls horizontally on a phone rather than
 * wrapping into a ragged grid: four stats reflowing to 2x2 at 390px puts the
 * least important number in the most prominent corner.
 */
export function StatStrip({ stats, className, live = false }: StatStripProps) {
  if (stats.length === 0) return null;
  return (
    <dl
      className={cn(
        'flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1',
        'sm:grid sm:snap-none sm:overflow-visible sm:pb-0',
        stats.length <= 2 ? 'sm:grid-cols-2' : 'sm:grid-cols-3 lg:grid-cols-4',
        className,
      )}
      {...(live ? { 'aria-live': 'polite' as const } : {})}
    >
      {stats.map((stat) => (
        <div
          key={stat.label}
          className="card min-w-[9.5rem] flex-1 shrink-0 snap-start px-4 py-3"
        >
          <dt className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-muted">
            <span className="truncate">{stat.label}</span>
            {stat.edited ? <EditedChip /> : null}
          </dt>
          <dd
            className={cn(
              'nums mt-1 text-2xl font-semibold leading-tight',
              TONE[stat.tone ?? 'default'],
            )}
          >
            {stat.value}
          </dd>
          {stat.hint ? <dd className="mt-0.5 text-xs text-muted">{stat.hint}</dd> : null}
        </div>
      ))}
    </dl>
  );
}

/**
 * Marks a number the visitor caused rather than one we recorded. It appears on
 * every derived value in the reward editor; without it, an edited ranking
 * screenshots identically to a measured one.
 */
export function EditedChip({ className }: { className?: string }) {
  return (
    <Badge className={cn('px-1.5 py-0 text-[10px] uppercase tracking-wide', className)}>
      edited
    </Badge>
  );
}
