/* global React, window, Icon */
const { useState: useStateLogin, useEffect: useEffectLogin } = React;

// ── หน้าเข้าสู่ระบบ — ธีมเข้ม ตามโลโก้ FACEINTIME (ขาว/สเลต + ไซแอน) ─────────────
const LG = {
  bg: '#0F151C', card: '#151C25', line: 'rgba(255,255,255,.08)', line2: 'rgba(255,255,255,.14)',
  ink: '#F1F5F9', ink2: '#B6C2D2', ink3: '#7C8A9C', cyan: '#1FD3F5', cyanInk: '#07202A',
};

const GoogleG = () => (
  <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.5l6.7-6.7C35.6 2.5 30.2 0 24 0 14.6 0 6.5 5.4 2.6 13.3l7.8 6C12.3 13.6 17.7 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4 7.1-10 7.1-17.5z"/><path fill="#FBBC05" d="M10.4 28.7A14.5 14.5 0 0 1 9.5 24c0-1.6.3-3.2.8-4.7l-7.8-6A24 24 0 0 0 0 24c0 3.9.9 7.5 2.6 10.7l7.8-6z"/><path fill="#34A853" d="M24 48c6.5 0 11.9-2.1 15.9-5.8l-7.5-5.8c-2.1 1.4-4.9 2.3-8.4 2.3-6.3 0-11.7-4.1-13.6-9.9l-7.8 6C6.5 42.6 14.6 48 24 48z"/></svg>
);

// ปุ่ม "เข้าสู่ระบบด้วย Google" — แสดงเมื่อเซิร์ฟเวอร์ตั้งค่า GOOGLE_CLIENT_ID แล้ว
function GoogleLoginButton() {
  const [on, setOn] = useStateLogin(false);
  useEffectLogin(() => { fetch('/auth/providers').then((r) => r.ok ? r.json() : null).then((d) => setOn(!!(d && d.google))).catch(() => {}); }, []);
  if (!on) return null;
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: LG.ink3, fontSize: 12 }}>
        <span style={{ flex: 1, height: 1, background: LG.line }}/>หรือ<span style={{ flex: 1, height: 1, background: LG.line }}/>
      </div>
      <a href="/auth/google" className="fit-btn-ghost" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, padding: '12px 18px', borderRadius: 12, border: `1px solid ${LG.line2}`, color: LG.ink, textDecoration: 'none', fontWeight: 600, fontSize: 14 }}>
        <GoogleG/> เข้าสู่ระบบด้วย Google
      </a>
    </>
  );
}

// ไอคอนจุดเด่น 3 อย่าง (เส้นบาง ไซแอน)
const FeatIcon = ({ kind }) => {
  const p = { fill: 'none', stroke: LG.cyan, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'face') return <svg width="34" height="34" viewBox="0 0 24 24" {...p}><path d="M4 8V6a2 2 0 0 1 2-2h2M16 4h2a2 2 0 0 1 2 2v2M4 16v2a2 2 0 0 0 2 2h2M16 20h2a2 2 0 0 0 2-2v-2"/><circle cx="12" cy="10" r="3"/><path d="M7 17c1-2 3-3 5-3s4 1 5 3"/></svg>;
  if (kind === 'shift') return <svg width="34" height="34" viewBox="0 0 24 24" {...p}><rect x="3" y="5" width="13" height="14" rx="2"/><path d="M3 9h13M7 3v4M12 3v4"/><circle cx="17.5" cy="16.5" r="4"/><path d="M17.5 14.5v2l1.5 1"/></svg>;
  return <svg width="34" height="34" viewBox="0 0 24 24" {...p}><path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4M9 11h5M9 14h3"/><circle cx="17" cy="17" r="3.2"/><path d="M17 15.2v3.6M16 16.2h1.6a.8.8 0 0 1 0 1.6H16m0 0h1.8"/></svg>;
};

