/* ============================================================================
   BetPrince Sportsbook — Auth (Login / Sign up) + login gate. -> window.
   Browsing is open; key actions (bet, deposit, withdraw, bets, profile) gate.
   ============================================================================ */

const SB_COUNTRIES = [
  { code: 'NG', name: 'Nigeria', flag: 'ng', dial: '+234' },
  { code: 'GH', name: 'Ghana', flag: 'gh', dial: '+233' },
  { code: 'KE', name: 'Kenya', flag: 'ke', dial: '+254' },
  { code: 'ZA', name: 'South Africa', flag: 'za', dial: '+27' },
  { code: 'CM', name: 'Cameroon', flag: 'cm', dial: '+237' },
  { code: 'TZ', name: 'Tanzania', flag: 'tz', dial: '+255' },
  { code: 'UG', name: 'Uganda', flag: 'ug', dial: '+256' },
  { code: 'GB', name: 'United Kingdom', flag: 'gb', dial: '+44' },
];

/* labelled input ----------------------------------------------------------- */
function AuthField({ label, optional, icon, children }) {
  return (
    <label style={{ display: 'block', marginBottom: 14 }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 7,
        fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5, color: 'var(--ink-2)' }}>
        {icon && <Icon name={icon} size={14} color="var(--ink-3)" />}
        {label}
        {optional && <span style={{ fontWeight: 600, fontSize: 11.5, color: 'var(--ink-3)' }}>· optional</span>}
      </span>
      {children}
    </label>
  );
}

const AUTH_INPUT = {
  width: '100%', boxSizing: 'border-box', background: 'var(--card-2)',
  border: '1px solid var(--line-2)', borderRadius: 12, padding: '14px 15px',
  fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 15, color: 'var(--ink)', outline: 'none',
};

