// PIN login screen. Sits in front of App() when the session cookie is missing
// or expired. Single input: PIN. Role (owner / staff / maid) is derived
// server-side from which hash the PIN matches; the client identifier
// (front / maid) is derived from role and never picked here.

const { useState } = React;

function LoginScreen({ onSuccess }) {
  const [pin, setPin] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!pin) return;
    setSubmitting(true);
    setError('');
    try {
      const session = await window.API.login(pin);
      onSuccess(session);
    } catch (err) {
      if (err.code === 'invalid_pin') {
        setError('PIN ไม่ถูกต้อง');
      } else if (err.code === 'network_error') {
        setError('ต่อ server ไม่ได้ — ตรวจว่า Worker เปิดอยู่');
      } else {
        setError(err.message || 'Login ล้มเหลว');
      }
      setPin('');
    } finally {
      setSubmitting(false);
    }
  };

  const onKey = (e) => {
    if (e.key === 'Enter') submit();
  };

  return (
    <div className="login-screen">
      <div className="login-card">
        <div className="login-title">Daily Report</div>
        <div className="login-sub">Hataara Hotel</div>

        <form onSubmit={submit} className="login-form">
          <label className="login-field">
            <span>PIN</span>
            <input
              type="password"
              inputMode="numeric"
              autoComplete="off"
              maxLength={8}
              value={pin}
              onChange={(e) => setPin(e.target.value.replace(/\D/g, ''))}
              onKeyDown={onKey}
              autoFocus
              placeholder="••••••"
            />
          </label>

          {error && <div className="login-error">{error}</div>}

          <button
            type="submit"
            className="login-submit"
            disabled={!pin || submitting}>
            {submitting ? 'กำลังเข้า…' : 'เข้าสู่ระบบ'}
          </button>
        </form>
      </div>
    </div>
  );
}

// Expose so app.jsx can render it without ES modules
window.LoginScreen = LoginScreen;
