// Auth screen — login / register — wired to real backend.
function Auth({ onNav, initialMode }) {
  const [mode, setMode] = React.useState(initialMode || 'login'); // login | register
  const [email, setEmail]       = React.useState('');
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm]   = React.useState('');
  const [agree, setAgree]       = React.useState(false);
  const [showPw, setShowPw]     = React.useState(false);
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState(null);
  const [shake, setShake]       = React.useState(0);
  const [success, setSuccess]   = React.useState(false);
  const [referralCode, setReferralCode] = React.useState('');
  const [showRefField, setShowRefField] = React.useState(false);

  // Prefill referral code from URL (?ref=XYZ) or localStorage (captured earlier)
  React.useEffect(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      const fromUrl = params.get('ref');
      if (fromUrl) {
        const clean = fromUrl.trim().toUpperCase().slice(0, 16);
        setReferralCode(clean);
        setShowRefField(true);
        localStorage.setItem('67px_ref', clean);
      } else {
        const stored = localStorage.getItem('67px_ref');
        if (stored) {
          setReferralCode(stored);
          setShowRefField(true);
        }
      }
    } catch (_) {}
  }, []);

  React.useEffect(() => { setError(null); }, [mode]);

  const strength = passwordStrength(password);

  const canSubmit = (() => {
    if (loading) return false;
    if (!email || !password) return false;
    if (mode === 'register') {
      if (!agree) return false;
      if (password !== confirm) return false;
      if (password.length < 8) return false;
    }
    return true;
  })();

  const submit = async (e) => {
    e.preventDefault();
    if (!canSubmit) return;

    setLoading(true);
    setError(null);

    try {
      const path = mode === 'register' ? '/api/auth/register' : '/api/auth/login';
      const body = { email, password };
      if (mode === 'register' && referralCode.trim()) {
        body.referral_code = referralCode.trim();
      }
      const data = await window.api(path, { method: 'POST', body });

      // Clear stored referral code after successful signup
      if (mode === 'register') {
        try { localStorage.removeItem('67px_ref'); } catch (_) {}
      }

      setSuccess(true);
      window.__user = data.user;
      setTimeout(() => {
        if (data.user?.role === 'admin') onNav('admin');
        else onNav('dashboard');
      }, 500);
    } catch (err) {
      setLoading(false);
      setError({
        message: window.apiErrorMessage(err),
        fields: err?.fields || null,
      });
      setShake(s => s + 1);
    }
  };

  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 1fr', background: 'var(--bg-0)' }}>
      {/* Left — form */}
      <div style={{ display: 'flex', flexDirection: 'column', padding: '32px 56px', minHeight: '100vh' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <a onClick={() => onNav('landing')} style={{ cursor: 'pointer' }}><Logo67 size={24}/></a>
          <div style={{ fontSize: 13, color: 'var(--fg-2)' }}>
            {mode === 'login' ? (
              <>New to 67proxies? <a onClick={() => setMode('register')} style={{ color: 'var(--accent)', cursor: 'pointer', fontWeight: 500 }}>Create account →</a></>
            ) : (
              <>Have an account? <a onClick={() => setMode('login')} style={{ color: 'var(--accent)', cursor: 'pointer', fontWeight: 500 }}>Sign in →</a></>
            )}
          </div>
        </div>

        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
          <div aria-hidden="true" style={{
            position: 'absolute', width: 520, height: 520, left: '50%', top: '50%',
            transform: 'translate(-50%, -50%)',
            background: 'radial-gradient(circle, color-mix(in oklab, var(--accent) 16%, transparent), transparent 60%)',
            filter: 'blur(40px)', pointerEvents: 'none',
            animation: 'authGlow 8s ease-in-out infinite',
          }}/>
          <div
            key={shake}
            style={{
              width: '100%', maxWidth: 380, position: 'relative',
              animation: shake ? 'authShake 0.45s cubic-bezier(.36,.07,.19,.97)' : undefined,
            }}
          >
            <div className="chip chip-accent" style={{ marginBottom: 20 }}>
              <span className="dot" style={{ background: 'var(--accent)' }}/>
              {mode === 'login' ? 'Welcome back' : 'Create your account'}
            </div>
            <h1 style={{ fontSize: 34, fontWeight: 500, letterSpacing: '-0.03em', margin: '0 0 10px', lineHeight: 1.05 }}>
              {mode === 'login' ? <>Sign in to<br/>67proxies.</> : <>Start scraping<br/>in 60 seconds.</>}
            </h1>
            <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 28px' }}>
              {mode === 'login' ? 'Pick up where you left off — dashboard, proxies, billing.' : 'Email + password. No credit card. Pay in crypto.'}
            </p>

            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '0 0 22px', fontSize: 11, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
              <div style={{ height: 1, flex: 1, background: 'var(--line)' }}/>
              <span>{mode === 'login' ? 'sign in with email' : 'create with email'}</span>
              <div style={{ height: 1, flex: 1, background: 'var(--line)' }}/>
            </div>

            <form onSubmit={submit} className="auth-fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 14 }} noValidate>
              <Field label="Email">
                <div style={{ position: 'relative' }}>
                  <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-3)', pointerEvents: 'none' }}>
                    <Icon name="mail" size={14}/>
                  </span>
                  <input
                    type="email"
                    value={email}
                    onChange={e => { setEmail(e.target.value); setError(null); }}
                    placeholder="you@gmail.com"
                    autoComplete="email"
                    required
                    maxLength={254}
                    style={{
                      width: '100%',
                      paddingLeft: 34,
                      borderColor: error?.fields?.email ? 'var(--err)' : undefined,
                    }}
                  />
                </div>
                {error?.fields?.email && (
                  <div style={{ fontSize: 11, color: 'var(--err)', marginTop: 6 }}>{error.fields.email[0]}</div>
                )}
              </Field>

              <Field label="Password">
                <div style={{ position: 'relative' }}>
                  <input
                    type={showPw ? 'text' : 'password'}
                    value={password}
                    onChange={e => { setPassword(e.target.value); setError(null); }}
                    placeholder="••••••••••"
                    autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
                    required
                    minLength={mode === 'register' ? 8 : 1}
                    maxLength={256}
                    style={{
                      width: '100%',
                      paddingRight: 36,
                      borderColor: error?.fields?.password ? 'var(--err)' : undefined,
                    }}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPw(p => !p)}
                    aria-label={showPw ? 'Hide password' : 'Show password'}
                    style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-3)', padding: 4 }}
                  >
                    <Icon name={showPw ? 'eye-off' : 'eye'} size={14}/>
                  </button>
                </div>
                {mode === 'register' && password && (
                  <div style={{ marginTop: 8 }}>
                    <div style={{ display: 'flex', gap: 3 }}>
                      {[0, 1, 2, 3].map(i => (
                        <div key={i} style={{
                          height: 3, flex: 1, borderRadius: 2,
                          background: i < strength.score ? strength.color : 'var(--line)',
                          transition: 'background 0.25s',
                        }}/>
                      ))}
                    </div>
                    <div style={{ fontSize: 11, color: strength.color, marginTop: 6 }}>{strength.label}</div>
                  </div>
                )}
              </Field>

              {mode === 'register' && (
                <Field label="Confirm password">
                  <input
                    type={showPw ? 'text' : 'password'}
                    value={confirm}
                    onChange={e => setConfirm(e.target.value)}
                    placeholder="••••••••••"
                    required
                    maxLength={256}
                    style={{
                      width: '100%',
                      borderColor: confirm && confirm !== password ? 'var(--err)' : undefined,
                    }}
                  />
                  {confirm && confirm !== password && (
                    <div style={{ fontSize: 11, color: 'var(--err)', marginTop: 6 }}>Passwords don't match</div>
                  )}
                </Field>
              )}

              {mode === 'register' && (
                <label style={{ display: 'flex', gap: 9, fontSize: 12, color: 'var(--fg-1)', cursor: 'pointer', marginTop: 4, lineHeight: 1.4 }}>
                  <input
                    type="checkbox"
                    checked={agree}
                    onChange={e => setAgree(e.target.checked)}
                    required
                    style={{ width: 15, height: 15, accentColor: 'var(--accent)', marginTop: 1, padding: 0 }}
                  />
                  <span>
                    I agree to the <a style={{ color: 'var(--accent)' }}>Terms</a>, <a style={{ color: 'var(--accent)' }}>Privacy Policy</a>, and <a style={{ color: 'var(--accent)' }}>Acceptable Use</a> policy.
                  </span>
                </label>
              )}

              {mode === 'register' && (
                <div>
                  {!showRefField ? (
                    <button
                      type="button"
                      onClick={() => setShowRefField(true)}
                      style={{ background: 'transparent', fontSize: 12, color: 'var(--accent)', cursor: 'pointer', padding: 0 }}
                    >
                      Have a referral code? <span style={{ textDecoration: 'underline' }}>Enter it</span>
                    </button>
                  ) : (
                    <Field label="Referral code (optional)">
                      <input
                        type="text"
                        value={referralCode}
                        onChange={e => setReferralCode(e.target.value.toUpperCase())}
                        placeholder="ABCD1234"
                        maxLength={16}
                        className="mono"
                        style={{ width: '100%', letterSpacing: '0.08em' }}
                      />
                      <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 6 }}>
                        You'll get <b style={{ color: 'var(--accent)' }}>5% off every purchase</b> for life.
                      </div>
                    </Field>
                  )}
                </div>
              )}

              {error?.message && (
                <div role="alert" style={{
                  fontSize: 12, color: 'var(--err)',
                  background: 'color-mix(in oklab, var(--err) 10%, transparent)',
                  border: '1px solid color-mix(in oklab, var(--err) 30%, transparent)',
                  padding: '9px 12px', borderRadius: 8,
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <Icon name="alert" size={13}/> {error.message}
                </div>
              )}

              <button
                type="submit"
                className="btn btn-primary"
                disabled={!canSubmit}
                style={{
                  width: '100%', justifyContent: 'center', marginTop: 8, padding: '12px 16px',
                  opacity: !canSubmit && !success ? 0.6 : 1,
                  background: success ? 'var(--ok)' : undefined,
                  transition: 'background 0.2s',
                }}
              >
                {success ? (<><Icon name="check" size={14}/> Signed in</>) :
                 loading  ? (<><Spinner/> Authenticating…</>) : (
                  <>
                    {mode === 'login' ? 'Sign in' : 'Create account'}
                    <Icon name="arrow_right" size={14}/>
                  </>
                )}
              </button>

              {mode === 'login' && (
                <div style={{ fontSize: 11, color: 'var(--fg-3)', textAlign: 'center', marginTop: 4, lineHeight: 1.5 }}>
                  <a style={{ color: 'var(--accent)', cursor: 'pointer' }}>Forgot your password?</a> We'll email you a reset link.
                </div>
              )}
            </form>
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--fg-3)' }}>
          <div>© 2026 67proxies</div>
          <div style={{ display: 'flex', gap: 16 }}>
            <a>Terms</a><a>Status</a>
          </div>
        </div>
      </div>

      <AuthSidePanel mode={mode}/>

      <style>{`
        @keyframes authShake {
          10%, 90% { transform: translate3d(-1px, 0, 0); }
          20%, 80% { transform: translate3d(2px, 0, 0); }
          30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
          40%, 60% { transform: translate3d(4px, 0, 0); }
        }
        @keyframes authGlow {
          0%, 100% { opacity: 0.75; transform: translate(-50%,-50%) scale(1); }
          50%      { opacity: 1;    transform: translate(-50%,-50%) scale(1.07); }
        }
      `}</style>
    </div>
  );
}

