// rd-scanner.jsx — the hero action. Dark camera screen, arc brackets, fast lock.

function RdFauxQr({ size = 148 }) {
  // deterministic QR-ish pattern
  const cells = [];
  const n = 15;
  for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
    const inFinder = (x < 5 && y < 5) || (x > n - 6 && y < 5) || (x < 5 && y > n - 6);
    if (inFinder) continue;
    const v = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;
    if (v - Math.floor(v) > 0.52) cells.push(<rect key={x + '-' + y} x={x} y={y} width="1" height="1" fill="#0A2B22" />);
  }
  const finder = (fx, fy) => (
    <g key={fx + ',' + fy}>
      <rect x={fx} y={fy} width="5" height="5" fill="none" stroke="#0A2B22" strokeWidth="1" />
      <rect x={fx + 1.6} y={fy + 1.6} width="1.8" height="1.8" fill="#0A2B22" />
    </g>
  );
  return (
    <svg width={size} height={size} viewBox={`-1 -1 ${17} ${17}`} style={{ display: 'block' }}>
      <rect x="-1" y="-1" width="17" height="17" fill="#FFFFFF" rx="0.8" />
      {cells}{finder(0, 0)}{finder(10, 0)}{finder(0, 10)}
    </svg>
  );
}

// corner brackets with the shaka sweep — one corner gets the big arc
function RdBrackets({ state = 'seek' }) {
  const c = state === 'bad' ? RD.coral : state === 'lock' ? RD.teal : 'rgba(255,255,255,0.9)';
  const L = 46, R = 14, big = 40;
  const corner = (rot, sweep) => (
    <svg key={rot} width={L} height={L} viewBox={`0 0 ${L} ${L}`} style={{ transform: `rotate(${rot}deg)`, transition: 'all 140ms ease' }}>
      <path d={sweep ? `M ${L} 3 L ${big} 3 A ${big - 3} ${big - 3} 0 0 0 3 ${L}` : `M ${L} 3 L ${R} 3 Q 3 3 3 ${R} L 3 ${L}`}
        fill="none" stroke={c} strokeWidth="5" strokeLinecap="round" />
    </svg>
  );
  return (
    <div style={{ position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: '1fr 1fr', gridTemplateRows: '1fr 1fr' }}>
      <div style={{ justifySelf: 'start', alignSelf: 'start' }}>{corner(0, true)}</div>
      <div style={{ justifySelf: 'end', alignSelf: 'start' }}>{corner(90, false)}</div>
      <div style={{ justifySelf: 'start', alignSelf: 'end', gridRow: 2 }}>{corner(270, false)}</div>
      <div style={{ justifySelf: 'end', alignSelf: 'end', gridRow: 2 }}>{corner(180, false)}</div>
    </div>
  );
}

