'use client';

import { useEffect, useState } from 'react';
import QRCode from 'qrcode';
import { cn } from '@/lib/cn';
import { useMessages } from '@/i18n/client';

/** Share-link QR for a participant's report. `path` is app-relative, e.g. /r/<token>. */
export function QrCode({ path, className }: { path: string; className?: string }) {
  const t = useMessages().chat;
  const [svg, setSvg] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    QRCode.toString(new URL(path, window.location.origin).toString(), {
      type: 'svg',
      margin: 0,
      errorCorrectionLevel: 'M',
      color: { dark: '#0B1222', light: '#FFFFFF' },
    }).then((s) => !cancelled && setSvg(s));
    return () => {
      cancelled = true;
    };
  }, [path]);

  return (
    <div
      role="img"
      aria-label={t.qrLabel}
      className={cn('aspect-square rounded-2xl bg-white p-4 [&>svg]:size-full', !svg && 'animate-pulse', className)}
      // Generated locally by the qrcode library from our own URL.
      dangerouslySetInnerHTML={svg ? { __html: svg } : undefined}
    />
  );
}

export function useShareUrl(path: string) {
  const [url, setUrl] = useState('');
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- origin is only known in the browser
    setUrl(new URL(path, window.location.origin).toString());
  }, [path]);
  return url;
}
