/* ============================================================
   login.jsx — Email sign-in via Backend.whoami() + lock screen.
   For GAS mode: validates email against Users tab.
   For local mode: any input passes (demo).
   ============================================================ */
const ROLES = [
  { key: 'mt', label: 'นักเทคนิค' },
  { key: 'chief', label: 'หัวหน้าแล็บ' },
  { key: 'admin', label: 'ผู้ดูแลระบบ' },
];

function LabomniqBrand({ large = false }) {
  return <div className={`lab-brand${large ? ' lab-brand-large' : ''}`}>
    <img src="assets/labomniq/mark.svg" width="42" height="42" alt="" />
    <div className="lab-brand-copy"><div className="lab-brand-name">LABOMNIQ<span>.</span></div><div className="lab-brand-tag">LABORATORY INTELLIGENCE</div>{large && <div className="lab-brand-platform">Laboratory Asset Intelligence Platform</div>}</div>
  </div>;
}

function LoginScreen({ onEnter, instruments, labomniq = false }) {
  const isGas = window.Backend && window.Backend.mode === 'gas';
  // headline stats: prefer the public summary endpoint (works before sign-in,
  // when the full DB is no longer readable anonymously); fall back to computing
  // from instruments when available (local mode / already authorized)
  const [summary, setSummary] = useState(null);
  useEffect(() => {
    if (window.Backend && window.Backend.summary) {
      window.Backend.summary().then(function (r) { if (r && r.ok && r.summary) setSummary(r.summary); });
    }
  }, []);
  const stats = useMemo(() => {
    if (summary) return summary;
    const act = (instruments || []).filter(i => !(window.isDecommissioned && window.isDecommissioned(i)));
    const depts = new Set(act.map(i => i.dept).filter(Boolean));
    let ready = 0, warn = 0;
    act.forEach(i => { const k = window.statusOf(i).key; if (k === 'ok' || k === 'warn') ready++; if (k === 'warn') warn++; });
    return { total: act.length, depts: depts.size, rate: act.length ? Math.round(ready / act.length * 100) : 0, warn };
  }, [instruments, summary]);
  const [emailVal, setEmailVal] = useState(window.Backend ? window.Backend.getEmail() : '');
  const [gpass, setGpass] = useState('');
  const [gshow, setGshow] = useState(false);
  const [user, setUser] = useState('mt.staff');
  const [pass, setPass] = useState('labops2569');
  const [show, setShow] = useState(false);
  const [role, setRole] = useState('mt');
  const [remember, setRemember] = useState(true);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [reqBusy, setReqBusy] = useState(false);
  const [reqSent, setReqSent] = useState(false);
  const [reqOpen, setReqOpen] = useState(false);
  const [reqName, setReqName] = useState('');
  const [reqDept, setReqDept] = useState('');

  const sendRequest = async () => {
    const em = emailVal.trim().toLowerCase();
    if (!em || !em.includes('@')) { setErr('กรุณากรอกอีเมล Google ก่อนส่งคำขอ'); return; }
    if (!reqName.trim()) { setErr('กรุณากรอกชื่อ-สกุลผู้ขอใช้งาน'); return; }
    setReqBusy(true); setErr('');
    try {
      const res = await window.Backend.requestAccess({ email: em, name: reqName.trim(), dept: reqDept.trim() });
      if (res && res.ok) setReqSent(true);
      else setErr((res && res.message) || 'ส่งคำขอไม่สำเร็จ ลองใหม่อีกครั้ง');
    } catch (e) { setErr('ส่งคำขอไม่สำเร็จ ลองใหม่อีกครั้ง'); }
    setReqBusy(false);
  };

  const submitGas = async (e) => {
    e && e.preventDefault();
    const em = emailVal.trim().toLowerCase();
    if (!em || !em.includes('@')) { setErr('กรุณากรอกอีเมล Google ให้ถูกต้อง'); return; }
    if (!gpass) { setErr('กรุณากรอกรหัสผ่าน'); return; }
    setBusy(true); setErr('');
    try {
      const res = await window.Backend.whoami(gpass, em);
      if (res.ok && res.user) {
        onEnter({ user: res.user.name || em, email: em, role: res.user.role || 'user', gasUser: res.user, remember, mustChange: !!res.mustChange });
      } else {
        setErr(res.message || 'อีเมลนี้ยังไม่ได้รับสิทธิ์เข้าใช้ระบบ กรุณาติดต่อผู้ดูแลระบบ');
      }
    } catch (ex) {
      setErr('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้ ลองอีกครั้ง');
    }
    setBusy(false);
  };

  const submitLocal = (e) => {
    e && e.preventDefault();
    setBusy(true);
    setTimeout(() => onEnter({ user, role, remember }), 540);
  };

  if (labomniq) return (
    <div className="lab-login">
      <div className="lab-login-photo" aria-hidden="true" />
      <div className="lab-login-hospital"><img className="lab-login-logo" src="assets/brand/hospital-logo.webp" width="52" height="52" alt="" /><div><b>โรงพยาบาลอำนาจเจริญ</b><small>กลุ่มงานเทคนิคการแพทย์และพยาธิวิทยาคลินิก</small></div></div>
      <div className="lab-login-layout">
        <section className="lab-login-intro" aria-label="LABOMNIQ ระบบบริหารจัดการเครื่องมือห้องปฏิบัติการ">
          <LabomniqBrand large />
          <div className="lab-login-description"><h1>ระบบบริหารจัดการเครื่องมือ<br className="lab-intro-break" />ห้องปฏิบัติการ</h1></div>
          <div className="lab-login-rule" />
          <div className="lab-login-capabilities">
            {[[I.dash, 'Smart Asset', 'Management'], [I.trend, 'Data Analytics', '& Dashboard'], [I.shield, 'Quality &', 'Compliance'], [I.sliders, 'Calibration &', 'Maintenance']].map(([Icon, first, second]) => <div key={first}><span><Icon size={31} /></span>{first}<br />{second}</div>)}
          </div>
          <div className="lab-login-motto">LABORATORY <span>·</span> PEOPLE <span>·</span> DATA <span>·</span> BETTER CARE</div>
        </section>
        <form className="lab-auth-form" onSubmit={isGas ? submitGas : submitLocal}>
          <div className="lab-auth-heading"><h2>เข้าสู่ระบบ</h2><p>Sign in to your account</p></div>
          <div className="lab-auth-field">
            <label htmlFor="lab-login-user">{isGas ? 'อีเมล' : 'ชื่อผู้ใช้ / รหัสพนักงาน'}</label>
            <div className="lab-auth-input"><I.user size={18} />
              {isGas ? <input id="lab-login-user" type="email" value={emailVal} onChange={e => { setEmailVal(e.target.value); setErr(''); }} placeholder="example@gmail.com" autoComplete="email" autoFocus={!window.matchMedia('(max-width: 800px), (max-height: 760px)').matches} /> : <input id="lab-login-user" value={user} onChange={e => setUser(e.target.value)} placeholder="ชื่อผู้ใช้" autoComplete="username" />}
            </div>
          </div>
          <div className="lab-auth-field">
            <label htmlFor="lab-login-password">รหัสผ่าน</label>
            <div className="lab-auth-input"><I.lock size={18} />
              <input id="lab-login-password" type={(isGas ? gshow : show) ? 'text' : 'password'} value={isGas ? gpass : pass} onChange={e => { if (isGas) { setGpass(e.target.value); setErr(''); } else setPass(e.target.value); }} placeholder="รหัสผ่าน" autoComplete="current-password" />
              <button type="button" className="lab-auth-eye" onClick={() => isGas ? setGshow(s => !s) : setShow(s => !s)} aria-label={(isGas ? gshow : show) ? 'ซ่อนรหัสผ่าน' : 'แสดงรหัสผ่าน'} aria-pressed={isGas ? gshow : show}>{(isGas ? gshow : show) ? <I.eyeoff size={18} /> : <I.eye size={18} />}</button>
            </div>
          </div>
          {!isGas && <div className="lab-auth-field"><label>บทบาท</label><div className="auth-segrole">{ROLES.map(r => <button type="button" key={r.key} className={role === r.key ? 'on' : ''} onClick={() => setRole(r.key)}>{r.label}</button>)}</div></div>}
          {err && <div className="lab-auth-error" role="alert">{err}</div>}
          <label className="lab-auth-remember"><input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} /> จดจำฉัน</label>
          <button className="lab-auth-submit" type="submit" disabled={busy}>{busy ? <><I.refresh size={18} style={{ animation: 'spin 1s linear infinite' }} /> กำลังตรวจสอบ…</> : <><I.unlock size={18} /> เข้าสู่ระบบ</>}</button>
          {isGas ? <div className="lab-auth-access">
            {reqSent ? <div className="lab-auth-success" role="status"><I.check size={17} /> ส่งคำขอแล้ว — ผู้ดูแลจะเปิดสิทธิ์ให้เร็วๆ นี้</div> : reqOpen ? <div className="lab-auth-request">
              <label htmlFor="lab-request-name">ชื่อ-สกุล / ตำแหน่ง</label><input id="lab-request-name" className="input" value={reqName} onChange={e => { setReqName(e.target.value); setErr(''); }} placeholder="เช่น ทนพ. สมชาย ใจดี" autoComplete="name" />
              <label htmlFor="lab-request-dept">หน่วยงาน / แผนก (ถ้ามี)</label><input id="lab-request-dept" className="input" value={reqDept} onChange={e => setReqDept(e.target.value)} placeholder="หน่วยงาน / แผนก" />
              <div><button type="button" className="btn btn-primary btn-sm" onClick={sendRequest} disabled={reqBusy}>{reqBusy ? 'กำลังส่งคำขอ…' : 'ส่งคำขอ'}</button><button type="button" className="btn btn-sm" onClick={() => setReqOpen(false)}>ยกเลิก</button></div>
            </div> : <>ยังไม่มีสิทธิ์เข้าใช้งาน? <button type="button" onClick={() => { setReqOpen(true); setErr(''); }}>ส่งคำขอสิทธิ์ถึงผู้ดูแล</button></>}
          </div> : <><div className="auth-sso"><button type="button" onClick={submitLocal}><I.scan size={17} /> บัตรพนักงาน</button><button type="button" onClick={submitLocal}><I.finger size={17} /> ลายนิ้วมือ</button></div><div className="lab-auth-access">โหมดสาธิต — กด "เข้าสู่ระบบ" ได้เลยโดยไม่ต้องกรอกข้อมูลจริง</div></>}
          <AppCredit variant="login" />
        </form>
        <div className="lab-login-quote" aria-hidden="true">SMART ASSETS<br />SAFER LABS<br />BETTER CARE<span /></div>
      </div>
    </div>
  );

  return (
    <div className="auth">
      {/* animated landing background (full screen); the login card floats centered on top */}
      <div className="auth-show"><div className="auth-scan" /></div>

      {/* form */}
      <div className="auth-form">
        {isGas ? (
          <form className="auth-card" onSubmit={submitGas} style={{ position: 'relative' }}>
            <img className="auth-org-logo" src="assets/brand/hospital-logo.webp" width="112" height="113"
              alt="ตราโรงพยาบาลอำนาจเจริญ กระทรวงสาธารณสุข" />
            <div className="auth-title">LabInstrument</div>
            <div className="auth-sub">ระบบจัดการเครื่องมือทางห้องปฏิบัติการ</div>
            <div className="auth-sub auth-sub2">กลุ่มงานเทคนิคการแพทย์และ<span style={{ whiteSpace: 'nowrap' }}>พยาธิวิทยาคลินิก</span></div>

            <div className="auth-field">
              <label className="field-label">อีเมล</label>
              <div className="auth-inputwrap">
                <I.user className="ico" size={17} />
                <input type="email" value={emailVal} onChange={e => { setEmailVal(e.target.value); setErr(''); }} placeholder="example@gmail.com" autoComplete="email" autoFocus />
              </div>
            </div>

            <div className="auth-field">
              <label className="field-label">รหัสผ่าน</label>
              <div className="auth-inputwrap">
                <I.lock className="ico" size={17} />
                <input type={gshow ? 'text' : 'password'} value={gpass} onChange={e => { setGpass(e.target.value); setErr(''); }} placeholder="รหัสผ่าน" autoComplete="current-password" />
                <button type="button" className="auth-eye" onClick={() => setGshow(s => !s)} title={gshow ? 'ซ่อน' : 'แสดง'}>
                  {gshow ? <I.eyeoff size={17} /> : <I.eye size={17} />}
                </button>
              </div>
            </div>

            {err && <div style={{ color: 'var(--danger-ink)', fontSize: 13, padding: '6px 0', lineHeight: 1.5 }}>{err}</div>}

            <div className="auth-row">
              <label className="auth-check"><input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} /> จดจำฉัน</label>
            </div>

            <button className="auth-submit" type="submit" disabled={busy}>
              {busy ? <><I.refresh size={18} style={{ animation: 'spin 1s linear infinite' }} /> กำลังตรวจสอบ…</> : <><I.unlock size={18} /> เข้าสู่ระบบ</>}
            </button>

            <div className="auth-demo">
              {reqSent ? (
                <span style={{ color: 'var(--ok-ink)', fontWeight: 600 }}>✓ ส่งคำขอแล้ว — ผู้ดูแลจะเปิดสิทธิ์ให้เร็วๆ นี้</span>
              ) : reqOpen ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, textAlign: 'left' }}>
                  <input className="input" value={reqName} onChange={e => { setReqName(e.target.value); setErr(''); }} placeholder="ชื่อ-สกุล / ตำแหน่ง (เช่น ทนพ. สมชาย ใจดี)" />
                  <input className="input" value={reqDept} onChange={e => setReqDept(e.target.value)} placeholder="หน่วยงาน / แผนก (ถ้ามี)" />
                  <div style={{ display: 'flex', gap: 8 }}>
                    <button type="button" className="btn btn-primary btn-sm" onClick={sendRequest} disabled={reqBusy} style={{ flex: 1 }}>{reqBusy ? 'กำลังส่งคำขอ…' : 'ส่งคำขอ'}</button>
                    <button type="button" className="btn btn-sm" onClick={() => setReqOpen(false)}>ยกเลิก</button>
                  </div>
                </div>
              ) : (
                <>ยังไม่มีสิทธิ์เข้าใช้งาน? <button type="button" onClick={() => { setReqOpen(true); setErr(''); }} style={{ background: 'none', border: 'none', color: 'var(--accent-ink)', fontWeight: 600, fontFamily: 'inherit', fontSize: 'inherit', cursor: 'pointer', padding: 0 }}>ส่งคำขอสิทธิ์ถึงผู้ดูแล</button></>
              )}
            </div>
          </form>
        ) : (
          <form className="auth-card" onSubmit={submitLocal}>
            <div className="auth-title">เข้าสู่ระบบ</div>
            <div className="auth-sub">ลงชื่อเข้าใช้เพื่อจัดการเครื่องมือห้องปฏิบัติการ</div>

            <div className="auth-field">
              <label className="field-label">ชื่อผู้ใช้ / รหัสพนักงาน</label>
              <div className="auth-inputwrap">
                <I.user className="ico" size={17} />
                <input value={user} onChange={e => setUser(e.target.value)} placeholder="ชื่อผู้ใช้" autoComplete="username" />
              </div>
            </div>

            <div className="auth-field">
              <label className="field-label">รหัสผ่าน</label>
              <div className="auth-inputwrap">
                <I.lock className="ico" size={17} />
                <input type={show ? 'text' : 'password'} value={pass} onChange={e => setPass(e.target.value)} placeholder="รหัสผ่าน" autoComplete="current-password" />
                <button type="button" className="auth-eye" onClick={() => setShow(s => !s)} title={show ? 'ซ่อน' : 'แสดง'}>
                  {show ? <I.eyeoff size={17} /> : <I.eye size={17} />}
                </button>
              </div>
            </div>

            <div className="auth-field">
              <label className="field-label">บทบาท</label>
              <div className="auth-segrole">
                {ROLES.map(r => (
                  <button type="button" key={r.key} className={role === r.key ? 'on' : ''} onClick={() => setRole(r.key)}>{r.label}</button>
                ))}
              </div>
            </div>

            <div className="auth-row">
              <label className="auth-check"><input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} /> จดจำฉัน</label>
              <span className="auth-link">ลืมรหัสผ่าน?</span>
            </div>

            <button className="auth-submit" type="submit" disabled={busy}>
              {busy ? <><I.refresh size={18} style={{ animation: 'spin 1s linear infinite' }} /> กำลังเข้าสู่ระบบ…</> : <><I.unlock size={18} /> เข้าสู่ระบบ</>}
            </button>

            <div className="auth-or">หรือ</div>
            <div className="auth-sso">
              <button type="button" onClick={submitLocal}><I.scan size={17} /> บัตรพนักงาน</button>
              <button type="button" onClick={submitLocal}><I.finger size={17} /> ลายนิ้วมือ</button>
            </div>

            <div className="auth-demo">โหมดสาธิต — กด "เข้าสู่ระบบ" ได้เลยโดยไม่ต้องกรอกข้อมูลจริง</div>
          </form>
        )}
        <AppCredit variant="login" />
      </div>
    </div>
  );
}

