// Nordbank — admin backoffice login.
//
// Standalone page that posts a password to /api/admin-login. The Cloudflare
// Pages function validates against an env-held secret and sets an httpOnly
// session cookie on success. The browser never sees the secret.
//
// Renders without the public Header/Footer to make it visually distinct from
// the customer-facing site.

function AdminLogin() {
  const [password, setPassword] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');

  async function submit(e) {
    e.preventDefault();
    if (busy || !password) return;
    setError('');
    setBusy(true);
    try {
      const res = await fetch('/api/admin-login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ password }),
      });
      if (res.ok) {
        navigate('/admin/applications');
        return;
      }
      if (res.status === 401) {
        setError('Incorrect password.');
      } else {
        let msg = 'Login failed. Please try again.';
        try {
          const body = await res.json();
          if (body && typeof body.error === 'string' && body.error) msg = body.error;
        } catch (e) { /* ignore */ }
        setError(msg);
      }
    } catch (err) {
      console.error('[admin-login] network error', err);
      setError('Network error. Please try again.');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="min-h-screen bg-surface flex flex-col">
      <header className="border-b hairline bg-white">
        <div className="max-w-5xl mx-auto px-4 md:px-6 h-14 flex items-center gap-3">
          <NordbankLogo />
          <span className="hidden sm:inline text-xs font-semibold tracking-[0.18em] uppercase text-navy-300">
            · Admin
          </span>
        </div>
      </header>

      <main className="flex-1 flex items-center justify-center px-4 md:px-6 py-12">
        <div className="w-full max-w-md nb-fade">
          <Card className="p-8 md:p-10">
            <h1 className="text-2xl font-semibold text-navy-900">Admin sign in</h1>
            <p className="mt-2 text-sm text-navy-500">
              Backoffice access for Nordbank operations. Authenticated and audited.
            </p>
            <form className="mt-6 space-y-4" onSubmit={submit}>
              <Field label="Account" htmlFor="admin-account">
                <TextInput
                  id="admin-account"
                  value="Admin"
                  onChange={() => {}}
                  disabled
                  readOnly
                />
              </Field>
              <Field label="Password" required htmlFor="admin-password">
                <TextInput
                  id="admin-password"
                  type="password"
                  value={password}
                  onChange={setPassword}
                  placeholder="••••••••"
                  autoComplete="current-password"
                />
              </Field>
              {error && <p role="alert" className="text-sm text-danger">{error}</p>}
              <button
                type="submit"
                disabled={busy || !password}
                className="w-full bg-navy-900 hover:bg-navy-700 text-white text-sm font-semibold py-3 rounded-full transition-colors disabled:opacity-60 flex items-center justify-center gap-2"
              >
                {busy && <Spinner />}
                {busy ? 'Signing in…' : 'Sign in'}
              </button>
            </form>
          </Card>
          <p className="mt-4 text-center text-[11px] text-navy-300">
            Nordbank internal · Unauthorised access prohibited.
          </p>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { AdminLogin });
