// pin.jsx — In-app PIN gate. Soft access control: deters casual visitors who
// somehow find the URL but don't know the PIN. Source-readable (anyone with
// the URL can fetch this file and see the constant), so it's not real auth —
// it's a friction layer for the URL+PIN sharing model. Trade-off: zero-friction
// for trusted users (PIN saved in localStorage, never asked again, including
// across PWA reinstalls when iOS preserves storage).
const PIN = '474441';
const UNLOCK_KEY = 'monthlyPlan.unlocked';

function PinGate({ children }) {
  const [unlocked, setUnlocked] = React.useState(() => {
    try { return localStorage.getItem(UNLOCK_KEY) === 'true'; } catch (_) { return false; }
  });
  const [entered, setEntered] = React.useState('');
  const [error, setError] = React.useState(false);

  if (unlocked) return children;

  const press = (digit) => {
    if (error || entered.length >= PIN.length) return;
    const next = entered + digit;
    setEntered(next);
    if (next.length === PIN.length) {
      if (next === PIN) {
        setTimeout(() => {
          try { localStorage.setItem(UNLOCK_KEY, 'true'); } catch (_) {}
          setUnlocked(true);
        }, 120);
      } else {
        setError(true);
        setTimeout(() => { setEntered(''); setError(false); }, 520);
      }
    }
  };
  const back = () => { if (!error) setEntered(entered.slice(0, -1)); };

  const Key = ({ label, onClick, ghost }) => (
    <button onClick={onClick} className="pressable" style={{
      width: 72, height: 72, borderRadius: 36,
      background: ghost ? 'transparent' : tokens.card,
      border: ghost ? 'none' : `1px solid ${tokens.divider}`,
      color: tokens.ink, fontFamily: tokens.serif, fontSize: 28, fontWeight: 400,
      letterSpacing: -0.5, cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      WebkitTapHighlightColor: 'transparent',
    }}>{label}</button>
  );

  return (
    <div className="page-in" style={{
      position: 'absolute', inset: 0, background: tokens.paper,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '40px 28px', zIndex: 100,
    }}>
      <div style={{
        fontFamily: tokens.serif, fontSize: 38, color: tokens.ink, letterSpacing: -0.6,
      }}>Monthly Plan</div>
      <div style={{
        fontFamily: tokens.sans, fontSize: 13, color: tokens.ink3, marginTop: 8,
        letterSpacing: 0.4, textTransform: 'uppercase',
      }}>Enter PIN</div>

      <div className={error ? 'shake' : ''} style={{
        display: 'flex', gap: 14, marginTop: 28, marginBottom: 36,
      }}>
        {Array.from({ length: PIN.length }).map((_, i) => (
          <div key={i} style={{
            width: 12, height: 12, borderRadius: 6,
            background: i < entered.length
              ? (error ? tokens.bad : tokens.ink)
              : 'transparent',
            border: `1.5px solid ${error ? tokens.bad : (i < entered.length ? tokens.ink : tokens.divider)}`,
            transition: 'background 160ms, border-color 160ms',
          }}/>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 72px)', gap: 14 }}>
        {[1,2,3,4,5,6,7,8,9].map(d => <Key key={d} label={d} onClick={() => press(String(d))} />)}
        <span/>
        <Key label="0" onClick={() => press('0')} />
        <Key label="⌫" ghost onClick={back} />
      </div>
    </div>
  );
}

Object.assign(window, { PinGate });
