const { useState, useEffect } = React;

// A 4-digit PIN gate shown after Google sign-in for an extra layer of privacy.
//   mode 'create' — set a brand-new PIN (entered, then confirmed)
//   mode 'enter'  — verify the existing PIN
// onComplete(pin) is awaited; in 'enter' mode it must resolve to a boolean
// (false → error shake). In 'create' mode the confirm step calls it once.
const PinScreen = ({ mode, neutralMode, onComplete, onSignOut, userEmail }) => {
  const LEN = 4;
  const [stage, setStage] = useState('first'); // create only: 'first' | 'confirm'
  const [firstPin, setFirstPin] = useState('');
  const [entry, setEntry] = useState('');
  const [error, setError] = useState('');
  const [shake, setShake] = useState(false);
  const [busy, setBusy] = useState(false);

  const fail = (msg) => {
    setError(msg); setShake(true); setEntry('');
    setTimeout(() => setShake(false), 500);
  };

  const submit = async (pin) => {
    if (busy) return;
    if (mode === 'create') {
      if (stage === 'first') {
        setFirstPin(pin); setEntry(''); setError(''); setStage('confirm');
        return;
      }
      if (pin !== firstPin) {
        setStage('first'); setFirstPin('');
        fail("PINs didn't match — start over");
        return;
      }
      setBusy(true);
      try { await onComplete(pin); } catch (e) { setBusy(false); fail('Could not save PIN'); }
      return;
    }
    // enter mode
    setBusy(true);
    let ok = false;
    try { ok = await onComplete(pin); } catch (e) { ok = false; }
    setBusy(false);
    if (!ok) fail('Incorrect PIN');
  };

  const press = (d) => {
    if (busy || entry.length >= LEN) return;
    const next = entry + d;
    setEntry(next); setError('');
    if (next.length === LEN) setTimeout(() => submit(next), 130);
  };
  const back = () => { if (!busy) setEntry((e) => e.slice(0, -1)); };

  // Physical keyboard support (desktop)
  useEffect(() => {
    const onKey = (e) => {
      if (e.key >= '0' && e.key <= '9') press(e.key);
      else if (e.key === 'Backspace') back();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [entry, stage, firstPin, busy]);

  const title = mode === 'create'
    ? (stage === 'first' ? 'Create a PIN' : 'Confirm your PIN')
    : 'Enter your PIN';
  const subtitle = mode === 'create'
    ? (stage === 'first'
        ? 'Pick a 4-digit code to keep your space private.'
        : 'Type it once more to confirm.')
    : (neutralMode ? 'Enter your 4-digit code to continue.' : 'Welcome back — enter your code ✨');

  const accent = neutralMode ? '#007AFF' : '#f472b6';
  const keys = ['1','2','3','4','5','6','7','8','9','','0','back'];

  return (
    <div className={`min-h-screen ${neutralMode ? 'neutral-mode bg-[#f5f5f7]' : 'bg-main'} flex flex-col items-center justify-center p-4 font-sans`}>
      <div className={`signin-card p-8 rounded-[2rem] text-center max-w-xs w-full relative overflow-hidden ${shake ? 'pin-shake' : ''}`}>
        {!neutralMode && <div className="absolute inset-0 pointer-events-none" style={{ background: 'radial-gradient(circle at 60% 0%, rgba(244,114,182,0.08) 0%, transparent 70%)' }} />}

        <div className="icon-badge w-14 h-14 mx-auto mb-5 rounded-[20px] flex items-center justify-center">
          <Lock className="text-white drop-shadow-sm" size={24} />
        </div>

        <h2 className={`text-xl font-bold mb-2 ${neutralMode ? 'text-slate-800' : 'text-pink-500'}`}>{title}</h2>
        <p className="mb-6 text-xs leading-relaxed text-slate-500 min-h-[2rem]">
          {error ? <span className="text-red-400 font-semibold">{error}</span> : subtitle}
        </p>

        {/* Entry dots */}
        <div className="flex justify-center gap-3 mb-7">
          {[...Array(LEN)].map((_, i) => (
            <div key={i} className="w-3.5 h-3.5 rounded-full transition-all duration-150" style={{
              backgroundColor: i < entry.length ? accent : 'transparent',
              border: `2px solid ${i < entry.length ? accent : (neutralMode ? '#d2d2d7' : '#fbcfe8')}`,
              transform: i < entry.length ? 'scale(1.1)' : 'scale(1)'
            }} />
          ))}
        </div>

        {/* Numpad */}
        <div className="grid grid-cols-3 gap-3">
          {keys.map((k, i) => {
            if (k === '') return <div key={i} />;
            if (k === 'back') return (
              <button key={i} onClick={back} disabled={busy}
                className="h-14 rounded-2xl flex items-center justify-center text-slate-400 hover:bg-pink-50/60 active:scale-95 transition-all disabled:opacity-40">
                <Backspace size={22} />
              </button>
            );
            return (
              <button key={i} onClick={() => press(k)} disabled={busy}
                className={`h-14 rounded-2xl text-xl font-bold transition-all active:scale-95 disabled:opacity-40 ${neutralMode ? 'bg-white text-slate-700 hover:bg-slate-50 shadow-glow' : 'card-glass text-pink-500 hover:bg-pink-50/60 shadow-glow border border-white/60'}`}>
                {k}
              </button>
            );
          })}
        </div>

        <button onClick={onSignOut} className="mt-6 text-[11px] font-semibold text-slate-400 hover:text-slate-600 transition-colors">
          {userEmail ? `Not ${userEmail}? ` : ''}Sign out
        </button>
      </div>
    </div>
  );
};

window.PinScreen = PinScreen;
