"use client"; import { useEffect, useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import Link from "next/link"; interface Operator { id: string; name: string; } export default function OperatorLoginClient() { const router = useRouter(); const searchParams = useSearchParams(); // A scanned QR card lands unauthenticated operators on /login/operator?next=/op/scan/. // We echo that back to the login API so the redirect after auth returns them to the scan page // instead of dumping them on the generic /op home. const nextPath = searchParams.get("next") ?? undefined; const [operators, setOperators] = useState(null); const [selected, setSelected] = useState(null); const [pin, setPin] = useState(""); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); useEffect(() => { fetch("/api/operators") .then((r) => r.json()) .then((d) => setOperators(d.operators ?? [])) .catch(() => setOperators([])); }, []); function pressKey(k: string) { setError(null); if (k === "back") { setPin((p) => p.slice(0, -1)); return; } if (k === "clear") { setPin(""); return; } setPin((p) => (p.length >= 4 ? p : p + k)); } async function submit() { if (!selected || pin.length !== 4) return; setBusy(true); setError(null); try { const res = await fetch("/api/auth/operator/login", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ operatorId: selected.id, pin, next: nextPath }), }); const data = await res.json().catch(() => ({})); if (!res.ok) { setError(data.error ?? "Sign-in failed"); setPin(""); return; } router.push(data.redirect ?? "/op"); router.refresh(); } catch { setError("Network error"); } finally { setBusy(false); } } useEffect(() => { if (pin.length === 4 && !busy) { void submit(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [pin]); if (operators === null) { return (

Loading…

); } if (!selected) { return (

Who are you?

Tap your name to sign in.

{operators.length === 0 ? (

No operators exist yet.

Ask an admin to create your account.

) : (
{operators.map((op) => ( ))}
)}
← Back
); } const keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "clear", "0", "back"]; return (

Hi, {selected.name}

Enter your 4-digit PIN

{[0, 1, 2, 3].map((i) => (
i ? "bg-slate-900" : "bg-slate-200"}`} /> ))}
{error && (

{error}

)}
{keys.map((k) => { const label = k === "back" ? "⌫" : k === "clear" ? "C" : k; return ( ); })}
); }