// Login Page — White BG with Orange Circles
const { useState: lgSt, useRef: lgRf } = React;

function LoginPage({ onLogin }) {
  const [step, setStep]       = lgSt(1);
  const [email, setEmail]     = lgSt('');
  const [otp, setOtp]         = lgSt(['','','','','','']);
  const [genOtp, setGenOtp]   = lgSt('');
  const [err, setErr]         = lgSt('');
  const [loading, setLoading] = lgSt(false);
  const [demoOtp, setDemoOtp] = lgSt('');
  const refs = [lgRf(),lgRf(),lgRf(),lgRf(),lgRf(),lgRf()];

  function handleSendOTP(e) {
    e.preventDefault();
    setErr('');
    if (!email.trim()) { setErr('Please enter your email address.'); return; }
    const user = Store.all('users').find(u => u.email.toLowerCase() === email.toLowerCase());
    if (!user) { setErr('No account found. Try admin@omgroup.com'); return; }
    setLoading(true);
    setTimeout(() => {
      const code = String(Math.floor(100000 + Math.random() * 900000));
      setGenOtp(code); setDemoOtp(code);
      setLoading(false); setStep(2);
      setTimeout(() => refs[0].current?.focus(), 80);
    }, 700);
  }

  function handleOtpChange(i, e) {
    const v = e.target.value.replace(/\D/,'').slice(-1);
    const next = [...otp]; next[i] = v; setOtp(next);
    if (v && i < 5) refs[i+1].current?.focus();
  }
  function handleOtpKey(i, e) {
    if (e.key === 'Backspace' && !otp[i] && i > 0) refs[i-1].current?.focus();
  }
  function handlePaste(e) {
    const p = e.clipboardData.getData('text').replace(/\D/g,'').slice(0,6);
    if (p.length === 6) { setOtp(p.split('')); setTimeout(()=>refs[5].current?.focus(),50); }
  }

  function handleVerify(e) {
    e.preventDefault(); setErr('');
    const entered = otp.join('');
    if (entered.length < 6) { setErr('Please enter the complete 6-digit OTP.'); return; }
    if (entered !== genOtp) { setErr('Invalid OTP. Please try again.'); return; }
    setLoading(true);
    setTimeout(() => {
      const user = Store.login(email);
      setLoading(false);
      if (user) onLogin(user);
      else setErr('Login failed.');
    }, 500);
  }

  return (
    <div className="login-bg">
      {/* Decorative circles */}
      <div className="lc1" /><div className="lc2" /><div className="lc3" /><div className="lc4" />

      <div className="login-card">
        {/* Logo */}
        <div style={{textAlign:'center',marginBottom:24}}>
          <img src="uploads/OM GROUP FULL LOGO-61ed36bc.png" alt="OM Group"
            style={{height:72,maxWidth:'100%',objectFit:'contain',display:'block',margin:'0 auto 12px'}}
            onError={e=>{e.target.style.display='none'}} />
          <p style={{fontSize:13,color:'var(--or)',fontWeight:600,margin:0}}>Log in to your account</p>
        </div>

        {step === 1 ? (
          <form onSubmit={handleSendOTP}>
            {err && (
              <div style={{background:'#FEE2E2',color:'#991B1B',border:'1px solid #FECACA',borderRadius:4,padding:'7px 10px',fontSize:12,marginBottom:12}}>
                {err}
              </div>
            )}
            <div className="fld" style={{marginBottom:12}}>
              <label>Email Address</label>
              <input className="inp" type="email" value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="Enter your email address" required autoFocus />
            </div>
            <div style={{background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:4,padding:'7px 10px',fontSize:11.5,color:'#1E40AF',marginBottom:14,lineHeight:1.6}}>
              <strong>Demo account:</strong> admin@omgroup.com
            </div>
            <button type="submit" className="btn btn-or" disabled={loading}
              style={{width:'100%',justifyContent:'center',height:38,fontSize:13,fontWeight:600}}>
              {loading ? 'Sending OTP…' : 'Send OTP'}
            </button>
          </form>
        ) : (
          <form onSubmit={handleVerify}>
            <div style={{marginBottom:14,fontSize:12,color:'var(--txt2)',lineHeight:1.6}}>
              OTP sent to <strong style={{color:'var(--txt)'}}>{email}</strong>
            </div>
            {demoOtp && (
              <div style={{background:'#FEF3C7',border:'1px solid #FDE68A',borderRadius:4,padding:'7px 10px',fontSize:12,color:'#92400E',marginBottom:12,textAlign:'center'}}>
                <strong>Demo OTP: {demoOtp}</strong>
              </div>
            )}
            {err && (
              <div style={{background:'#FEE2E2',color:'#991B1B',border:'1px solid #FECACA',borderRadius:4,padding:'7px 10px',fontSize:12,marginBottom:12}}>
                {err}
              </div>
            )}
            <div style={{marginBottom:18}} onPaste={handlePaste}>
              <div style={{fontSize:11.5,color:'var(--txt2)',marginBottom:8}}>Enter 6-digit OTP</div>
              <div className="otp-boxes">
                {otp.map((v, i) => (
                  <input key={i} ref={refs[i]} className="otp-box"
                    type="text" inputMode="numeric" value={v} maxLength={1}
                    onChange={e => handleOtpChange(i, e)}
                    onKeyDown={e => handleOtpKey(i, e)} />
                ))}
              </div>
            </div>
            <button type="submit" className="btn btn-or" disabled={loading}
              style={{width:'100%',justifyContent:'center',height:38,fontSize:13,fontWeight:600,marginBottom:8}}>
              {loading ? 'Verifying…' : 'Verify OTP & Sign In'}
            </button>
            <button type="button" className="btn btn-gh"
              onClick={() => { setStep(1); setOtp(['','','','','','']); setErr(''); }}
              style={{width:'100%',justifyContent:'center',fontSize:12}}>
              ← Back
            </button>
          </form>
        )}
      </div>
    </div>
  );
}
window.LoginPage = LoginPage;
