// ===========================================================
// 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 submit = (e) => {
    e && e.preventDefault();
    setError(null);
    const raw = email.trim();
    if (!raw) { setError('Nhập email hoặc số điện thoại.'); return; }
    // Tài khoản nhân viên cài sẵn (src/accounts.js) + tài khoản Admin tạo thêm trong app — tìm theo EMAIL hoặc SĐT
    const S = window.TVS_SESSION;
    const u = window.tvsFindAccount(raw);
    if (!u) {
      setError(window.tvsLooksLikePhone(raw) ? 'Số điện thoại này chưa được cấp tài khoản. Liên hệ Admin.' : 'Email không tồn tại trong hệ thống. Liên hệ Admin để được cấp tài khoản.');
      return;
    }
    if (!u.pwdHash && !u.pwd) { setError('Tài khoản này chưa có mật khẩu — Admin vào Cài đặt → Người dùng để tạo lại.'); return; }
    if (!window.tvsCheckPassword(u, password)) { setError('Mật khẩu không đúng.'); return; }
    if (u.status === 'inactive') { setError('Tài khoản đã tạm khoá. Liên hệ Admin để mở lại.'); return; }
    // "Chờ kích hoạt" (tài khoản tạo trong app) → tự kích hoạt ở lần đăng nhập đầu
    if (u.status === 'pending' && u._ref) { u._ref.status = 'active'; u._ref.last = 'Vừa đăng nhập'; S._persist && S._persist(); S.emit && S.emit(); }
    setLoading(true);
    setTimeout(() => onLogin && onLogin((u.roles && u.roles[0]) || 'instore', { name: u.name, team: u.team, email: u.email, phone: u.phone, roles: u.roles || [] }), 700);
  };


  return (
    <div className="auth-split" style={{minHeight:'100vh',display:'grid',gridTemplateColumns:'1fr 1fr',background:'var(--bg-page)'}}>
      {/* LEFT — Brand panel */}
      <div className="auth-brand-panel" 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 hoặc số điện thoại và mật khẩu do Admin cấp.
              </p>

              <form onSubmit={submit}>
                <div className="field-label">Email hoặc số điện thoại</div>
                <input className="input mb-3" type="text" autoComplete="username" value={email} onChange={(e)=>{setEmail(e.target.value); setError(null);}} placeholder="ten@tvs.vn hoặc 0903 xxx xxx" 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'}}
                onClick={() => window.tvsDemo('Đăng nhập SSO Microsoft 365')}>
                <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" value={email} onChange={(e)=>setEmail(e.target.value)} placeholder="ten@tvs.vn"/>
              <button className="btn btn-primary btn-lg" style={{width:'100%',justifyContent:'center'}}
                onClick={() => {
                  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { window.tvsToast('Nhập email hợp lệ trước đã', 'demo'); return; }
                  window.tvsToast('Đã gửi link đặt lại mật khẩu tới ' + email);
                  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;