function LockScreen({ userName, userEmail, onUnlock, onLogout }) {
  const [now, setNow] = useState(new Date());
  const [pass, setPass] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  // the page behind stays in the DOM (blurred) — keep Tab/Enter from reaching
  // its buttons while locked. The lock itself is portalled outside #root.
  useEffect(() => {
    const root = document.getElementById('root');
    if (root) root.inert = true;
    return () => { if (root) root.inert = false; };
  }, []);

  // unlocking = the same password check as signing in (server-side, so the
  // 5-wrong-tries lockout applies here too); a fresh token comes back with it
  const submit = async (e) => {
    e && e.preventDefault();
    if (busy) return;
    if (!pass) { setErr('กรุณากรอกรหัสผ่าน'); return; }
    setBusy(true); setErr('');
    try {
      const res = await window.Backend.whoami(pass);
      const who = res && res.user && String(res.user.email || '').trim().toLowerCase();
      if (!res || !res.ok || !res.user) {
        setErr((res && res.message) || 'รหัสผ่านไม่ถูกต้อง');
      } else if (userEmail && who && who !== String(userEmail).trim().toLowerCase()) {
        // another account signed in on this browser meanwhile
        setErr('บัญชีไม่ตรงกับผู้ที่ล็อกหน้าจอไว้ — กรุณาออกจากระบบแล้วเข้าใหม่');
      } else {
        setPass(''); setBusy(false);
        onUnlock();
        return;
      }
    } catch (ex) {
      setErr('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้ ลองอีกครั้ง');
    }
    setPass(''); setBusy(false);
  };
  const hh = String(now.getHours()).padStart(2, '0');
  const mm = String(now.getMinutes()).padStart(2, '0');
  const dateStr = `${['อาทิตย์','จันทร์','อังคาร','พุธ','พฤหัสบดี','ศุกร์','เสาร์'][now.getDay()]} ${now.getDate()} ${THMONTH[now.getMonth()]} ${now.getFullYear() + 543}`;
  const initials = (userName || 'MT').slice(0, 2).toUpperCase();

  return ReactDOM.createPortal(
    <div className="lock">
      <div className="lock-card enter">
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)', marginBottom: 18, border: '1px solid var(--line)', borderRadius: 99, padding: '5px 12px', whiteSpace: 'nowrap' }}>
          <I.lock size={13} /> หน้าจอถูกล็อก
        </div>
        <div className="lock-clock">{hh}<span style={{ opacity: .4 }}>:</span>{mm}</div>
        <div className="lock-date">{dateStr}</div>

        <div className="lock-user">
          <div className="lock-avatar">{initials}</div>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontWeight: 600, fontSize: 15 }}>{userName || 'นักเทคนิคการแพทย์'}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>ผู้ดูแลเครื่องมือ</div>
          </div>
        </div>

        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div className="auth-inputwrap">
            <I.lock className="ico" size={17} />
            <input type="password" value={pass} onChange={e => { setPass(e.target.value); if (err) setErr(''); }} placeholder="ป้อนรหัสผ่านเพื่อปลดล็อก" autoComplete="current-password" autoFocus />
          </div>
          {err && <div role="alert" style={{ color: 'var(--danger-ink)', fontSize: 13, padding: '2px 0', lineHeight: 1.5 }}>{err}</div>}
          <button className="auth-submit" type="submit" disabled={busy}>
            {busy ? <><I.refresh size={18} style={{ animation: 'spin 1s linear infinite' }} /> กำลังตรวจสอบ…</> : <><I.unlock size={18} /> ปลดล็อก</>}
          </button>
          <button type="button" onClick={onLogout} style={{ background: 'none', border: 'none', color: 'var(--ink-3)', fontFamily: 'inherit', fontSize: 13, cursor: 'pointer', padding: 6 }}>ออกจากระบบ</button>
        </form>
      </div>
    </div>,
    document.body
  );
}

window.LoginScreen = LoginScreen;
window.LockScreen = LockScreen;
