// ===========================================================
// Login screen — entry point trước khi vào CRM
// ===========================================================

function AuthScreen({ onLogin }) {
  const [mode, setMode] = useState('login'); // login | forgot
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showQuickRoles, setShowQuickRoles] = useState(false);

  // Đăng nhập thật qua backend (window.TVS_API). onLogin nhận id vai trò thật.
  const doApiLogin = async (em, pwd) => {
    setError(null);
    setLoading(true);
    try {
      const user = await window.TVS_API.login(em.trim().toLowerCase(), pwd);
      if (onLogin) onLogin(user.id);
    } catch (err) {
      setLoading(false);
      setError(err.message || 'Đăng nhập thất bại.');
    }
  };

  const submit = (e) => {
    e && e.preventDefault();
    doApiLogin(email, password);
  };

  const quickLogin = (em, pwd) => doApiLogin(em, pwd || 'TVS@2026');

  return (
    <div style={{minHeight:'100vh',display:'grid',gridTemplateColumns:'1fr 1fr',background:'var(--bg-page)'}}>
      {/* LEFT — Brand panel */}
      <div style={{
        background:'linear-gradient(135deg, var(--vs-dark-blue) 0%, #00347a 60%, #013189 100%)',
        color:'#fff',
        padding:'var(--space-12) var(--space-10)',
        display:'flex',
        flexDirection:'column',
        justifyContent:'space-between',
        position:'relative',
        overflow:'hidden',
      }}>
        <div style={{position:'absolute',right:-100,top:-100,width:480,height:480,background:'radial-gradient(circle,rgba(65,182,230,0.30) 0%,transparent 60%)',borderRadius:'50%'}}/>
        <div style={{position:'absolute',left:-80,bottom:-80,width:340,height:340,background:'radial-gradient(circle,rgba(65,182,230,0.18) 0%,transparent 60%)',borderRadius:'50%'}}/>

        <div style={{position:'relative',zIndex:1}}>
          <img src="assets/logo-horiz-white.png" alt="The Vitamin Shoppe" style={{height:44}}/>
          <div style={{marginTop:8,fontSize:11,letterSpacing:'0.18em',textTransform:'uppercase',color:'var(--vs-light-blue)',fontWeight:700}}>
            Customer Relationship Management
          </div>
        </div>

        <div style={{position:'relative',zIndex:1}}>
          <h1 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:48,lineHeight:1.05,letterSpacing:'-0.01em',margin:'0 0 var(--space-3)',color:'#fff'}}>
            Thrive Every Day.
          </h1>
          <p style={{fontSize:18,lineHeight:1.5,color:'rgba(255,255,255,0.82)',maxWidth:480,margin:0}}>
            Hệ thống CRM nội bộ — quản lý khách hàng, đối tác B2B, và doanh số toàn hệ thống The Vitamin Shoppe Việt Nam.
          </p>
        </div>

        <div style={{position:'relative',zIndex:1,fontSize:12,color:'rgba(255,255,255,0.5)'}}>
          © 2026 The Vitamin Shoppe Vietnam · v1.0.0
        </div>
      </div>

      {/* RIGHT — Form */}
      <div style={{padding:'var(--space-12) var(--space-10)',display:'flex',flexDirection:'column',justifyContent:'center'}}>
        <div style={{maxWidth:420,width:'100%',margin:'0 auto'}}>
          {mode === 'login' ? (
            <>
              <div className="eyebrow">Đăng nhập</div>
              <h2 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:32,margin:'4px 0 var(--space-2)',color:'var(--fg-1)'}}>
                Chào mừng quay lại
              </h2>
              <p className="fg-muted text-sm mb-5">
                Nhập email công ty và mật khẩu để vào hệ thống.
              </p>

              <form onSubmit={submit}>
                <div className="field-label">Email công ty</div>
                <input className="input mb-3" type="email" value={email} onChange={(e)=>{setEmail(e.target.value); setError(null);}} placeholder="ten@tvs.vn" required/>

                <div className="row">
                  <span className="field-label" style={{flex:1}}>Mật khẩu</span>
                  <button type="button" className="text-xs" style={{background:'none',border:'none',color:'var(--vs-light-blue)',cursor:'pointer',fontWeight:700}} onClick={() => setMode('forgot')}>
                    Quên mật khẩu?
                  </button>
                </div>
                <input className="input mb-3" type="password" value={password} onChange={(e)=>{setPassword(e.target.value); setError(null);}} placeholder="••••••••" required/>

                {error && (
                  <div className="banner danger mb-3" style={{padding:'10px 12px'}}>
                    <Icon name="close" size={14}/>
                    <span className="text-sm" style={{flex:1}}>{error}</span>
                  </div>
                )}

                <label className="row mb-5" style={{cursor:'pointer'}}>
                  <input type="checkbox" checked={remember} onChange={(e)=>setRemember(e.target.checked)} style={{accentColor:'var(--vs-dark-blue)'}}/>
                  <span className="text-sm fg-2">Ghi nhớ đăng nhập trên thiết bị này</span>
                </label>

                <button type="submit" className="btn btn-primary btn-lg" style={{width:'100%',justifyContent:'center'}} disabled={loading}>
                  {loading ? (
                    <>
                      <span className="status-dot blue" style={{animation:'pulse 1s infinite'}}/>
                      Đang đăng nhập...
                    </>
                  ) : (
                    <>
                      <Icon name="arrowright" size={16}/>
                      Đăng nhập
                    </>
                  )}
                </button>
              </form>

              <div style={{margin:'var(--space-5) 0',display:'flex',alignItems:'center',gap:12}}>
                <div style={{flex:1,height:1,background:'var(--border-1)'}}/>
                <span className="text-xs fg-muted">hoặc</span>
                <div style={{flex:1,height:1,background:'var(--border-1)'}}/>
              </div>

              <button type="button" className="btn btn-secondary" style={{width:'100%',justifyContent:'center'}}>
                <Icon name="layers" size={16}/>
                Đăng nhập SSO Microsoft 365
              </button>


            </>
          ) : (
            <>
              <div className="eyebrow">Khôi phục mật khẩu</div>
              <h2 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:32,margin:'4px 0 var(--space-2)',color:'var(--fg-1)'}}>
                Quên mật khẩu?
              </h2>
              <p className="fg-muted text-sm mb-5">
                Nhập email công ty, chúng tôi sẽ gửi link đặt lại mật khẩu trong vài phút.
              </p>
              <div className="field-label">Email công ty</div>
              <input className="input mb-4" type="email" defaultValue={email} placeholder="ten@tvs.vn"/>
              <button className="btn btn-primary btn-lg" style={{width:'100%',justifyContent:'center'}} onClick={() => setMode('login')}>
                <Icon name="mail" size={16}/>Gửi link đặt lại
              </button>
              <button className="btn btn-ghost mt-3" style={{width:'100%',justifyContent:'center'}} onClick={() => setMode('login')}>
                <Icon name="arrowleft" size={14}/>Quay lại đăng nhập
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

window.AuthScreen = AuthScreen;