function LoginPage({ onLogin }) {
  const [user, setUser] = useStateLogin('');
  const [pwd, setPwd] = useStateLogin('');
  const [show, setShow] = useStateLogin(false);
  // ข้อความจากขั้นตอน Google (?oauth=unlinked|error&msg=…)
  const [err, setErr] = useStateLogin(() => { try { const q = new URLSearchParams(location.search); return q.get('oauth') && q.get('oauth') !== 'linked' ? (q.get('msg') || 'เข้าสู่ระบบด้วย Google ไม่สำเร็จ') : ''; } catch (_) { return ''; } });
  const [busy, setBusy] = useStateLogin(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    setBusy(true);
    try { await onLogin(user, pwd); }
    catch (e2) { setErr(e2.message || 'เข้าสู่ระบบไม่สำเร็จ'); }
    finally { setBusy(false); }
  };

  const field = { display: 'flex', alignItems: 'center', gap: 10, background: 'rgba(255,255,255,.03)', border: `1px solid ${LG.line2}`, borderRadius: 12, padding: '0 14px' };
  const input = { flex: 1, background: 'transparent', border: 0, outline: 'none', color: LG.ink, fontSize: 15, padding: '13px 0', fontFamily: 'inherit', minWidth: 0 };
  const label = { fontSize: 12.5, fontWeight: 600, color: LG.ink2, marginBottom: 6 };

  return (
    <div className="fit-login" style={{ minHeight: '100vh', background: LG.bg, color: LG.ink, display: 'flex', flexDirection: 'column', fontFamily: 'var(--font-body)' }}>
      {/* แถบบน */}
      <div className="fit-login-top" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 36px', width: '100%', maxWidth: 1240, margin: '0 auto', boxSizing: 'border-box' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="/img/logo.svg" alt="" style={{ width: 34, height: 33 }}/>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 16, letterSpacing: '.02em' }}>FACEINTIME</span>
        </div>
        <span style={{ fontSize: 12.5, color: LG.ink3, letterSpacing: '.04em' }}>faceintime.net</span>
      </div>

      <div className="fit-login-main" style={{ flex: 1, display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 440px', gap: 56, padding: '12px 36px 28px', alignItems: 'center', width: '100%', maxWidth: 1240, margin: '0 auto', boxSizing: 'border-box' }}>
        {/* ซ้าย: ข้อความ + จุดเด่น + ลายน้ำโลโก้ */}
        <div className="fit-login-hero" style={{ position: 'relative', minHeight: 600, overflow: 'hidden', paddingLeft: 12, paddingBottom: 230, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <div style={{ fontSize: 11.5, letterSpacing: '.28em', color: LG.ink3, fontWeight: 600 }}>FACE RECOGNITION &nbsp;•&nbsp; TIME ATTENDANCE</div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'clamp(44px, 5.2vw, 76px)', lineHeight: 1.02, margin: '22px 0 0', letterSpacing: '-.01em' }}>
            ทุกเวลา<br/><span style={{ color: LG.cyan }}>มีความหมาย</span>
          </h1>
          <div style={{ fontSize: 'clamp(15px, 1.4vw, 19px)', color: LG.ink2, marginTop: 16 }}>จัดการเวลางาน กะ และเงินเดือนในที่เดียว</div>

          <div style={{ display: 'flex', alignItems: 'stretch', marginTop: 36, position: 'relative', zIndex: 1 }}>
            {[['face', 'ลงเวลาอัตโนมัติ'], ['shift', 'จัดตารางกะและ OT'], ['pay', 'สรุปข้อมูลเงินเดือน']].map(([k, l], i) => (
              <div key={k} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, padding: '0 26px', borderLeft: i ? `1px solid ${LG.line2}` : 'none', minWidth: 120 }}>
                <FeatIcon kind={k}/>
                <span style={{ fontSize: 13.5, color: LG.ink2, whiteSpace: 'nowrap' }}>{l}</span>
              </div>
            ))}
          </div>

          {/* ลายน้ำ: โลโก้ใหญ่จางๆ */}
          <svg viewBox="0 0 240 232" aria-hidden="true" style={{ position: 'absolute', left: -30, bottom: -170, width: 'min(600px, 95%)', opacity: .9, pointerEvents: 'none' }}>
            <path d="M78 46h84a26 26 0 0 1 26 26v84a26 26 0 0 1-26 26H78a26 26 0 0 1-26-26V72a26 26 0 0 1 26-26z" fill="none" stroke="rgba(255,255,255,.06)" strokeWidth="16" strokeLinejoin="round"/>
            <path d="M76 176v40l34-32z" fill="rgba(255,255,255,.06)"/>
            <circle cx="40" cy="54" r="8" fill="rgba(255,255,255,.05)"/><circle cx="212" cy="102" r="9" fill="rgba(255,255,255,.05)"/><circle cx="200" cy="134" r="5" fill="rgba(255,255,255,.05)"/>
            <path d="M24 176 C58 144 98 126 126 122 C160 117 178 138 158 152 C138 164 118 146 132 130 C150 110 190 96 228 82" fill="none" stroke="rgba(31,211,245,.55)" strokeWidth="3" strokeLinecap="round"/>
            <path d="M24 176 C58 144 98 126 126 122 C160 117 178 138 158 152 C138 164 118 146 132 130 C150 110 190 96 228 82" fill="none" stroke="rgba(31,211,245,.12)" strokeWidth="14" strokeLinecap="round"/>
          </svg>
        </div>

        {/* มือถือ: หัวข้อย่อ (แสดงแทน hero) */}
        <div className="fit-login-mhero" style={{ display: 'none' }}>
          <div style={{ fontSize: 10.5, letterSpacing: '.24em', color: LG.ink3, fontWeight: 600 }}>FACE RECOGNITION • TIME ATTENDANCE</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 34, lineHeight: 1.05, marginTop: 8 }}>ทุกเวลา <span style={{ color: LG.cyan }}>มีความหมาย</span></div>
          <div style={{ fontSize: 13.5, color: LG.ink2, marginTop: 6 }}>จัดการเวลางาน กะ และเงินเดือนในที่เดียว</div>
        </div>

        {/* ขวา: การ์ดล็อกอิน */}
        <div className="fit-login-form" style={{ display: 'grid', placeItems: 'center' }}>
          <form onSubmit={submit} style={{ width: 'min(430px, 100%)', background: LG.card, border: `1px solid ${LG.line2}`, borderRadius: 22, padding: '34px 34px 26px', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', gap: 16, boxShadow: '0 30px 80px -30px rgba(0,0,0,.7)' }}>
            <div style={{ textAlign: 'center' }}>
              <img src="/img/logo.svg" alt="Face in Time" style={{ width: 84, height: 81 }}/>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26, marginTop: 6 }}>ยินดีต้อนรับกลับ</div>
              <div style={{ fontSize: 13.5, color: LG.ink2, marginTop: 4 }}>เข้าสู่ระบบเพื่อจัดการทีมของคุณ</div>
            </div>

            <div>
              <div style={label}>ชื่อผู้ใช้</div>
              <div style={field}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={LG.ink3} strokeWidth="1.8" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 3.6-7 8-7s8 3 8 7"/></svg>
                <input style={input} value={user} onChange={(e) => setUser(e.target.value)} placeholder="กรอกชื่อผู้ใช้ หรือรหัสพนักงาน" autoComplete="username" autoFocus/>
              </div>
            </div>
            <div>
              <div style={label}>รหัสผ่าน</div>
              <div style={field}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={LG.ink3} strokeWidth="1.8" strokeLinecap="round"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>
                <input style={input} type={show ? 'text' : 'password'} value={pwd} onChange={(e) => setPwd(e.target.value)} placeholder="กรอกรหัสผ่าน" autoComplete="current-password"/>
                <button type="button" onClick={() => setShow(!show)} aria-label={show ? 'ซ่อนรหัสผ่าน' : 'แสดงรหัสผ่าน'} style={{ background: 'none', border: 0, color: LG.ink3, cursor: 'pointer', padding: 4, display: 'flex' }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>{show && <path d="M4 4l16 16"/>}</svg>
                </button>
              </div>
            </div>

            {err && <div style={{ padding: '10px 14px', borderRadius: 10, background: 'rgba(255,107,107,.12)', border: '1px solid rgba(255,107,107,.35)', color: '#FFB3B3', fontSize: 13, fontWeight: 600 }}>{err}</div>}

            <button type="submit" disabled={busy} style={{ width: '100%', padding: '14px 18px', borderRadius: 12, border: 0, background: LG.cyan, color: LG.cyanInk, fontFamily: 'inherit', fontSize: 15.5, fontWeight: 800, cursor: 'pointer', opacity: busy ? .7 : 1, boxShadow: '0 10px 30px -10px rgba(31,211,245,.6)' }}>
              {busy ? 'กำลังเข้าสู่ระบบ…' : 'เข้าสู่ระบบ'}
            </button>
            <GoogleLoginButton/>

            <div style={{ borderTop: `1px solid ${LG.line}`, paddingTop: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, fontSize: 12.5, color: LG.ink3 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>
              เชื่อมต่ออย่างปลอดภัย · TLS
            </div>
          </form>
        </div>
      </div>

      <div style={{ textAlign: 'right', padding: '0 36px 16px', fontSize: 11, letterSpacing: '.22em', color: LG.ink3, width: '100%', maxWidth: 1240, margin: '0 auto', boxSizing: 'border-box' }}>FACEINTIME © 2026</div>
    </div>
  );
}

window.LoginPage = LoginPage;