function RdScanner({ market = 'br', live = true, outcome = 'ok', staticState, onClose, onLocked, onTypeKey }) {
  const m = RD_MARKETS[market];
  // phase: seek → found → lock|bad
  const [phase, setPhase] = React.useState(staticState || 'seek');
  const [attempt, setAttempt] = React.useState(0);
  const [torch, setTorch] = React.useState(false);

  React.useEffect(() => {
    if (!live) return;
    setPhase('seek');
    const t1 = setTimeout(() => setPhase('found'), 1000);
    const t2 = setTimeout(() => setPhase(outcome === 'badqr' ? 'bad' : 'lock'), 1650);
    const t3 = outcome === 'ok' ? setTimeout(() => onLocked && onLocked(), 2250) : null;
    return () => { clearTimeout(t1); clearTimeout(t2); t3 && clearTimeout(t3); };
  }, [attempt, outcome, live]);

  const bState = phase === 'lock' ? 'lock' : phase === 'bad' ? 'bad' : 'seek';

  return (
    <RdScreen label="Scan" bg={RD.dark} grain={false} style={{ color: '#fff' }}>
      {/* camera vignette */}
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(90% 70% at 50% 42%, #12241D 0%, #071410 78%)', filter: torch ? 'brightness(1.9)' : 'none', transition: 'filter 160ms ease' }}></div>
      <RdGrain on={true} opacity={0.07} />

      <div style={{ position: 'relative', zIndex: 2, display: 'flex', flexDirection: 'column', height: '100%', padding: '64px 22px 40px' }}>
        {/* top bar */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <button onClick={onClose} aria-label="Close" style={{
            width: 46, height: 46, borderRadius: 'var(--r-chip)', border: '1.5px solid rgba(255,255,255,0.28)',
            background: 'rgba(255,255,255,0.08)', color: '#fff', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><IcX size={20} /></button>
          <button onClick={() => setTorch(v => !v)} aria-label="Torch" style={{
            width: 46, height: 46, borderRadius: 'var(--r-chip)',
            border: torch ? '1.5px solid #fff' : '1.5px solid rgba(255,255,255,0.28)',
            background: torch ? '#fff' : 'rgba(255,255,255,0.08)', color: torch ? RD.ink : '#fff', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 140ms ease',
          }}><IcBolt size={20} /></button>
        </div>

        <div className="rd-h1" style={{ fontSize: 27, color: '#fff', marginTop: 26 }}>{m.scanTitle}</div>
        <div className="rd-body" style={{ fontSize: 15, color: 'rgba(255,255,255,0.72)', marginTop: 6 }}>{m.scanHint}</div>

        {/* frame */}
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ position: 'relative', width: 258, height: 258 }}>
            <RdBrackets state={bState} />
            {(phase === 'found' || phase === 'lock' || phase === 'bad') && (
              <div style={{
                position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                animation: live ? 'rd-fade 160ms ease both' : 'none',
                filter: phase === 'bad' ? 'saturate(0.4)' : 'none', opacity: phase === 'bad' ? 0.55 : 1,
              }}>
                <div style={{ borderRadius: 'var(--r-chip)', overflow: 'hidden', outline: phase === 'lock' ? `4px solid ${RD.teal}` : 'none' }}>
                  <RdFauxQr />
                </div>
              </div>
            )}
            {phase === 'seek' && (
              <div style={{
                position: 'absolute', left: 12, right: 12, top: 14, height: 3, borderRadius: 2,
                background: RD.teal, boxShadow: `0 0 14px ${'#00D4AA'}`,
                animation: live ? 'rd-scan 1.5s ease-in-out infinite' : 'none',
              }}></div>
            )}
          </div>
        </div>

        {/* status / recovery — bad QR is first-class, calm, specific */}
        {phase === 'bad' ? (
          <div style={{ animation: live ? 'rd-rise 180ms ease both' : 'none' }}>
            <div style={{
              display: 'flex', gap: 12, alignItems: 'flex-start', padding: '15px 16px',
              background: 'rgba(255,255,255,0.07)', border: `1.5px solid rgba(255,107,107,0.55)`, borderRadius: 'var(--r-card)',
            }}>
              <IcX size={20} color={RD.coral} />
              <div>
                <div className="rd-h3" style={{ fontSize: 15.5, color: '#fff' }}>That's not a {m.railName} code</div>
                <div className="rd-body" style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.7)', marginTop: 3 }}>
                  Try the printed code by the till, or type the key instead.
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
              <RdButton kind="primary" style={{ minHeight: 56, fontSize: 17 }} onClick={() => setAttempt(a => a + 1)}
                icon={<IcRefresh size={19} color={RD.tealInk} />}>Rescan</RdButton>
              <RdButton kind="paper" onClick={onTypeKey} style={{ minHeight: 56, fontSize: 16, background: 'rgba(255,255,255,0.1)', color: '#fff', border: '1.5px solid rgba(255,255,255,0.3)' }}
                icon={<IcKeypad size={19} color="#fff" />}>Type key</RdButton>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <button onClick={onTypeKey} style={{
              display: 'flex', alignItems: 'center', gap: 9, padding: '13px 18px',
              background: 'rgba(255,255,255,0.08)', border: '1.5px solid rgba(255,255,255,0.28)',
              borderRadius: 'var(--r-btn)', color: '#fff', fontFamily: RD.ui, fontWeight: 600, fontSize: 15, cursor: 'pointer',
            }}><IcKeypad size={18} />Enter {m.railName} key</button>
            <RdRailSlot market={market} h={15} style={{ background: '#fff' }} />
          </div>
        )}
      </div>
    </RdScreen>
  );
}

Object.assign(window, { RdScanner, RdFauxQr, RdBrackets });
