import { create } from 'qrcode';
import { cn } from '@/lib/cn';

/**
 * A real, scannable QR code drawn as one SVG path (no canvas, no client JS), so it renders
 * crisply at TV scale and in server components. Dark modules on a light quiet zone keep it
 * readable by every phone camera.
 */
export function QrCode({
  value,
  label,
  className,
  foreground = '#070b1f',
  background = '#ffffff',
}: {
  value: string;
  /** Accessible description, e.g. "QR code to join PintRush at The Anchor". */
  label: string;
  className?: string;
  foreground?: string;
  background?: string;
}) {
  const { modules } = create(value, { errorCorrectionLevel: 'M' });
  const size = modules.size;
  let d = '';
  for (let row = 0; row < size; row += 1) {
    for (let col = 0; col < size; col += 1) {
      if (modules.data[row * size + col]) d += `M${col} ${row}h1v1h-1z`;
    }
  }
  const quiet = 2;
  const box = size + quiet * 2;
  return (
    <svg
      viewBox={`${-quiet} ${-quiet} ${box} ${box}`}
      role="img"
      aria-label={label}
      shapeRendering="crispEdges"
      className={cn('block', className)}
    >
      <rect x={-quiet} y={-quiet} width={box} height={box} rx={1.5} fill={background} />
      <path d={d} fill={foreground} />
    </svg>
  );
}