function Field({ label, right, children }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
        <label style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{label}</label>
        {right}
      </div>
      {children}
    </div>
  );
}

function Spinner() {
  return (
    <span style={{
      width: 14, height: 14, border: '2px solid currentColor',
      borderTopColor: 'transparent', borderRadius: '50%',
      animation: 'spin 0.7s linear infinite', display: 'inline-block',
    }}>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </span>
  );
}

function passwordStrength(pw) {
  if (!pw) return { score: 0, label: '', color: 'var(--line)' };
  let score = 0;
  if (pw.length >= 8)  score++;
  if (pw.length >= 12) score++;
  if (/[A-Z]/.test(pw) && /[a-z]/.test(pw)) score++;
  if (/[0-9]/.test(pw) && /[^A-Za-z0-9]/.test(pw)) score++;
  const map = [
    { label: 'Too short',   color: 'var(--err)'  },
    { label: 'Weak',        color: 'var(--err)'  },
    { label: 'Decent',      color: 'var(--warn)' },
    { label: 'Strong',      color: 'var(--ok)'   },
    { label: 'Very strong', color: 'var(--ok)'   },
  ];
  return { score, ...map[score] };
}

function AuthSidePanel({ mode }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setTick(x => x + 1), 1400);
    return () => clearInterval(t);
  }, []);

  const ips = ['185.199.247.142', '62.73.104.18', '198.54.117.210', '82.165.44.91', '104.28.132.53', '91.244.83.7', '203.0.113.19', '45.79.210.144'];
  const ports = ['7823', '9041', '8421', '7156', '8910', '9234', '7765', '8188'];

  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: 'radial-gradient(ellipse at 30% 20%, color-mix(in oklab, var(--accent) 18%, transparent), transparent 55%), radial-gradient(ellipse at 70% 80%, color-mix(in oklab, var(--accent) 12%, transparent), transparent 50%), var(--bg-1)',
      borderLeft: '1px solid var(--line)',
      display: 'flex', flexDirection: 'column', padding: '48px',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px)',
        backgroundSize: '48px 48px',
        maskImage: 'radial-gradient(ellipse 80% 70% at 50% 50%, black 30%, transparent 80%)',
      }}/>
      <div style={{ position: 'relative', maxWidth: 440 }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 20 }}>
          /// proven at scale
        </div>
        <div style={{ fontSize: 26, fontWeight: 500, letterSpacing: '-0.025em', lineHeight: 1.25, marginBottom: 24, textWrap: 'pretty' }}>
          "We ditched three competitors and went all-in on 67proxies. <span style={{ color: 'var(--accent)' }}>CAPTCHA rate dropped from 31% to 2%</span> in a week."
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: 'linear-gradient(135deg, var(--accent), var(--accent-2))',
            display: 'grid', placeItems: 'center', color: 'var(--accent-ink)', fontWeight: 600, fontSize: 13,
          }}>MK</div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Mira Kovacs</div>
            <div style={{ fontSize: 11, color: 'var(--fg-2)' }}>Head of Data · Stanza Analytics</div>
          </div>
        </div>
      </div>

      <div style={{ position: 'relative', marginTop: 'auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ fontSize: 11, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Live endpoints · worldwide pool</div>
          <div className="chip chip-ok" style={{ fontSize: 10 }}>
            <span className="dot" style={{ background: 'var(--ok)', animation: 'pulse 1.6s ease-in-out infinite' }}/>
            67.2M online
          </div>
        </div>
        <div className="card" style={{ padding: 0, overflow: 'hidden', background: 'rgba(7,9,13,0.65)', backdropFilter: 'blur(6px)' }}>
          {ips.map((ip, i) => {
            const active = ((i + tick) % ips.length) < 3;
            return (
              <div key={ip} style={{
                display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 16,
                padding: '11px 16px',
                borderBottom: i < ips.length - 1 ? '1px solid var(--line-soft)' : 'none',
                fontSize: 12, transition: 'background 0.4s',
                background: active ? 'color-mix(in oklab, var(--accent) 8%, transparent)' : 'transparent',
              }}>
                <span className="mono" style={{ color: active ? 'var(--accent)' : 'var(--fg-1)' }}>
                  {ip}:{ports[i]}
                </span>
                <span className="mono" style={{ color: 'var(--fg-2)', fontSize: 11 }}>
                  {(12 + (i * 17) % 88)}ms
                </span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10, color: active ? 'var(--ok)' : 'var(--fg-3)' }}>
                  <span className="dot" style={{ background: active ? 'var(--ok)' : 'var(--fg-3)' }}/>
                  {active ? 'routing' : 'idle'}
                </span>
              </div>
            );
          })}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginTop: 16 }}>
          {[
            { k: '99.98%', v: 'Uptime · 90d' },
            { k: '<0.6s',  v: 'Avg response' },
            { k: '12K+',   v: 'Engineers'    },
          ].map(s => (
            <div key={s.v} className="card" style={{ padding: '10px 14px', background: 'rgba(7,9,13,0.55)' }}>
              <div className="mono" style={{ fontSize: 15, fontWeight: 500, color: 'var(--accent)' }}>{s.k}</div>
              <div style={{ fontSize: 10, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{s.v}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`@keyframes pulse { 50% { opacity: 0.35; } }`}</style>
    </div>
  );
}

window.Auth = Auth;
