'use client';

import { useParams } from 'next/navigation';
import { CodeForm } from '../_lib/CodeForm';

/** The code from the URL, as the guest would type it (codes are case-insensitive, shown upper case). */
function triedCode(raw: string | string[] | undefined): string {
  const value = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '');
  let decoded = value;
  try {
    decoded = decodeURIComponent(value);
  } catch {
    // already decoded or malformed: show it as it is
  }
  return decoded.trim().toUpperCase();
}

/**
 * "We can't find that bar": say which code was tried and put it back in the field, focused, so an
 * O/0 mix-up is a one-character fix instead of a blind retype.
 */
export function MissingVenueForm() {
  const code = triedCode(useParams<{ venueCode: string }>()?.venueCode);
  return (
    <>
      <p className="mt-3 text-center text-muted">
        {code ? (
          <>
            No bar uses the code <span className="font-semibold break-all text-fg">“{code.slice(0, 24)}”</span>.
          </>
        ) : (
          'That game code doesn’t match any venue.'
        )}{' '}
        Scan the QR code on the TV again, or fix the code below — it’s shown under the QR code.
      </p>
      <div className="mt-8">
        <CodeForm defaultValue={code.slice(0, 12)} autoFocus />
      </div>
    </>
  );
}
