// screen-signin.jsx — Magic-link sign-in + register.
// One screen with a "new here?" toggle. Email magic-link via Supabase Auth.

const { useState: siU, useEffect: siE } = React;

function SignInScreen({ onNav, initialMode }) {
  const { Footer, Field } = window.PJ_UI;
  const [mode, setMode] = siU(initialMode === 'register' ? 'register' : 'signin');
  const [method, setMethod] = siU('email'); // 'email' | 'phone'
  const [email, setEmail] = siU(window.pjGetEmail() || '');
  const [name, setName] = siU(window.pjGetName() || '');
  const [phone, setPhone] = siU(window.pjGetPhone() || '');
  const [smsCode, setSmsCode] = siU('');
  const [smsSent, setSmsSent] = siU(false);
  const [submitting, setSubmitting] = siU(false);
  const [sent, setSent] = siU(false);
  const [err, setErr] = siU(null);

  // Detect magic-link callback (hash contains access_token) and show a "signing you in" state.
  const [callbackBusy, setCallbackBusy] = siU(
    typeof window !== 'undefined' && /access_token=|error_code=/.test(window.location.hash || '')
  );

  // If already signed in, bounce home. Also poll briefly when we're processing a callback.
  siE(() => {
    if (window.pjIsSignedIn()) { onNav('/'); return; }
    if (!callbackBusy) return;
    let n = 0;
    const t = setInterval(() => {
      if (window.pjIsSignedIn()) { clearInterval(t); onNav('/'); return; }
      if (++n > 20) { clearInterval(t); setCallbackBusy(false); setErr('Sign-in took too long. Try again.'); }
    }, 400);
    return () => clearInterval(t);
  }, [callbackBusy]);

  const isRegister = mode === 'register';
  const isPhone = method === 'phone';
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const phoneOk = /^\+?[0-9 ()-]{8,}$/.test(phone.trim());
  const canSubmit = !submitting && (!isRegister || name.trim().length > 0) && (isPhone ? phoneOk : emailOk);
  const canVerify = !submitting && /^\d{4,8}$/.test(smsCode.trim());

  const submit = async (e) => {
    e && e.preventDefault && e.preventDefault();
    if (!canSubmit) return;
    setErr(null);
    setSubmitting(true);
    try {
      if (isPhone) {
        await window.pjSendPhoneOtp(phone.trim(), {
          name: isRegister ? name.trim() : undefined
        });
        setSmsSent(true);
      } else {
        await window.pjSendMagicLink(email.trim(), {
          name: isRegister ? name.trim() : undefined,
          phone: isRegister ? phone.trim() : undefined,
          redirectPath: '/'
        });
        setSent(true);
      }
    } catch (ex) {
      setErr((ex && ex.message) || String(ex));
    } finally {
      setSubmitting(false);
    }
  };

  const verifySms = async (e) => {
    e && e.preventDefault && e.preventDefault();
    if (!canVerify) return;
    setErr(null);
    setSubmitting(true);
    try {
      await window.pjVerifyPhoneOtp(phone.trim(), smsCode.trim());
      onNav('/');
    } catch (ex) {
      setErr((ex && ex.message) || String(ex));
    } finally {
      setSubmitting(false);
    }
  };

  const inputStyle = {
    width: '100%',
    padding: '14px 16px',
    background: '#0F1318',
    border: '1px solid #2A323C',
    borderRadius: 10,
    color: 'var(--text)',
    fontSize: 16,
    fontFamily: 'var(--font-display)',
    outline: 'none',
    boxSizing: 'border-box'
  };

  return (
    <div className="page" style={{ padding: '40px 20px 120px' }}>
      <div className="container" style={{ maxWidth: 460 }}>
        <div className="mono green" style={{ marginBottom: 14 }}>
          ◆ {isRegister ? 'CREATE ACCOUNT' : 'SIGN IN'}
        </div>
        <h1 style={{
          fontSize: 'clamp(36px, 7vw, 52px)',
          lineHeight: 1.02,
          letterSpacing: '-0.035em',
          marginBottom: 10,
          fontWeight: 700
        }}>
          {isRegister
            ? <span>Lock <span style={{ color: 'var(--green)', textShadow: '0 0 24px var(--green-glow)' }}>your name</span> to your equity.</span>
            : <span>Welcome <span style={{ color: 'var(--green)', textShadow: '0 0 24px var(--green-glow)' }}>back</span>.</span>}
        </h1>
        <p className="text-2" style={{ marginBottom: 24, fontSize: 16 }}>
          {isPhone
            ? "Enter your phone. We'll text you a 6-digit code."
            : "Enter your email. We'll send a magic link — no passwords."}
        </p>

        {callbackBusy && (
          <div style={{ padding: '20px 18px', background: 'rgba(0,224,138,0.08)', border: '1px solid var(--green-line)', borderRadius: 12, marginBottom: 20, textAlign: 'center' }}>
            <div className="mono green" style={{ marginBottom: 8, fontSize: 11, letterSpacing: '0.14em' }}>◆ SIGNING YOU IN</div>
            <div style={{ fontSize: 14, color: 'var(--text-2)' }}>Finishing up — one sec.</div>
          </div>
        )}

        <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
          {[
            { id: 'email', label: 'EMAIL' },
            { id: 'phone', label: 'PHONE' }
          ].map(m => (
            <button
              key={m.id}
              type="button"
              onClick={() => { setMethod(m.id); setErr(null); setSent(false); setSmsSent(false); }}
              style={{
                all: 'unset',
                cursor: 'pointer',
                flex: 1,
                textAlign: 'center',
                padding: '12px 0',
                borderRadius: 10,
                background: method === m.id ? 'rgba(0,224,138,0.08)' : 'transparent',
                border: '1px solid ' + (method === m.id ? 'var(--green)' : '#2A323C'),
                color: method === m.id ? 'var(--green)' : 'var(--text-3)',
                fontFamily: 'var(--font-mono)',
                fontSize: 11,
                letterSpacing: '0.16em',
                fontWeight: 700
              }}
            >
              {m.label}
            </button>
          ))}
        </div>

        {smsSent ? (
          <form onSubmit={verifySms} className="stack-3">
            <div style={{
              padding: '16px 18px',
              background: 'rgba(0, 224, 138, 0.06)',
              border: '1px solid var(--green-line)',
              borderRadius: 12,
              marginBottom: 16,
              fontSize: 14, color: 'var(--text)'
            }}>
              Code sent to <strong>{phone}</strong>. Enter it below.
            </div>
            <Field label="6-digit code">
              <input
                type="text"
                inputMode="numeric"
                autoComplete="one-time-code"
                value={smsCode}
                onChange={(e) => setSmsCode(e.target.value.replace(/\D/g,'').slice(0,8))}
                placeholder="123456"
                style={inputStyle}
              />
            </Field>
            {err && (
              <div className="mono" style={{ color: '#ff8a9c', fontSize: 12, padding: '10px 12px', background: 'rgba(255,77,94,0.06)', border: '1px solid rgba(255,77,94,0.25)', borderRadius: 8 }}>{err}</div>
            )}
            <button
              type="submit"
              disabled={!canVerify}
              style={{ all: 'unset', cursor: canVerify ? 'pointer' : 'not-allowed', opacity: canVerify ? 1 : 0.5, display: 'block', width: '100%', padding: '18px 24px', borderRadius: 12, background: 'linear-gradient(180deg, #E8ECEF 0%, #B8BFC8 55%, #8A929C 100%)', color: '#0B0E11', textAlign: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17, boxShadow: '0 0 28px rgba(0,224,138,0.30), 0 0 0 1px #2A323C, 0 8px 22px rgba(0,0,0,0.55)', boxSizing: 'border-box' }}
            >
              {submitting ? 'Verifying…' : 'Verify code'}
            </button>
            <div style={{ textAlign: 'center', marginTop: 10 }}>
              <a href="#" onClick={(e) => { e.preventDefault(); setSmsSent(false); setSmsCode(''); }} className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-3)', textDecoration: 'underline' }}>
                Try a different phone
              </a>
            </div>
          </form>
        ) : sent ? (
          <div style={{
            padding: '20px 18px',
            background: 'rgba(0, 224, 138, 0.06)',
            border: '1px solid var(--green-line)',
            borderRadius: 12,
            marginBottom: 20
          }}>
            <div className="mono green" style={{ marginBottom: 8, fontSize: 11, letterSpacing: '0.14em' }}>
              ◆ CHECK YOUR INBOX
            </div>
            <div style={{ fontSize: 15, color: 'var(--text)', lineHeight: 1.5 }}>
              We sent a sign-in link to <strong>{email}</strong>. Click it to finish.
            </div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', letterSpacing: '0.14em', textTransform: 'uppercase', marginTop: 12 }}>
              Didn't get it? Check spam, or
              {' '}
              <a
                href="#"
                onClick={(e) => { e.preventDefault(); setSent(false); }}
                style={{ color: 'var(--green)', textDecoration: 'underline' }}
              >try again</a>.
            </div>
          </div>
        ) : (
          <form onSubmit={submit} className="stack-3">
            {!isPhone && (
              <Field label="Email">
                <input
                  type="email"
                  autoComplete="email"
                  inputMode="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@example.com"
                  style={inputStyle}
                />
              </Field>
            )}

            {isPhone && (
              <Field label="Phone" help="Include country code. e.g. +1 555 123 4567">
                <input
                  type="tel"
                  autoComplete="tel"
                  inputMode="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="+1 555 123 4567"
                  style={inputStyle}
                />
              </Field>
            )}

            {isRegister && (
              <Field label="Real name" help="As it appears on your ID — used to verify WSOP cashes.">
                <input
                  type="text"
                  autoComplete="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Daniel Negreanu"
                  style={inputStyle}
                />
              </Field>
            )}

            {isRegister && !isPhone && (
              <Field label="Phone / WhatsApp (optional)" help="For future swap-locked notifications. Skip if you want.">
                <input
                  type="tel"
                  autoComplete="tel"
                  inputMode="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="+1 555 123 4567"
                  style={inputStyle}
                />
              </Field>
            )}

            {err && (
              <div className="mono" style={{
                color: '#ff8a9c',
                fontSize: 12,
                padding: '10px 12px',
                background: 'rgba(255,77,94,0.06)',
                border: '1px solid rgba(255,77,94,0.25)',
                borderRadius: 8
              }}>{err}</div>
            )}

            <button
              type="submit"
              disabled={!canSubmit}
              style={{
                all: 'unset',
                cursor: canSubmit ? 'pointer' : 'not-allowed',
                opacity: canSubmit ? 1 : 0.5,
                display: 'block',
                width: '100%',
                padding: '18px 24px',
                borderRadius: 12,
                background: 'linear-gradient(180deg, #E8ECEF 0%, #B8BFC8 55%, #8A929C 100%)',
                color: '#0B0E11',
                textAlign: 'center',
                fontFamily: 'var(--font-display)',
                fontWeight: 700,
                fontSize: 17,
                letterSpacing: '-0.01em',
                boxShadow: '0 0 28px rgba(0,224,138,0.30), 0 0 0 1px #2A323C, 0 8px 22px rgba(0,0,0,0.55)',
                boxSizing: 'border-box'
              }}
            >
              {submitting ? 'Sending…' : (isPhone ? 'Text me a code' : 'Send magic link')}
            </button>

            <div style={{ textAlign: 'center', marginTop: 10 }}>
              <a
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  setMode(isRegister ? 'signin' : 'register');
                  setErr(null);
                }}
                className="mono"
                style={{
                  fontSize: 11,
                  letterSpacing: '0.14em',
                  textTransform: 'uppercase',
                  color: 'var(--text-3)',
                  textDecoration: 'underline'
                }}
              >
                {isRegister ? 'Already have an account? Sign in' : 'New here? Create an account'}
              </a>
            </div>
          </form>
        )}

        <Footer />
      </div>
    </div>
  );
}

window.SignInScreen = SignInScreen;