/* Full auth screen — login / signup toggle -------------------------------- */
function AuthScreen({ mode, onMode, onSubmit, onClose }) {
  const isSignup = mode === 'signup';
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [country, setCountry] = useState('NG');
  const [promo, setPromo] = useState('');
  const [pwd, setPwd] = useState('');
  const [showPwd, setShowPwd] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);

  useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

  const emailOk = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim());
  const pwdOk = pwd.length >= 8;
  const valid = isSignup ? (name.trim().length > 1 && emailOk && pwdOk) : (emailOk && pwdOk);

  const submit = async () => {
    if (!valid || busy) return;
    setBusy(true);
    setErr(null);
    try {
      let r;
      if (isSignup) {
        r = await BP_API.signup(email.trim().toLowerCase(), pwd, name.trim());
      } else {
        r = await BP_API.login(email.trim().toLowerCase(), pwd);
      }
      onSubmit(r); // { user, balance, token }
    } catch (e) {
      const code = (e.body && e.body.error) || e.message;
      const friendly = {
        email_taken: 'That email is already registered. Try logging in.',
        invalid_credentials: 'Email or password is wrong.',
        invalid_input: 'Please check the form and try again.',
      };
      setErr(friendly[code] || ('Could not ' + (isSignup ? 'sign up' : 'log in') + ': ' + code));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ minHeight: '100%', background: 'var(--bg)' }}>
      {/* branded hero */}
      <div style={{ background: 'var(--header-bg)', padding: '18px 18px 30px', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -40, right: -30, width: 150, height: 150, borderRadius: '50%',
          background: 'var(--gold)', opacity: 0.16 }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Wordmark size={22} />
          <button onClick={onClose} aria-label="Close" style={{ width: 36, height: 36, borderRadius: 999,
            background: 'rgba(255,255,255,0.14)', border: 'none', cursor: 'pointer', color: 'var(--header-ink)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="x" size={20} />
          </button>
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26, color: 'var(--header-ink)',
          letterSpacing: '-0.01em', marginTop: 20 }}>
          {isSignup ? 'Create your account' : 'Welcome back'}
        </div>
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 13.5, color: 'rgba(255,255,255,0.72)', marginTop: 4 }}>
          {isSignup ? 'Join BetPrince in under a minute.' : 'Log in to bet, deposit and cash out.'}
        </div>
      </div>

      {/* form card pulled up over the hero */}
      <div style={{ margin: '-16px 14px 24px', background: 'var(--card)', borderRadius: 18,
        border: '1px solid var(--line)', boxShadow: 'var(--shadow-pop)', padding: '16px 16px 20px' }}>
        {/* segmented toggle */}
        <div style={{ display: 'flex', gap: 6, background: 'var(--card-2)', border: '1px solid var(--line)',
          borderRadius: 12, padding: 4, marginBottom: 18 }}>
          {[['login', 'Log in'], ['signup', 'Sign up']].map(([k, l]) => {
            const on = mode === k;
            return (
              <button key={k} onClick={() => onMode(k)} style={{ flex: 1, padding: '11px', borderRadius: 9,
                border: 'none', cursor: 'pointer', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5,
                background: on ? 'var(--blue)' : 'transparent', color: on ? 'var(--blue-ink)' : 'var(--ink-3)',
                transition: 'background 140ms' }}>{l}</button>
            );
          })}
        </div>

        {isSignup && (
          <AuthField label="Full name" icon="user">
            <input value={name} onChange={(e) => setName(e.target.value)}
              style={AUTH_INPUT} />
          </AuthField>
        )}

        <AuthField label="Email" icon="mail">
          <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" inputMode="email"
            onKeyDown={(e) => e.key === 'Enter' && submit()}
            style={AUTH_INPUT} />
        </AuthField>

        {isSignup && (
          <AuthField label="Country" icon="globe">
            <div style={{ position: 'relative' }}>
              <img src={`https://flagcdn.com/w40/${(SB_COUNTRIES.find(c => c.code === country) || {}).flag}.png`}
                alt="" style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
                  width: 22, height: 15, objectFit: 'cover', borderRadius: 2, pointerEvents: 'none' }} />
              <select value={country} onChange={(e) => setCountry(e.target.value)}
                style={{ ...AUTH_INPUT, paddingLeft: 46, appearance: 'none', cursor: 'pointer' }}>
                {SB_COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}
              </select>
              <Icon name="chevron-down" size={18} style={{ position: 'absolute', right: 14, top: '50%',
                transform: 'translateY(-50%)', color: 'var(--ink-3)', pointerEvents: 'none' }} />
            </div>
          </AuthField>
        )}

        <AuthField label="Password" icon="lock">
          <div style={{ position: 'relative' }}>
            <input value={pwd} onChange={(e) => setPwd(e.target.value)} type={showPwd ? 'text' : 'password'}
              onKeyDown={(e) => e.key === 'Enter' && submit()}
              style={{ ...AUTH_INPUT, paddingRight: 46 }} />
            <button type="button" onClick={() => setShowPwd(s => !s)} aria-label="Toggle password"
              style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', width: 32, height: 32,
                borderRadius: 8, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--ink-3)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={showPwd ? 'eye-off' : 'eye'} size={18} />
            </button>
          </div>
          {isSignup && pwd.length > 0 && !pwdOk && (
            <span style={{ display: 'block', marginTop: 6, fontFamily: 'var(--font-text)', fontSize: 11.5,
              color: 'var(--live)' }}>
              Must be at least 8 characters.
            </span>
          )}
        </AuthField>

        {isSignup && (
          <AuthField label="Promo code" optional icon="ticket">
            <input value={promo} onChange={(e) => setPromo(e.target.value.toUpperCase())}
              style={{ ...AUTH_INPUT, letterSpacing: '0.04em' }} />
          </AuthField>
        )}

        <div style={{ height: 4 }} />

        {err && (
          <div style={{ background: 'var(--live-bg)', color: 'var(--live)', borderRadius: 10,
            padding: '11px 14px', marginBottom: 10, fontFamily: 'var(--font-text)',
            fontSize: 13, fontWeight: 600 }}>{err}</div>
        )}

        <GoldBtn full disabled={!valid || busy} onClick={submit}>
          {busy ? 'Please wait...' : (isSignup ? 'Create account' : 'Log in')}
        </GoldBtn>

        <div style={{ textAlign: 'center', marginTop: 14, fontFamily: 'var(--font-text)', fontSize: 13, color: 'var(--ink-3)' }}>
          {isSignup ? 'Already have an account? ' : "New to BetPrince? "}
          <span onClick={() => onMode(isSignup ? 'login' : 'signup')}
            style={{ fontWeight: 700, color: 'var(--blue)', cursor: 'pointer' }}>
            {isSignup ? 'Log in' : 'Create one'}
          </span>
        </div>

        {isSignup && (
          <div style={{ textAlign: 'center', marginTop: 14, fontFamily: 'var(--font-text)', fontSize: 11.5,
            color: 'var(--ink-3)', lineHeight: 1.5 }}>
            By continuing you confirm you are 18+ and agree to the Terms & Privacy Policy.
          </div>
        )}
      </div>
    </div>
  );
}

/* Login gate — bottom sheet shown when a logged-out user taps a key action -- */
function LoginGate({ open, action, onClose, onLogin, onSignup }) {
  useEffect(() => { if (open && window.lucide) window.lucide.createIcons(); });
  return (
    <>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 80, background: 'var(--scrim)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'opacity 220ms' }} />
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 90, background: 'var(--card)',
        borderRadius: '24px 24px 0 0', boxShadow: 'var(--shadow-pop)', padding: '10px 18px 26px',
        transform: open ? 'translateY(0)' : 'translateY(110%)',
        transition: 'transform 300ms cubic-bezier(0.22,1,0.36,1)' }}>
        <div style={{ width: 38, height: 4, borderRadius: 999, background: 'var(--line-2)', margin: '0 auto 18px' }} />
        <div style={{ width: 56, height: 56, borderRadius: 16, background: 'var(--blue-tint)', color: 'var(--blue)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
          <Icon name="lock-keyhole" size={26} />
        </div>
        <div style={{ textAlign: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20,
          color: 'var(--ink)', marginBottom: 20 }}>Log in to {action || 'continue'}</div>
        <GoldBtn full onClick={onLogin}>Log in</GoldBtn>
        <div style={{ height: 10 }} />
        <button onClick={onSignup} style={{ width: '100%', background: 'var(--card-2)', color: 'var(--ink)',
          border: '1px solid var(--line-2)', borderRadius: 12, padding: '14px 20px', cursor: 'pointer',
          fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15 }}>Create an account</button>
      </div>
    </>
  );
}

Object.assign(window, { SB_COUNTRIES, AuthScreen, LoginGate, AuthField });
