// Auth — splash, register, login
function Splash() {
  const { go } = useApp();
  return (
    <div className="screen page-enter" style={{ position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <div className="auth-bg">
        <div className="blob blob-1"></div>
        <div className="blob blob-2"></div>
        <div className="blob blob-3"></div>
      </div>
      <StatusBar />
      <div style={{ flex: 1, position: 'relative', zIndex: 1, padding: '20px 24px 30px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', textAlign: 'center' }}>
          <Logo size="lg" />
          <h2 style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.03em', margin: '40px 0 14px', lineHeight: 1.05 }}>
            Trade everything.<br/>
            <span style={{ background: 'linear-gradient(135deg, var(--green), var(--cyan))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>Settled in crypto.</span>
          </h2>
          <p style={{ color: 'var(--text-dim)', fontSize: 15, lineHeight: 1.5, maxWidth: 320, margin: 0 }}>
            Forex, indices, stocks and crypto CFDs. Fund instantly with BTC, ETH or USDT — no paperwork, no waiting.
          </p>
          <div className="row" style={{ gap: 16, marginTop: 28 }}>
            <Stat n="180+" l="Markets" />
            <div style={{ width: 1, height: 30, background: 'var(--line)' }}></div>
            <Stat n="1:500" l="Leverage" />
            <div style={{ width: 1, height: 30, background: 'var(--line)' }}></div>
            <Stat n="0.0s" l="KYC" />
          </div>
        </div>
        <div className="stack" style={{ gap: 10 }}>
          <button className="btn btn-primary" onClick={() => go('register')}>Create account</button>
          <button className="btn btn-ghost" onClick={() => go('login')}>I already have an account</button>
        </div>
      </div>
    </div>
  );
}

function Stat({ n, l }) {
  return (
    <div className="col" style={{ alignItems: 'center' }}>
      <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>{n}</div>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{l}</div>
    </div>
  );
}

const COUNTRIES = [
  { c: 'AE', n: 'United Arab Emirates', d: '+971' },
  { c: 'AU', n: 'Australia', d: '+61' },
  { c: 'BR', n: 'Brazil', d: '+55' },
  { c: 'CA', n: 'Canada', d: '+1' },
  { c: 'DE', n: 'Germany', d: '+49' },
  { c: 'ES', n: 'Spain', d: '+34' },
  { c: 'FR', n: 'France', d: '+33' },
  { c: 'GB', n: 'United Kingdom', d: '+44' },
  { c: 'IN', n: 'India', d: '+91' },
  { c: 'JP', n: 'Japan', d: '+81' },
  { c: 'MX', n: 'Mexico', d: '+52' },
  { c: 'NG', n: 'Nigeria', d: '+234' },
  { c: 'PH', n: 'Philippines', d: '+63' },
  { c: 'SG', n: 'Singapore', d: '+65' },
  { c: 'TH', n: 'Thailand', d: '+66' },
  { c: 'TR', n: 'Türkiye', d: '+90' },
  { c: 'US', n: 'United States', d: '+1' },
  { c: 'VN', n: 'Vietnam', d: '+84' },
  { c: 'ZA', n: 'South Africa', d: '+27' },
];

function Register() {
  const { go, login } = useApp();
  const [step, setStep] = useState(1);
  const [data, setData] = useState({ name: '', email: '', country: 'GB', phone: '', password: '' });
  const [showPw, setShowPw] = useState(false);
  const [showCountries, setShowCountries] = useState(false);
  const country = COUNTRIES.find(x => x.c === data.country);

  const upd = (k, v) => setData(d => ({ ...d, [k]: v }));
  const pwStrength = useMemo(() => {
    const p = data.password; let s = 0;
    if (p.length >= 8) s++;
    if (/[A-Z]/.test(p)) s++;
    if (/[0-9]/.test(p)) s++;
    if (/[^A-Za-z0-9]/.test(p)) s++;
    return s;
  }, [data.password]);

  const canStep1 = data.name.trim().length > 1 && /\S+@\S+\.\S+/.test(data.email);
  const canStep2 = data.phone.length >= 6 && pwStrength >= 2;

  const submit = () => {
    login({ name: data.name, email: data.email, country: data.country });
    go('dashboard');
  };

  return (
    <div className="screen page-enter">
      <StatusBar />
      <AppBar title="" onBack={() => step === 1 ? go('splash') : setStep(1)} />
      <div style={{ padding: '0 24px 30px' }}>
        <div className="row" style={{ gap: 6, marginBottom: 24 }}>
          {[1,2].map(s => (
            <div key={s} style={{
              flex: 1, height: 4, borderRadius: 2,
              background: s <= step ? 'var(--green)' : 'var(--line)'
            }}/>
          ))}
        </div>

        <h1 style={{ fontSize: 30, margin: '0 0 8px', fontWeight: 700, letterSpacing: '-0.02em' }}>
          {step === 1 ? 'Create account' : 'A few more details'}
        </h1>
        <p style={{ color: 'var(--text-dim)', fontSize: 14, margin: '0 0 28px' }}>
          {step === 1 ? 'Start trading in under 60 seconds.' : 'We\'ll text a verification code.'}
        </p>

        {step === 1 ? (
          <div className="stack" style={{ gap: 16 }}>
            <div className="input-group">
              <label className="input-label">Full name</label>
              <input className="input" placeholder="Jane Doe" value={data.name} onChange={e => upd('name', e.target.value)} />
            </div>
            <div className="input-group">
              <label className="input-label">Email</label>
              <input className="input" type="email" placeholder="you@email.com" value={data.email} onChange={e => upd('email', e.target.value)} />
            </div>
            <button className="btn btn-primary" disabled={!canStep1} onClick={() => setStep(2)} style={{ marginTop: 8 }}>Continue</button>
            <div style={{ textAlign: 'center', color: 'var(--text-dim)', fontSize: 13, marginTop: 8 }}>
              Already registered? <a onClick={() => go('login')} style={{ color: 'var(--green)', cursor: 'pointer', fontWeight: 500 }}>Sign in</a>
            </div>
          </div>
        ) : (
          <div className="stack" style={{ gap: 16 }}>
            <div className="input-group">
              <label className="input-label">Country</label>
              <button className="input row" onClick={() => setShowCountries(true)} style={{ textAlign: 'left', justifyContent: 'space-between' }}>
                <span>{country.n}</span>
                <I.chevD />
              </button>
            </div>
            <div className="input-group">
              <label className="input-label">Phone number</label>
              <span className="input-prefix mono">{country.d}</span>
              <input className="input input-with-prefix mono" type="tel" placeholder="123 456 789" value={data.phone} onChange={e => upd('phone', e.target.value)} />
            </div>
            <div className="input-group">
              <label className="input-label">Password</label>
              <input className="input" type={showPw ? 'text' : 'password'} placeholder="At least 8 characters" value={data.password} onChange={e => upd('password', e.target.value)} />
              <button className="input-suffix" onClick={() => setShowPw(s => !s)}>{showPw ? <I.eyeOff /> : <I.eye />}</button>
              <div className="row" style={{ gap: 4, marginTop: 8 }}>
                {[1,2,3,4].map(i => (
                  <div key={i} style={{
                    flex: 1, height: 3, borderRadius: 2,
                    background: i <= pwStrength ? (pwStrength <= 1 ? 'var(--red)' : pwStrength <= 2 ? 'var(--amber)' : 'var(--green)') : 'var(--line)'
                  }}/>
                ))}
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 6 }}>
                {data.password.length === 0 ? '8+ chars, mix letters & numbers' : pwStrength <= 1 ? 'Weak' : pwStrength === 2 ? 'OK' : pwStrength === 3 ? 'Strong' : 'Very strong'}
              </div>
            </div>
            <button className="btn btn-primary" disabled={!canStep2} onClick={submit} style={{ marginTop: 8 }}>Create account</button>
            <p style={{ fontSize: 11, color: 'var(--text-dim)', textAlign: 'center', lineHeight: 1.5, margin: 0 }}>
              By continuing you agree to AITrader's <span style={{ color: 'var(--text)' }}>Terms</span> and <span style={{ color: 'var(--text)' }}>Risk Disclosure</span>. CFDs are complex instruments with high risk of losing money.
            </p>
          </div>
        )}
      </div>

      {showCountries && (
        <div className="modal-bg" onClick={() => setShowCountries(false)}>
          <div className="sheet" onClick={e => e.stopPropagation()}>
            <div className="sheet-handle"></div>
            <h3 style={{ margin: '0 0 12px', fontSize: 20 }}>Country of residence</h3>
            <div className="stack" style={{ gap: 2, maxHeight: 400, overflowY: 'auto' }}>
              {COUNTRIES.map(c => (
                <button key={c.c} onClick={() => { upd('country', c.c); setShowCountries(false); }}
                  className="row between" style={{
                    background: data.country === c.c ? 'var(--card)' : 'transparent',
                    border: '1px solid ' + (data.country === c.c ? 'var(--line)' : 'transparent'),
                    borderRadius: 12, padding: '12px 14px', cursor: 'pointer', color: 'var(--text)', textAlign: 'left'
                  }}>
                  <span className="row" style={{ gap: 12 }}>
                    <span className="country-pill mono" style={{ minWidth: 36, justifyContent: 'center' }}>{c.c}</span>
                    <span>{c.n}</span>
                  </span>
                  <span className="mono" style={{ color: 'var(--text-dim)', fontSize: 13 }}>{c.d}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Login() {
  const { go, login } = useApp();
  const [email, setEmail] = useState('jane@aitrader.io');
  const [pw, setPw] = useState('demo1234');
  const [showPw, setShowPw] = useState(false);

  const submit = () => {
    login({ name: 'Jane Cooper', email, country: 'GB' });
    go('dashboard');
  };

  return (
    <div className="screen page-enter" style={{ position: 'relative' }}>
      <div className="auth-bg"><div className="blob blob-1"></div><div className="blob blob-2"></div></div>
      <StatusBar />
      <AppBar title="" onBack={() => go('splash')} />
      <div style={{ padding: '20px 24px 30px', position: 'relative', zIndex: 1 }}>
        <h1 style={{ fontSize: 30, margin: '0 0 8px', fontWeight: 700, letterSpacing: '-0.02em' }}>Welcome back</h1>
        <p style={{ color: 'var(--text-dim)', fontSize: 14, margin: '0 0 28px' }}>Sign in to your AITrader account.</p>
        <div className="stack" style={{ gap: 16 }}>
          <div className="input-group">
            <label className="input-label">Email</label>
            <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} />
          </div>
          <div className="input-group">
            <label className="input-label">Password</label>
            <input className="input" type={showPw ? 'text' : 'password'} value={pw} onChange={e => setPw(e.target.value)} />
            <button className="input-suffix" onClick={() => setShowPw(s => !s)}>{showPw ? <I.eyeOff /> : <I.eye />}</button>
          </div>
          <div style={{ textAlign: 'right', fontSize: 13 }}>
            <a style={{ color: 'var(--green)', cursor: 'pointer', fontWeight: 500 }}>Forgot password?</a>
          </div>
          <button className="btn btn-primary" onClick={submit}>Sign in</button>
          <div style={{ textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>
            New here? <a onClick={() => go('register')} style={{ color: 'var(--green)', cursor: 'pointer', fontWeight: 500 }}>Create account</a>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Splash = Splash;
window.Register = Register;
window.Login = Login;
window.COUNTRIES = COUNTRIES;
