"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import Link from "next/link"; import { useAuth } from "@/hooks/useAuth"; import { apiFetch, ApiError } from "@/lib/api"; import { errorMessage } from "@/lib/utils"; import { useVisiblePolling } from "@/hooks/useVisiblePolling"; import { useDismissingState } from "@/hooks/useDismissingState"; import { Baby, CloudOff, LogIn, LogOut, QrCode, RefreshCw, Search, UserPlus, Users } from "lucide-react"; import { BackLink } from "@/components/shared/BackLink"; import { QRScanner } from "@/components/qr/QRScanner"; import { KidsEventPicker } from "@/components/kids/KidsEventPicker"; import { RoomBoard } from "@/components/kids/RoomBoard"; import { StickerPanel } from "@/components/kids/StickerPanel"; import { ChildForm, type ChildInput } from "@/components/kids/ChildForm"; import { FAMILY_QR_PREFIX, QR_PREFIX, deviceId, loadOffline, offlineCheckIn, saveOffline, stickerAlert, suggestRoom, type CheckInResult, type KidsBoard, type KidsFamily, type OfflineState, } from "@/lib/kids"; type Tab = "in" | "out" | "rooms"; type Msg = { type: "ok" | "err"; text: string } | null; type CodeLookup = { code: string | null; found: boolean; family?: { name: string; parents: { userId: string; name: string; phone: string | null }[]; adults: { id: string; name: string; relationship: string | null }[] } | null; children: { id: string; name: string; room: { id: string; name: string } | null; checkedOutAt: string | null; collectedBy: string | null }[]; }; const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"; const tabCls = (on: boolean) => `px-4 py-2 rounded-lg text-sm font-medium inline-flex items-center gap-1.5 ${on ? "bg-brand-600 text-white" : "bg-white border text-gray-700"}`; /** The kids check-in desk: find the family, check children in (pickup code + sticker panel), check them out by code. */ export default function KidsDeskPage() { const { token, user } = useAuth(); const isSupervisor = user?.role === "admin" || user?.role === "supervisor"; const [eventId, setEventId] = useState(""); const [sessionId, setSessionId] = useState(""); const [tab, setTab] = useState("in"); const [board, setBoard] = useState(null); const [boardError, setBoardError] = useState(null); const [msg, setMsg] = useDismissingState(null, 9000); const [busy, setBusy] = useState(false); // Offline const [offline, setOffline] = useState(null); const [working, setWorking] = useState<"online" | "offline">("online"); // Check in const [q, setQ] = useState(""); const [results, setResults] = useState(null); const [family, setFamily] = useState(null); const [picked, setPicked] = useState>({}); // childId → roomId const [sendTo, setSendTo] = useState(""); const [result, setResult] = useState(null); const [scanning, setScanning] = useState(false); const [newFamily, setNewFamily] = useState<{ name: string; parentName: string; phone: string; email: string } | null>(null); const [addingChild, setAddingChild] = useState(false); // Check out const [code, setCode] = useState(""); const [lookup, setLookup] = useState(null); const [outPicked, setOutPicked] = useState>({}); const [collectedBy, setCollectedBy] = useState(""); const [wrongCode, setWrongCode] = useState(null); const qs = sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : ""; const loadBoard = useCallback(async (log = false) => { if (!token || !eventId || working === "offline") return; try { const data = await apiFetch(`/api/kids/events/${eventId}/board${qs}${log ? `${qs ? "&" : "?"}log=1` : ""}`, { authToken: token }); setBoard(data); setBoardError(null); } catch (e) { setBoard(null); setBoardError(errorMessage(e) || "Could not load the desk"); } }, [token, eventId, qs, working]); useEffect(() => { setBoard(null); setFamily(null); setResult(null); setOffline(eventId ? loadOffline(eventId) : null); loadBoard(true); }, [eventId, sessionId]); // eslint-disable-line react-hooks/exhaustive-deps useVisiblePolling(() => { loadBoard(); }, 10000, !!token && !!eventId && working === "online"); // Go offline by itself when the browser loses its connection (if an offline list is ready). useEffect(() => { const down = () => { if (loadOffline(eventId)) setWorking("offline"); }; window.addEventListener("offline", down); return () => window.removeEventListener("offline", down); }, [eventId]); const rooms = useMemo(() => (working === "offline" ? offline?.snapshot.rooms : board?.rooms) || [], [working, offline, board]); const inNow = useMemo(() => { const m = new Map(); // childId → room name const list = working === "offline" ? offline?.snapshot.checkIns : board?.checkIns; for (const c of list || []) if (!c.checkedOutAt && c.childId) m.set(c.childId, rooms.find(r => r.id === c.roomId)?.name || ""); if (working === "offline") for (const c of offline?.checkIns || []) if (!offline!.checkOuts.some(o => o.clientId === c.clientId)) m.set(c.childId, c.roomName); return m; }, [working, offline, board, rooms]); const fail = (e: unknown, fallback: string) => { // A dropped connection with an offline list ready: switch over instead of failing. if (!(e instanceof ApiError) && loadOffline(eventId)) { setWorking("offline"); setOffline(loadOffline(eventId)); setMsg({ type: "err", text: "No connection — switched to the offline list. Try that again." }); return; } setMsg({ type: "err", text: errorMessage(e) || fallback }); }; // ─── Families ─────────────────────────────────────────────────────────────── const chooseFamily = (f: KidsFamily) => { setFamily(f); setResults(null); setResult(null); setSendTo(""); setAddingChild(false); const extra: Record = {}; const next: Record = {}; for (const c of f.children) { if (inNow.has(c.id)) continue; const room = suggestRoom(rooms, c.age, extra); if (room) { next[c.id] = room.id; extra[room.id] = (extra[room.id] || 0) + 1; } } setPicked(next); }; const search = async (e?: React.FormEvent) => { e?.preventDefault(); const term = q.trim(); if (term.length < 2) return; if (working === "offline") { const t = term.toLowerCase(), digits = term.replace(/\D/g, ""); setResults((offline?.snapshot.families || []).filter(f => f.name.toLowerCase().includes(t) || f.children.some(c => c.name.toLowerCase().includes(t)) || f.parents.some(p => p.name.toLowerCase().includes(t) || (digits.length >= 6 && (p.phone || "").replace(/\D/g, "").slice(-9).includes(digits.slice(-9))))).slice(0, 20)); return; } try { setResults(await apiFetch(`/api/kids/events/${eventId}/families?q=${encodeURIComponent(term)}`, { authToken: token })); } catch (err) { fail(err, "Search failed"); } }; const onScan = async (text: string) => { setScanning(false); const t = text.trim(); if (t.toUpperCase().startsWith(QR_PREFIX)) { setTab("out"); setCode(t.slice(QR_PREFIX.length)); lookUpCode(t.slice(QR_PREFIX.length)); return; } if (!t.toUpperCase().startsWith(FAMILY_QR_PREFIX)) { setMsg({ type: "err", text: "That isn't a family or pickup QR code." }); return; } if (working === "offline") { setMsg({ type: "err", text: "Family QR codes need a connection — search by name or phone instead." }); return; } try { chooseFamily(await apiFetch(`/api/kids/events/${eventId}/families/qr/${encodeURIComponent(t.slice(FAMILY_QR_PREFIX.length))}`, { authToken: token })); } catch (err) { fail(err, "Family not found"); } }; const createFamily = async (child: ChildInput) => { if (!newFamily) return; setBusy(true); try { const f = await apiFetch(`/api/kids/events/${eventId}/families`, { method: "POST", authToken: token, body: { name: newFamily.name, parent: { name: newFamily.parentName, phone: newFamily.phone, email: newFamily.email }, children: [child] }, }); setNewFamily(null); chooseFamily(f); setMsg({ type: "ok", text: `${f.name} added.` }); } catch (err) { fail(err, "Could not add the family"); } finally { setBusy(false); } }; const addChild = async (child: ChildInput) => { if (!family) return; setBusy(true); try { await apiFetch(`/api/kids/events/${eventId}/families/${family.id}/children`, { method: "POST", authToken: token, body: child }); chooseFamily(await apiFetch(`/api/kids/events/${eventId}/families/${family.id}`, { authToken: token })); setMsg({ type: "ok", text: `${child.firstName} added.` }); } catch (err) { fail(err, "Could not add the child"); } finally { setBusy(false); } }; // ─── Check in ─────────────────────────────────────────────────────────────── const doCheckIn = async () => { if (!family) return; const children = Object.entries(picked).filter(([, roomId]) => roomId).map(([childId, roomId]) => ({ childId, roomId })); if (!children.length) { setMsg({ type: "err", text: "Tick the children to check in." }); return; } if (working === "offline" && offline) { try { const picks = children.map(p => ({ child: family.children.find(c => c.id === p.childId)!, room: rooms.find(r => r.id === p.roomId)! })); const out = offlineCheckIn(offline, family, picks); setOffline(out.state); saveOffline(eventId, out.state); setResult({ code: out.code, qr: QR_PREFIX + out.code, occasion: offline.snapshot.occasion, family: { id: family.id, name: family.name }, checkIns: picks.map(p => ({ id: p.child.id, name: p.child.name, firstName: p.child.firstName, room: { id: p.room.id, name: p.room.name }, already: false, sticker: stickerAlert(p.child.allergies, p.child.hasMedical) })), }); setMsg({ type: "ok", text: "Checked in on this device — tell the parent the code (no message is sent while offline)." }); } catch (err) { setMsg({ type: "err", text: errorMessage(err) || "Could not check in offline" }); } return; } setBusy(true); try { const r = await apiFetch(`/api/kids/events/${eventId}/check-in`, { method: "POST", authToken: token, body: { familyId: family.id, sessionId: sessionId || undefined, children, sendToAdultId: sendTo || undefined }, }); setResult(r); loadBoard(); } catch (err) { fail(err, "Check-in failed"); } finally { setBusy(false); } }; // ─── Check out ────────────────────────────────────────────────────────────── const offlineLookup = (raw: string): CodeLookup => { const c = raw.trim().toUpperCase().replace(/[\s-]/g, ""); const mine = (offline?.checkIns || []).filter(x => x.code === c); const fam = offline?.snapshot.families.find(f => f.id === mine[0]?.familyId); return { code: c, found: mine.length > 0, family: fam ? { name: fam.name, parents: fam.parents, adults: fam.adults } : null, children: mine.map(x => { const o = offline!.checkOuts.find(k => k.clientId === x.clientId); return { id: x.clientId, name: x.name, room: { id: x.roomId, name: x.roomName }, checkedOutAt: o?.at || null, collectedBy: o?.collectedBy || null }; }), }; }; const lookUpCode = async (raw = code) => { setWrongCode(null); setLookup(null); if (!raw.trim()) return; let l: CodeLookup; if (working === "offline") { l = offlineLookup(raw); if (!l.found) { setWrongCode(offline?.snapshot.checkIns.some(c => c.code === raw.trim().toUpperCase()) ? "This code was given out before going offline. Check these children out on a connected device, or use \"Without code\" there." : "That code doesn't match any child checked in on this device."); return; } } else { try { l = await apiFetch(`/api/kids/events/${eventId}/code/${encodeURIComponent(raw.trim())}${qs}`, { authToken: token }); } catch (err) { fail(err, "Lookup failed"); return; } if (!l.found) { // Record the wrong code (alerts the rooms) through the check-out call. try { await apiFetch(`/api/kids/events/${eventId}/check-out`, { method: "POST", authToken: token, body: { code: raw, collectedBy: "", sessionId: sessionId || undefined } }); } catch (err) { setWrongCode(errorMessage(err) || "Wrong code"); } loadBoard(); return; } } setLookup(l); setOutPicked(Object.fromEntries(l.children.filter(c => !c.checkedOutAt).map(c => [c.id, true]))); setCollectedBy(l.family?.parents[0]?.name || ""); }; const doCheckOut = async () => { if (!lookup) return; const ids = Object.entries(outPicked).filter(([, on]) => on).map(([id]) => id); if (!ids.length) { setMsg({ type: "err", text: "Tick the children being collected." }); return; } if (!collectedBy.trim()) { setMsg({ type: "err", text: "Enter who is collecting." }); return; } if (working === "offline" && offline) { const at = new Date().toISOString(); const next = { ...offline, checkOuts: [...offline.checkOuts, ...ids.map(clientId => ({ clientId, collectedBy, at }))] }; setOffline(next); saveOffline(eventId, next); setMsg({ type: "ok", text: `Checked out on this device: ${lookup.children.filter(c => ids.includes(c.id)).map(c => c.name).join(", ")}.` }); setLookup(null); setCode(""); return; } setBusy(true); try { const r = await apiFetch<{ checkedOut: { name: string }[] }>(`/api/kids/events/${eventId}/check-out`, { method: "POST", authToken: token, body: { code: lookup.code, checkInIds: ids, collectedBy, sessionId: sessionId || undefined }, }); setMsg({ type: "ok", text: `Collected: ${r.checkedOut.map(c => c.name).join(", ")}.` }); setLookup(null); setCode(""); loadBoard(); } catch (err) { fail(err, "Check-out failed"); } finally { setBusy(false); } }; // ─── Offline list ─────────────────────────────────────────────────────────── const getReady = async () => { setBusy(true); try { const snapshot = await apiFetch(`/api/kids/events/${eventId}/offline?deviceId=${encodeURIComponent(deviceId())}${sessionId ? `&sessionId=${encodeURIComponent(sessionId)}` : ""}`, { authToken: token }); const prev = loadOffline(eventId); const sameOccasion = prev?.snapshot.occasion === snapshot.occasion; const state: OfflineState = { snapshot, familyCodes: sameOccasion ? prev!.familyCodes : {}, checkIns: sameOccasion ? prev!.checkIns : [], checkOuts: sameOccasion ? prev!.checkOuts : [], }; saveOffline(eventId, state); setOffline(state); setMsg({ type: "ok", text: `Offline list ready: ${snapshot.families.length} families, ${snapshot.codes.length} pickup codes for this device.` }); } catch (err) { fail(err, "Could not download the offline list"); } finally { setBusy(false); } }; const sync = async () => { if (!offline) return; setBusy(true); try { const r = await apiFetch<{ checkedIn: number; checkedOut: number; conflicts: { clientId: string | null; message: string }[] }>(`/api/kids/events/${eventId}/sync`, { method: "POST", authToken: token, body: { deviceId: deviceId(), occasion: offline.snapshot.occasion, checkIns: offline.checkIns, checkOuts: offline.checkOuts }, }); const next: OfflineState = { ...offline, checkIns: [], checkOuts: [] }; saveOffline(eventId, next); setOffline(next); setWorking("online"); setMsg({ type: r.conflicts.length ? "err" : "ok", text: `Synced: ${r.checkedIn} checked in, ${r.checkedOut} checked out.${r.conflicts.length ? ` Check: ${r.conflicts.map(c => c.message).join(" ")}` : ""}`, }); loadBoard(); } catch (err) { setMsg({ type: "err", text: errorMessage(err) || "Sync failed — still offline? Your check-ins are kept on this device." }); } finally { setBusy(false); } }; const queued = (offline?.checkIns.length || 0) + (offline?.checkOuts.length || 0); const ready = working === "offline" ? !!offline : !!board; return (

Kids check-in

{board?.sessionLabel ? `${board.sessionLabel} · ` : ""}Check children in and out with pickup codes

Room screen
{ setEventId(id); setSessionId(sid); }} /> {eventId && (
{working === "offline" ? ( <> Working offline {queued} change{queued === 1 ? "" : "s"} waiting to sync · {Math.max(0, (offline?.snapshot.codes.length || 0) - Object.keys(offline?.familyCodes || {}).length)} codes left ) : ( <> {offline ? `Offline list from ${new Date(offline.snapshot.downloadedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}` : "Wi-Fi unreliable? Download the list first."} {queued > 0 && } {offline && } )}
)} {boardError && working === "online" &&
{boardError}
} {msg &&
{msg.text}
} {ready && ( <>
{working === "online" && }
{(tab === "in" || tab === "out") && (
{scanning &&
}
)} {tab === "in" && ( result ? (
({ id: c.id, firstName: c.firstName, room: c.room?.name || null, sticker: c.sticker, already: c.already }))} />
) : (
setQ(e.target.value)} aria-label="Find a family" />
{results && (
    {results.map(f => (
  • ))} {!results.length &&
  • No family found.
  • }
)} {working === "online" && !newFamily && ( )} {newFamily && (
New family
setNewFamily({ ...newFamily, parentName: e.target.value })} />
setNewFamily({ ...newFamily, phone: e.target.value })} /> setNewFamily({ ...newFamily, email: e.target.value })} />
setNewFamily({ ...newFamily, name: e.target.value })} />
First child:
setNewFamily(null)} saveLabel="Add family" />
)}
{family && (

{family.name}

{family.parents.map(p => `${p.name}${p.phone ? ` · ${p.phone}` : ""}`).join(" — ")}
    {family.children.map(c => { const inRoom = inNow.get(c.id); return (
  • {inRoom !== undefined ? In — {inRoom} : picked[c.id] ? ( ) : null}
  • ); })}
{working === "online" && (addingChild ? (
setAddingChild(false)} saveLabel="Add child" />
) : ( ))} {working === "online" && family.adults.some(a => a.phone) && ( )}
)}
) )} {tab === "out" && (
{ e.preventDefault(); lookUpCode(); }} className="flex gap-2"> setCode(e.target.value)} maxLength={10} aria-label="Pickup code" />
{wrongCode &&
{wrongCode}
} {lookup && (
{lookup.family && (
{lookup.family.name}
Parents: {lookup.family.parents.map(p => p.name).join(", ") || "—"}
{lookup.family.adults.length > 0 &&
May also collect: {lookup.family.adults.map(a => `${a.name}${a.relationship ? ` (${a.relationship})` : ""}`).join(", ")}
}
)}
    {lookup.children.map(c => { const custody = board?.checkIns.find(b => b.id === c.id)?.custodyNotes; return (
  • {custody &&
    Custody: {custody}
    }
  • ); })}
)}
)} {tab === "rooms" && board && working === "online" && ( loadBoard()} onMessage={setMsg} /> )} )}
); }