// screen-scan.jsx — In-app QR scan that redirects to the encoded swap URL.

function ScanScreen({ onNav }) {
  const { QRScanner } = window.PJ_UI || {};
  const [error, setError] = React.useState(null);

  const onResult = (text) => {
    if (!text) return;
    try {
      const url = new URL(text);
      const path = url.pathname + url.search;
      if (path.startsWith('/s/')) {
        onNav(path);
      } else {
        setError('That QR is not a Poker Jamie swap.');
      }
    } catch (e) {
      setError('Could not read that QR. Try again.');
    }
  };

  return (
    <div className="page" style={{ padding: '32px 20px 120px' }}>
      <div style={{ maxWidth: 440, margin: '0 auto', textAlign: 'center' }}>
        <div className="mono green" style={{ marginBottom: 14 }}>◆ Scan a Code</div>
        <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em', marginBottom: 10 }}>
          Point at the QR.
        </h2>
        <p className="text-2" style={{ marginBottom: 28, fontSize: 15 }}>
          Camera opens automatically. We'll jump you to the swap.
        </p>

        <div style={{
          width: '100%',
          aspectRatio: '1',
          borderRadius: 20,
          overflow: 'hidden',
          border: '1px solid var(--green-line)',
          boxShadow: '0 0 40px var(--green-glow), 0 0 80px var(--green-glow-2)',
          background: '#000'
        }}>
          {QRScanner ? <QRScanner onResult={onResult} onError={(e) => setError(String(e))} /> : (
            <div style={{ padding: 24, color: 'var(--text-3)' }}>Scanner unavailable</div>
          )}
        </div>

        {error && (
          <div style={{
            marginTop: 18,
            padding: '12px 16px',
            border: '1px solid rgba(255,59,92,0.4)',
            background: 'var(--red-soft)',
            color: '#ff8a9c',
            borderRadius: 10,
            fontFamily: 'var(--font-mono)',
            fontSize: 12,
            letterSpacing: '0.06em'
          }}>
            {error}
          </div>
        )}

        <button className="btn btn-secondary" style={{ marginTop: 28 }} onClick={() => onNav('/')}>
          Cancel
        </button>
      </div>
    </div>
  );
}

window.ScanScreen = ScanScreen;
