/* ============ Login page ============ */
function Login({ onLogin }) {
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [show, setShow] = useState(false);
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    const id = email.trim();
    if (!id || !pw) { setErr('กรุณากรอกชื่อผู้ใช้และรหัสผ่าน'); return; }
    setLoading(true);
    const res = await API.login(id, pw);
    if (res.ok && res.data.ok) {
      API.setToken(res.data.token);
      try { await onLogin(res.data.user); } catch (err) { setLoading(false); setErr('โหลดข้อมูลไม่สำเร็จ ลองใหม่อีกครั้ง'); }
    } else {
      setLoading(false);
      setErr((res.data && res.data.msg) || 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง');
    }
  };

  return (
    <div style={{ minHeight: '100%', display: 'flex' }}>
      {/* brand panel */}
      <div className="login-brand" style={{
        flex: 1, background: 'linear-gradient(155deg, var(--primary-dark), var(--primary) 60%, oklch(0.55 0.09 168))',
        color: '#fff', padding: '54px 52px', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ position: 'absolute', right: -90, top: -90, width: 320, height: 320, borderRadius: '50%', background: 'rgba(255,255,255,.06)' }}></div>
        <div style={{ position: 'absolute', right: 40, bottom: -120, width: 280, height: 280, borderRadius: '50%', background: 'rgba(255,255,255,.05)' }}></div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, position: 'relative' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(255,255,255,.16)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 22, backdropFilter: 'blur(8px)' }}>ภ</div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 17 }}>บัญชี·ภาษี</div>
            <div style={{ fontSize: 12, opacity: .8 }}>ระบบจัดเตรียมเอกสารภาษีสำหรับธุรกิจไทย</div>
          </div>
        </div>
        <div style={{ marginTop: 'auto', position: 'relative' }}>
          <div style={{ fontSize: 30, fontWeight: 700, lineHeight: 1.3, letterSpacing: '-.01em' }}>เก็บใบเสร็จ คำนวณ VAT<br />ส่งสำนักงานบัญชี<br />ครบในที่เดียว</div>
          <div style={{ fontSize: 14.5, opacity: .85, marginTop: 16, maxWidth: 380, lineHeight: 1.65 }}>
            สแกนใบกำกับภาษี แยกหมวดรายจ่ายอัตโนมัติ สรุป ภ.พ.30 รายเดือน และแพ็กไฟล์ส่งบัญชีได้ในคลิกเดียว
          </div>
          <div style={{ display: 'flex', gap: 22, marginTop: 30 }}>
            {[['สแกน OCR', 'scan'], ['ภ.พ.30 อัตโนมัติ', 'vat'], ['แพ็กส่งบัญชี', 'package']].map(([t, ic]) => (
              <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, opacity: .92 }}>
                <Icon name={ic} size={17} />{t}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* form */}
      <div style={{ width: 'min(46%, 480px)', minWidth: 340, background: 'var(--surface)', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '40px clamp(28px, 6vw, 60px)' }}>
        <div style={{ maxWidth: 360, width: '100%', margin: '0 auto' }}>
          <h1 style={{ fontSize: 25, fontWeight: 700 }}>เข้าสู่ระบบ</h1>
          <p style={{ color: 'var(--ink-2)', fontSize: 14, marginTop: 6, marginBottom: 26 }}>ยินดีต้อนรับกลับ — กรอกข้อมูลเพื่อเข้าใช้งาน</p>

          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
            <div className="field">
              <label>ชื่อผู้ใช้หรืออีเมล</label>
              <input className="input" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="ชื่อผู้ใช้" autoFocus autoComplete="username" />
            </div>
            <div className="field">
              <label>รหัสผ่าน</label>
              <div style={{ position: 'relative' }}>
                <input className="input" type={show ? 'text' : 'password'} value={pw} onChange={(e) => setPw(e.target.value)} style={{ paddingRight: 42 }} autoComplete="current-password" />
                <button type="button" onClick={() => setShow(!show)} className="x-btn" style={{ position: 'absolute', right: 5, top: 4 }}><Icon name="eye" size={17} /></button>
              </div>
            </div>
            {err && <div className="callout warn" style={{ padding: '9px 12px' }}><Icon name="alert" className="ic" />{err}</div>}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 13 }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 7, color: 'var(--ink-2)', cursor: 'pointer' }}>
                <input type="checkbox" defaultChecked style={{ accentColor: 'var(--primary)', width: 15, height: 15 }} /> จดจำการเข้าสู่ระบบ
              </label>
              <a style={{ color: 'var(--primary)', fontWeight: 600 }}>ลืมรหัสผ่าน?</a>
            </div>
            <button className="btn btn-primary btn-lg btn-block" disabled={loading}>
              {loading ? 'กำลังเข้าสู่ระบบ…' : <><Icon name="logout" className="ic" style={{ transform: 'scaleX(-1)' }} />เข้าสู่ระบบ</>}
            </button>
          </form>

          <div style={{ marginTop: 22, padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 11, border: '1px solid var(--line)', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <Icon name="lock" size={17} style={{ color: 'var(--ink-3)', flexShrink: 0, marginTop: 1 }} />
            <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.6 }}>
              เปิดบัญชีใหม่ต้องได้รับอนุญาตจาก<b>ผู้ดูแลระบบหลัก</b> หรือให้ผู้ดูแลระบบเป็นผู้เพิ่มให้ — กรุณาติดต่อผู้ดูแลระบบเพื่อขอเข้าใช้งาน
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Login = Login;
