/* =====================================================================
   AI-COS Essential — Sign in (production auth)
   Administrator setup is complete; accounts are provisioned in-app by
   an Admin (Users & Settings) or by ClearLoft.
   ===================================================================== */
function Login({ onEnter }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  const submit = async () => {
    setError(null);
    if (!email.trim() || !password) return setError('Enter your email and password.');
    setBusy(true);
    try {
      const r = await calAuth({ action: 'login', email: email.trim(), password });
      calSetSession(r.token, r.user);
      onEnter(r.user);
    } catch (e) {
      if (e.status === 409) setError('No user accounts are provisioned. Contact ClearLoft (connect@clearloft.in) to set up access.');
      else if (!e.status || e.network) setError('The service is unreachable. Check your connection and try again.');
      else setError(e.message);
    } finally { setBusy(false); }
  };
  const onKey = (e) => { if (e.key === 'Enter') submit(); };

  return (
    <div style={{ height: '100vh', display: 'grid', gridTemplateColumns: '1.05fr 1fr', overflow: 'hidden' }}>
      {/* ---- Left: brand panel ---- */}
      <div style={{ position: 'relative', background: 'linear-gradient(155deg, #0c2138 0%, #102a45 45%, #163a5e 100%)', color: '#fff', padding: '52px 56px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,.05) 1px, transparent 0)', backgroundSize: '26px 26px', opacity: .7 }} />
        <div style={{ position: 'absolute', top: -120, right: -120, width: 380, height: 380, borderRadius: '50%', background: 'radial-gradient(circle, rgba(47,111,237,.45), transparent 65%)', filter: 'blur(10px)' }} />
        <div style={{ position: 'relative', zIndex: 1 }}>
          <BrandLockup size={46} light />
          <div style={{ marginTop: 14, fontSize: 12, color: '#8fa6c4', fontWeight: 600, letterSpacing: '.6px', textTransform: 'uppercase' }}>
            {DB.company.lab}
          </div>
        </div>

        <div style={{ position: 'relative', zIndex: 1, marginTop: 'auto' }}>
          <div className="badge" style={{ background: 'rgba(47,111,237,.18)', color: '#9ec2ff', border: '1px solid rgba(47,111,237,.35)' }}>
            <Icon name="shield" size={12} /> {DB.company.standards}
          </div>
          <h1 style={{ fontSize: 38, fontWeight: 800, letterSpacing: '-1.2px', lineHeight: 1.08, margin: '18px 0 14px', maxWidth: 460 }}>
            Gas monitor calibration, managed end-to-end.
          </h1>
          <p style={{ fontSize: 15, color: '#aebfd6', maxWidth: 440, lineHeight: 1.55 }}>
            Calibration tracking, asset management, certificate generation, NCR &amp; CAPA, document control, email reminders and dashboard reporting — the {DB.company.short} calibration laboratory in one system.
          </p>
          <div className="row" style={{ gap: 26, marginTop: 30 }}>
            {[['7', 'Modules'], ['4', 'Named users'], ['17025', 'Aligned records']].map(([a, b], i) => (
              <div key={i} style={{ borderLeft: i ? '1px solid rgba(255,255,255,.12)' : 'none', paddingLeft: i ? 20 : 0 }}>
                <div style={{ fontSize: 20, fontWeight: 800, whiteSpace: 'nowrap' }}>{a}</div>
                <div style={{ fontSize: 12, color: '#8fa6c4', whiteSpace: 'nowrap' }}>{b}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ position: 'relative', zIndex: 1, marginTop: 34, fontSize: 12, color: '#6f87a6' }}>
          AI-COS Essential · by ClearLoft
        </div>
      </div>

      {/* ---- Right: sign-in ---- */}
      <div style={{ display: 'grid', placeItems: 'center', padding: 40, background: 'var(--bg)' }}>
        <div style={{ width: 380, maxWidth: '100%' }}>
          <div className="eyebrow">Sign in</div>
          <h2 style={{ fontSize: 25, fontWeight: 800, letterSpacing: '-.6px', margin: '6px 0 4px' }}>Welcome back</h2>
          <p className="muted" style={{ fontSize: 13.5, margin: '0 0 18px' }}>Sign in with your named user account.</p>

          {error && (
            <div className="row" style={{ gap: 10, alignItems: 'flex-start', background: 'var(--bad-bg)', border: '1px solid var(--bad-line)', borderRadius: 11, padding: '11px 13px', marginBottom: 16 }}>
              <span style={{ color: 'var(--bad)', flex: 'none', marginTop: 1 }}><Icon name="alert" size={16} /></span>
              <div style={{ fontSize: 12.5, color: 'var(--text-2)', lineHeight: 1.5 }}>{error}</div>
            </div>
          )}

          <label className="eyebrow" style={{ fontSize: 10.5 }}>Email</label>
          <div className="searchbox" style={{ width: '100%', marginTop: 5, marginBottom: 12, cursor: 'text' }}>
            <Icon name="users" size={15} />
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} onKeyDown={onKey} placeholder="you@company.com" autoFocus />
          </div>
          <label className="eyebrow" style={{ fontSize: 10.5 }}>Password</label>
          <div className="searchbox" style={{ width: '100%', marginTop: 5, marginBottom: 18, cursor: 'text' }}>
            <Icon name="lock" size={15} />
            <input type={showPw ? 'text' : 'password'} value={password} onChange={(e) => setPassword(e.target.value)} onKeyDown={onKey} placeholder="••••••••" />
            <span style={{ cursor: 'pointer', display: 'inline-flex' }} onClick={() => setShowPw(!showPw)}><Icon name="eye" size={15} /></span>
          </div>

          <Btn variant="primary" size="lg" style={{ width: '100%', opacity: busy ? .7 : 1 }} iconR="arrowR" onClick={busy ? undefined : submit}>
            {busy ? 'Please wait…' : 'Sign in'}
          </Btn>

          <div className="row" style={{ justifyContent: 'center', gap: 7, marginTop: 16, fontSize: 12, color: 'var(--text-3)' }}>
            <Icon name="lock" size={13} /> Sessions expire after 12 hours · up to 4 named users
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login });
