// SYK Login Page — glassmorphism style matching app theme

function LoginPage({ onLoginSuccess }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [remember, setRemember] = useState(true);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password) {
      setError('กรุณากรอก email และ password');
      return;
    }
    setError(null);
    setLoading(true);
    try {
      const user = await window.api.login(email.trim(), password);
      onLoginSuccess(user);
    } catch (err) {
      if (err.status === 401) setError('Email หรือ Password ไม่ถูกต้อง');
      else if (err.status === 403) setError('บัญชีถูกระงับ — กรุณาติดต่อผู้ดูแล');
      else if (err.status === 423) setError('บัญชีถูกล็อคชั่วคราว (login ผิดเกิน 5 ครั้ง) — ลองใหม่ใน 15 นาที');
      else if (err.status === 0) setError('เชื่อมต่อ Server ไม่ได้ — ตรวจสอบอินเทอร์เน็ต');
      else setError(err.message || 'เกิดข้อผิดพลาด');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: 24,
      position: 'relative',
      zIndex: 10,
    }}>
      {/* Glass card */}
      <div className="card anim-fadeup" style={{
        width: '100%',
        maxWidth: 420,
        padding: 36,
        background: 'var(--glass-2)',
        backdropFilter: 'blur(28px) saturate(160%)',
        WebkitBackdropFilter: 'blur(28px) saturate(160%)',
        border: '1px solid var(--line-strong)',
        boxShadow: '0 30px 80px -20px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.05) inset',
      }}>
        {/* Logo + title */}
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{
            width: 64, height: 64, borderRadius: 16,
            margin: '0 auto 16px',
            background: '#1a2670',
            boxShadow: '0 8px 24px -6px rgba(40,72,255,0.5)',
            overflow: 'hidden',
          }}>
            <img src="assets/syk-logo.svg"
              onError={(e) => { e.target.onerror = null; e.target.src = 'assets/syk-logo.png'; }}
              style={{ width: '100%', height: '100%', objectFit: 'cover' }} alt="SYK" />
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, fontFamily: 'var(--font-display)', letterSpacing: '-0.01em' }}>
            SYK Document System
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 4 }}>
            Construction Management Platform
          </div>
        </div>

        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Email */}
          <div>
            <label style={{ fontSize: 11.5, color: 'var(--ink-soft)', display: 'block', marginBottom: 6 }}>
              Email
            </label>
            <input
              type="email"
              autoComplete="email"
              autoFocus
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="user@syk-construction.com"
              className="field"
              disabled={loading}
              style={{ height: 42, fontSize: 14 }}
            />
          </div>

          {/* Password */}
          <div>
            <label style={{ fontSize: 11.5, color: 'var(--ink-soft)', display: 'block', marginBottom: 6 }}>
              Password
            </label>
            <div style={{ position: 'relative' }}>
              <input
                type={showPassword ? 'text' : 'password'}
                autoComplete="current-password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                className="field"
                disabled={loading}
                style={{ height: 42, fontSize: 14, paddingRight: 44 }}
              />
              <button
                type="button"
                onClick={() => setShowPassword(s => !s)}
                tabIndex={-1}
                style={{
                  position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
                  background: 'transparent', border: 0, cursor: 'pointer',
                  color: 'var(--ink-mute)', padding: 8,
                }}>
                {showPassword ? '🙈' : '👁️'}
              </button>
            </div>
          </div>

          {/* Error message */}
          {error && (
            <div style={{
              padding: '10px 12px',
              background: 'rgba(255,107,138,0.12)',
              border: '1px solid rgba(255,107,138,0.3)',
              borderRadius: 8,
              color: 'var(--rose)',
              fontSize: 12.5,
              display: 'flex',
              alignItems: 'center',
              gap: 8,
            }}>
              <span>⚠️</span>
              <span>{error}</span>
            </div>
          )}

          {/* Remember + forgot */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', color: 'var(--ink-soft)' }}>
              <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
              จดจำการเข้าสู่ระบบ
            </label>
            <a href="#" onClick={(e) => { e.preventDefault(); alert('กรุณาติดต่อผู้ดูแลระบบเพื่อ reset password'); }}
              style={{ color: 'var(--syk-blue-soft)', textDecoration: 'none' }}>
              ลืมรหัสผ่าน?
            </a>
          </div>

          {/* Submit */}
          <button
            type="submit"
            disabled={loading}
            className="btn btn-primary"
            style={{
              height: 44,
              fontSize: 14,
              fontWeight: 600,
              justifyContent: 'center',
              marginTop: 8,
              opacity: loading ? 0.7 : 1,
            }}>
            {loading ? (
              <>
                <span style={{ display: 'inline-block', animation: 'spin 1s linear infinite' }}>⏳</span>
                <span>กำลังเข้าสู่ระบบ...</span>
              </>
            ) : (
              <>
                <span>เข้าสู่ระบบ</span>
                <span>→</span>
              </>
            )}
          </button>
        </form>

        {/* Footer */}
        <div style={{ marginTop: 24, paddingTop: 16, borderTop: '1px solid var(--line)', textAlign: 'center' }}>
          <div style={{ fontSize: 10.5, color: 'var(--ink-mute)', lineHeight: 1.6 }}>
            🔒 ข้อมูลเข้ารหัสด้วย JWT + HTTPS<br />
            v1.0 · {window.SYK_MODE === 'web' ? '☁️ Cloudflare' : '💻 Desktop'} mode<br />
            <span className="mono" style={{ fontSize: 9 }}>{window.API_BASE}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;
