// ========== LOGIN / SIGN IN / REGISTER ==========
const LoginPage = ({ nav, toast, signIn, initialMode = 'login' }) => {
  // Read optional hint from window.__loginMode (set by TopBar) to open in register mode
  const startMode = (typeof window !== 'undefined' && window.__loginMode) || initialMode;
  const [mode, setMode] = React.useState(startMode); // login | signup
  const [role, setRole] = React.useState('client'); // client | provider
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => { if (typeof window !== 'undefined') window.__loginMode = null; }, []);

  const submit = async () => {
    if (busy) return;
    if (!email || !password) { toast('Email and password are required'); return; }
    if (mode === 'signup' && password.length < 8) { toast('Password must be at least 8 characters'); return; }
    setBusy(true);
    const parts = (name || '').trim().split(/\s+/);
    const firstName = parts[0] || (role === 'provider' ? 'Studio' : 'Friend');
    const lastName = parts.slice(1).join(' ') || (role === 'provider' ? 'Owner' : 'CaribGlow');
    const payload = { mode, role, email: email.trim().toLowerCase(), password, firstName, lastName, name };
    try {
      const result = await (signIn ? signIn(payload) : Promise.resolve());
      if (mode === 'login') {
        toast(`Welcome back!`);
      } else {
        toast(role === 'provider' ? 'Provider account created!' : 'Account created!');
      }
      const finalRole = (result && result.role) || role;
      nav(finalRole === 'provider' ? 'seller-dashboard' : 'landing');
    } catch (e) {
      // App.signIn already toasted the error
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="fade-in auth-layout">
      <div className="auth-side">
        <div className="eyebrow" style={{color:'var(--primary-deep)'}}>
          {mode === 'login' ? 'Welcome back' : role === 'provider' ? 'Join as a provider' : 'Join CaribGlow'}
        </div>
        <h1>
          {mode === 'login'
            ? <>Your <span style={{fontStyle:'italic'}}>glow</span>, ready.</>
            : role === 'provider'
              ? <>Start <span style={{fontStyle:'italic'}}>earning</span>, today.</>
              : <>Let's <span style={{fontStyle:'italic'}}>get you in</span>.</>}
        </h1>
        <p style={{fontSize: 16, color:'var(--ink-2)', marginTop: 10, marginBottom: 18}}>
          {mode === 'login'
            ? 'Sign in to keep booking, messaging, and shopping.'
            : role === 'provider'
              ? 'List your services, manage bookings, and grow your clientele.'
              : "A minute to set up. Then you're booking in seconds."}
        </p>

        {mode === 'signup' && (
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 8, marginBottom: 16}}>
            <button type="button" onClick={() => setRole('client')}
              className={`btn ${role === 'client' ? 'btn-brand' : 'btn-outline'}`}
              style={{padding:'12px 10px', flexDirection:'column', height: 'auto', gap: 2}}>
              <div style={{fontWeight: 700, fontSize: 14}}>I'm a client</div>
              <div style={{fontSize: 11, fontWeight: 400, opacity: 0.85}}>Book & shop</div>
            </button>
            <button type="button" onClick={() => setRole('provider')}
              className={`btn ${role === 'provider' ? 'btn-brand' : 'btn-outline'}`}
              style={{padding:'12px 10px', flexDirection:'column', height: 'auto', gap: 2}}>
              <div style={{fontWeight: 700, fontSize: 14}}>I'm a provider</div>
              <div style={{fontSize: 11, fontWeight: 400, opacity: 0.85}}>Offer services</div>
            </button>
          </div>
        )}

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 8, marginBottom: 14}}>
          <button className="btn btn-outline" style={{padding:'11px 0'}}>
            <span style={{fontWeight: 700}}>G</span> Google
          </button>
          <button className="btn btn-outline" style={{padding:'11px 0'}}>
             Apple
          </button>
        </div>

        <div style={{display:'flex', alignItems:'center', gap: 10, margin:'14px 0'}}>
          <div style={{flex: 1, height: 1, background:'var(--line)'}}/>
          <div style={{fontSize: 11, color:'var(--muted)'}}>OR WITH EMAIL</div>
          <div style={{flex: 1, height: 1, background:'var(--line)'}}/>
        </div>

        {mode === 'signup' && (
          <div className="field"><label>{role === 'provider' ? 'Your name or studio name' : 'Full name'}</label>
            <input value={name} onChange={e => setName(e.target.value)} placeholder={role === 'provider' ? 'Aya Bridal Atelier' : 'Full name'}/>
          </div>
        )}
        <div className="field"><label>Email</label><input type="email" value={email} onChange={e => setEmail(e.target.value)}/></div>
        <div className="field">
          <label style={{display:'flex', justifyContent:'space-between'}}>
            <span>Password</span>
            {mode === 'login' && (
              <span onClick={() => nav('auth')} style={{color:'var(--primary-deep)', fontSize: 12, fontWeight: 500, cursor:'pointer'}}>Forgot?</span>
            )}
          </label>
          <input type="password" autoComplete={mode==='signup' ? 'new-password' : 'current-password'} value={password} onChange={e => setPassword(e.target.value)} placeholder="At least 8 characters"/>
        </div>

        {mode === 'login' && (
          <label style={{display:'flex', gap: 10, alignItems:'center', fontSize: 13, padding:'4px 0 12px'}}>
            <input type="checkbox" defaultChecked/> Keep me signed in
          </label>
        )}

        <button className="btn btn-brand btn-lg" style={{width:'100%'}} onClick={submit} disabled={busy}>
          {busy ? 'Working…' : (mode === 'login' ? 'Sign in' : role === 'provider' ? 'Create provider account' : 'Create account')}
        </button>

        <div style={{textAlign:'center', marginTop: 18, fontSize: 13.5}}>
          {mode === 'login' ? <>
            New to CaribGlow? <span onClick={() => setMode('signup')} style={{color:'var(--primary-deep)', fontWeight: 600, cursor:'pointer', textDecoration:'underline'}}>Create account</span>
          </> : <>
            Already have an account? <span onClick={() => setMode('login')} style={{color:'var(--primary-deep)', fontWeight: 600, cursor:'pointer', textDecoration:'underline'}}>Sign in</span>
          </>}
        </div>

        <div style={{textAlign:'center', marginTop: 10, fontSize: 11.5, color:'var(--muted)'}}>
          By continuing you agree to our Terms and Privacy Policy.
        </div>
      </div>

      <div className="auth-visual">
        <div style={{position:'absolute', inset: 0, display:'grid', placeItems:'center', color:'#fff', textAlign:'center', padding: 40}}>
          <div>
            <div style={{fontSize: 84, marginBottom: 16}}>✦</div>
            <div style={{fontFamily:'Fraunces, serif', fontSize: 38, fontWeight: 500, letterSpacing:'-0.02em', lineHeight: 1.05}}>
              {mode === 'signup' && role === 'provider'
                ? <>Your chair,<br/><em>fully booked.</em></>
                : <>Caribbean beauty,<br/><em>one tap away.</em></>}
            </div>
            <div style={{marginTop: 16, fontSize: 15, opacity: 0.9, maxWidth: 320, margin:'16px auto 0', lineHeight: 1.5}}>
              {mode === 'signup' && role === 'provider'
                ? 'Earn with CaribGlow. Free to list, verified profile, instant booking.'
                : 'Verified Caribbean pros · Marketplace · Instant booking.'}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { LoginPage });
