function ScannerScreen({ adminId }) {
  const { Badge, Button, Input } = window.TheUpperDeckDesignSystem_4d3294;
  const videoRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  const streamRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const pausedRef = React.useRef(false);
  const [error, setError] = React.useState('');
  const [ticket, setTicket] = React.useState(null);
  const [status, setStatus] = React.useState('idle'); // idle | found | already | notfound | confirming | done
  const [checking, setChecking] = React.useState(false);
  const [manualMode, setManualMode] = React.useState(false);
  const [manualCode, setManualCode] = React.useState('');
  const [manualError, setManualError] = React.useState('');

  React.useEffect(() => {
    if (manualMode) return;
    let active = true;
    navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }).then((stream) => {
      if (!active) { stream.getTracks().forEach((t) => t.stop()); return; }
      streamRef.current = stream;
      videoRef.current.srcObject = stream;
      videoRef.current.play();
      loop();
    }).catch(() => setError('Camera access denied or unavailable. Check your browser permissions.'));
    function loop() {
      rafRef.current = requestAnimationFrame(loop);
      if (pausedRef.current) return;
      const video = videoRef.current, canvas = canvasRef.current;
      if (!video || video.readyState !== video.HAVE_ENOUGH_DATA) return;
      canvas.width = video.videoWidth; canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const code = window.jsQR && window.jsQR(img.data, img.width, img.height);
      if (code && code.data) handleDecoded(code.data);
    }
    return () => { active = false; cancelAnimationFrame(rafRef.current); if (streamRef.current) streamRef.current.getTracks().forEach((t) => t.stop()); };
  }, [manualMode]);

  async function handleDecoded(qr) {
    pausedRef.current = true;
    const t = await window.fetchTicketByQr(qr);
    if (!t) { setStatus('notfound'); return; }
    setTicket(t);
    setStatus(t.status === 'checked_in' ? 'already' : 'found');
  }

  async function lookupByOrderRef(ref) {
    setManualError('');
    const t = await window.fetchTicketByOrderRef(ref.trim());
    if (!t) { setManualError('No ticket found for that order reference.'); return; }
    setTicket(t);
    setStatus(t.status === 'checked_in' ? 'already' : 'found');
  }

  function resume() { setTicket(null); setStatus('idle'); pausedRef.current = false; setManualCode(''); setManualError(''); }

  async function confirmCheckin() {
    setChecking(true);
    await window.checkinTicketByIdLive(ticket.ticket_id, adminId);
    setChecking(false);
    setStatus('done');
    setTimeout(resume, 1400);
  }

  function ResultPanel({ dark }) {
    return (
      <div style={dark ? { position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(14,34,71,0.92)' } : { borderRadius: 'var(--radius-lg)', padding: 24, background: 'var(--navy-900)', textAlign: 'center' }}>
        {status === 'notfound' && (
          <div style={{ textAlign: 'center', color: 'white' }}>
            <Badge tone="error">Not found</Badge>
            <div style={{ margin: '14px 0 20px', fontSize: 'var(--text-sm)' }}>{manualMode ? "No ticket matches that order reference." : "This QR code doesn't match any ticket."}</div>
            <Button onClick={resume}>{manualMode ? 'Try again' : 'Scan again'}</Button>
          </div>
        )}
        {status === 'already' && ticket && (
          <div style={{ textAlign: 'center', color: 'white' }}>
            <Badge tone="warning">Already checked in</Badge>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-xl)', margin: '14px 0 4px' }}>{ticket.attendee_first_name} {ticket.attendee_last_name}</div>
            <div style={{ fontSize: 'var(--text-sm)', color: 'rgba(255,255,255,0.7)', marginBottom: 20 }}>{ticket.sub_event_title}</div>
            <Button onClick={resume}>{manualMode ? 'Look up another' : 'Scan again'}</Button>
          </div>
        )}
        {status === 'found' && ticket && (
          <div style={{ textAlign: 'center', color: 'white', width: '100%' }}>
            {ticket.order_status !== 'paid' && <Badge tone="error">Order not verified as paid</Badge>}
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', margin: '14px 0 4px' }}>{ticket.attendee_first_name} {ticket.attendee_last_name}</div>
            <div style={{ fontSize: 'var(--text-sm)', color: 'rgba(255,255,255,0.7)', marginBottom: 24 }}>{ticket.sub_event_title}</div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
              <Button variant="secondary" onClick={resume}>Cancel</Button>
              <Button onClick={confirmCheckin} disabled={checking}>{checking ? 'Checking in…' : 'Confirm check-in'}</Button>
            </div>
          </div>
        )}
        {status === 'done' && (
          <div style={{ textAlign: 'center', color: 'white' }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--status-success)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px', fontSize: 28 }}>\u2713</div>
            <div style={{ fontWeight: 700 }}>Checked in</div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 480, margin: '0 auto' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-xl)', marginBottom: 6 }}>Check-in scanner</div>
      <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)', marginBottom: 16 }}>{manualMode ? 'Type the order reference to look up their ticket.' : "Point the camera at an attendee's ticket QR code."}</div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 12 }}>
        <button onClick={() => { setManualMode((m) => !m); resume(); }} style={{ border: 'none', background: 'none', color: 'var(--brand-primary)', fontSize: 'var(--text-sm)', fontWeight: 600, cursor: 'pointer', padding: 0 }}>{manualMode ? 'Use camera scanner instead' : 'Camera not working? Enter order reference'}</button>
      </div>

      {manualMode ? (
        <div>
          {status === 'idle' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <Input label="Order reference" value={manualCode} onChange={setManualCode} placeholder="e.g. the order ID from the receipt" />
              {manualError && <div style={{ fontSize: 'var(--text-sm)', color: 'var(--status-error)' }}>{manualError}</div>}
              <Button onClick={() => lookupByOrderRef(manualCode)} disabled={!manualCode.trim()}>Look up</Button>
            </div>
          )}
          {status !== 'idle' && <ResultPanel dark={false} />}
        </div>
      ) : (
        <div>
          {error && <div style={{ padding: 16, background: 'var(--status-error-bg)', color: 'var(--status-error)', borderRadius: 'var(--radius-md)', fontSize: 'var(--text-sm)' }}>{error}</div>}
          {!error && (
            <div style={{ position: 'relative', borderRadius: 'var(--radius-lg)', overflow: 'hidden', background: '#000', aspectRatio: '1/1' }}>
              <video ref={videoRef} muted playsInline style={{ width: '100%', height: '100%', objectFit: 'cover', display: status === 'idle' ? 'block' : 'none' }} />
              <canvas ref={canvasRef} style={{ display: 'none' }} />
              {status !== 'idle' && <ResultPanel dark={true} />}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
window.ScannerScreen = ScannerScreen;
