/* Login screen — username + password ผ่าน /api/auth/login */

const { useState: useStateLogin } = React;

const ROLE_LABELS = {
  admin:  'ผู้ดูแลระบบ',
  staff:  'ผู้จ่ายหมึก',
  viewer: 'บัญชี / ดูอย่างเดียว',
};

function canEdit(role)       { return role === 'admin' || role === 'staff'; }
function canManageKeys(role) { return role === 'admin'; }
function canExport()         { return true; }

function LoginScreen({ onLogin }) {
  const [username, setUsername] = useStateLogin('');
  const [password, setPassword] = useStateLogin('');
  const [error, setError]       = useStateLogin('');
  const [loading, setLoading]   = useStateLogin(false);
  const [showPw, setShowPw]     = useStateLogin(false);

  async function submit() {
    if (!username.trim() || !password) return;
    setLoading(true);
    setError('');
    try {
      const user = await apiPost('/api/auth/login', { username: username.trim(), password });
      onLogin(user);
    } catch (e) {
      setError(e.status === 401 ? 'username หรือ password ไม่ถูกต้อง' : (e.message || 'เกิดข้อผิดพลาด'));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="login-bg">
      <div className="login-card">
        <div className="login-brand">
          <div className="brand-logo" style={{width: 48, height: 48, borderRadius: 12}}>
            <svg viewBox="0 0 32 32" width="48" height="48" fill="none">
              <rect x="0" y="0" width="32" height="32" rx="9" fill="url(#ii-grad-login)"/>
              <defs>
                <linearGradient id="ii-grad-login" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
                  <stop offset="0" stopColor="#3d8fd1"/>
                  <stop offset="1" stopColor="#1a78c2"/>
                </linearGradient>
              </defs>
              <path d="M16 6.5 C 12 12, 9.5 15.5, 9.5 19 a 6.5 6.5 0 0 0 13 0 C 22.5 15.5, 20 12, 16 6.5 Z"
                    fill="#ffffff" opacity="0.96"/>
              <path d="M13.2 17.5 c 0.2 -2 1.4 -3.6 2.6 -4.5"
                    stroke="#1a78c2" strokeWidth="1.1" strokeLinecap="round" opacity="0.5" fill="none"/>
              <rect x="11" y="20" width="10" height="2" rx="1" fill="#1a78c2" opacity="0.85"/>
            </svg>
          </div>
          <div>
            <div className="login-name">Ink Inventory</div>
            <div className="login-sub">ระบบเช็คหมึก</div>
          </div>
        </div>

        <h2 className="login-title">เข้าสู่ระบบ</h2>
        <div className="login-hint">กรุณาใส่ Username และ Password ของคุณ</div>

        <div className="login-field">
          <label>Username</label>
          <input
            type="text"
            value={username}
            onChange={e => setUsername(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && submit()}
            placeholder="กรอก username"
            autoFocus
            autoComplete="username"
          />
        </div>

        <div className="login-field" style={error ? {animation: 'shake 0.4s'} : {}}>
          <label>Password</label>
          <div className="login-input-wrap">
            <input
              type={showPw ? 'text' : 'password'}
              value={password}
              onChange={e => setPassword(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && submit()}
              placeholder="กรอก password"
              autoComplete="current-password"
            />
            <button className="login-eye" type="button" onClick={() => setShowPw(!showPw)}>
              {showPw ? '🙈' : '👁'}
            </button>
          </div>
          {error && <div className="login-error">{error}</div>}
        </div>

        <button className="btn btn-primary login-btn" onClick={submit}
                disabled={!username.trim() || !password || loading}>
          {loading ? 'กำลังเข้าสู่ระบบ...' : 'เข้าสู่ระบบ →'}
        </button>

        <div className="login-foot">
          ติดต่อแอดมิน หากลืม password หรือต้องการสิทธิ์เข้าใช้
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen, ROLE_LABELS, canEdit, canManageKeys, canExport });
