"use client"; import React, { useCallback, useEffect, useState } from "react"; import Link from "next/link"; import { MapPin, Plus, ArrowUp, ArrowDown, Archive, ArchiveRestore, Trash2, Pencil } from "lucide-react"; import { apiFetch } from "@/lib/api"; import { useAuth } from "@/hooks/useAuth"; import { useDismissingState } from "@/hooks/useDismissingState"; import { reloadCampuses, type Campus } from "@/hooks/useCampuses"; import { errorMessage } from "@/lib/utils"; type Person = { id: string; name: string; email: string }; type AdminCampus = Campus & { archivedAt: string | null; notifyRecipients: Person[]; _count: { events: number; homeOf: number }; }; type Draft = { name: string; slug: string; address: string; defaultLocation: string; contactName: string; contactEmail: string; contactPhone: string; colour: string; logoUrl: string; notifyRecipients: Person[]; }; const EMPTY: Draft = { name: "", slug: "", address: "", defaultLocation: "", contactName: "", contactEmail: "", contactPhone: "", colour: "", logoUrl: "", notifyRecipients: [] }; const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"; const toDraft = (c: AdminCampus): Draft => ({ name: c.name, slug: c.slug, address: c.address || "", defaultLocation: c.defaultLocation || "", contactName: c.contactName || "", contactEmail: c.contactEmail || "", contactPhone: c.contactPhone || "", colour: c.colour || "", logoUrl: c.logoUrl || "", notifyRecipients: c.notifyRecipients || [], }); /** Staff who get the daily summary for this campus's events. */ function RecipientsField({ value, onChange }: { value: Person[]; onChange: (v: Person[]) => void }) { const { token } = useAuth(); const [search, setSearch] = useState(""); const [results, setResults] = useState([]); useEffect(() => { if (!search.trim()) { setResults([]); return; } let cancelled = false; const t = setTimeout(async () => { try { const res = await apiFetch<{ data?: (Person & { role?: string })[] }>(`/api/users?search=${encodeURIComponent(search.trim())}&limit=10`, { authToken: token }); if (!cancelled) setResults((res?.data || []).filter(u => u.role !== "user")); } catch { if (!cancelled) setResults([]); } }, 300); return () => { cancelled = true; clearTimeout(t); }; }, [search, token]); const shown = results.filter(r => !value.some(v => v.id === r.id)); return (
{value.length > 0 && ( )} setSearch(e.target.value)} /> {shown.length > 0 && ( )}
); } function CampusForm({ initial, saving, onSave, onCancel }: { initial: Draft; saving: boolean; onSave: (d: Draft) => void; onCancel: () => void }) { const [d, setD] = useState(initial); const set = (k: keyof Draft) => (e: React.ChangeEvent) => setD(prev => ({ ...prev, [k]: e.target.value })); return (
{ e.preventDefault(); onSave(d); }} className="border rounded-xl p-4 space-y-3 bg-gray-50">

Daily summary for this campus

These staff also get the daily summary of this campus's events, on top of each event's own recipients.

setD(prev => ({ ...prev, notifyRecipients: v }))} />
); } /** Site settings → Campuses: turn campuses on, and add, order, archive and delete them. */ export function CampusesTab({ active }: { active: boolean }) { const { token } = useAuth(); const [enabled, setEnabled] = useState(false); const [campuses, setCampuses] = useState(null); const [editing, setEditing] = useState(null); const [busy, setBusy] = useState(false); const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); const load = useCallback(async () => { if (!token) return; try { const res = await apiFetch<{ enabled: boolean; campuses: AdminCampus[] }>("/api/campuses/admin", { authToken: token }); setEnabled(res.enabled); setCampuses(res.campuses); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Could not load campuses." }); } }, [token, setMsg]); useEffect(() => { if (active) load(); }, [active, load]); const run = async (fn: () => Promise, ok?: string) => { setBusy(true); try { await fn(); reloadCampuses(); await load(); if (ok) setMsg({ type: "ok", text: ok }); return true; } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Something went wrong." }); return false; } finally { setBusy(false); } }; const toggle = (on: boolean) => run(() => apiFetch("/api/campuses/settings", { method: "PUT", authToken: token, body: { enabled: on } }), on ? "Campuses are on." : "Campuses are off — campus fields are hidden, nothing is deleted."); const save = async (d: Draft, id?: string) => { const body = { ...d, notifyRecipients: undefined, notifyRecipientIds: d.notifyRecipients.map(p => p.id) }; const ok = await run(() => id ? apiFetch(`/api/campuses/${id}`, { method: "PUT", authToken: token, body }) : apiFetch("/api/campuses", { method: "POST", authToken: token, body }).then((c) => { const created = c as AdminCampus; // Recipients are set with an update, so a new campus gets them too. return d.notifyRecipients.length ? apiFetch(`/api/campuses/${created.id}`, { method: "PUT", authToken: token, body: { notifyRecipientIds: body.notifyRecipientIds } }) : created; }), id ? "Campus saved." : "Campus added."); if (ok) setEditing(null); }; const move = (list: AdminCampus[], i: number, dir: -1 | 1) => { const ids = list.map(c => c.id); [ids[i], ids[i + dir]] = [ids[i + dir], ids[i]]; return run(() => apiFetch("/api/campuses/order", { method: "PUT", authToken: token, body: { ids } })); }; const setArchived = (c: AdminCampus, archived: boolean) => run(() => apiFetch(`/api/campuses/${c.id}`, { method: "PUT", authToken: token, body: { archived } }), archived ? `${c.name} archived.` : `${c.name} restored.`); const remove = (c: AdminCampus) => { if (!window.confirm(`Delete ${c.name}? This can't be undone.`)) return; run(() => apiFetch(`/api/campuses/${c.id}`, { method: "DELETE", authToken: token }), `${c.name} deleted.`); }; if (!campuses) return msg ?

{msg.text}

:

Loading…

; const activeList = campuses.filter(c => !c.archivedAt); const archivedList = campuses.filter(c => c.archivedAt); return (

Campuses

For a church with more than one campus: each event belongs to a campus or to all campuses, the events page gets a campus filter, and people can choose their home campus. Churches with one campus can leave this off — nobody sees campus fields then.

{enabled && ( <>
{activeList.length === 0 && editing !== "new" &&

No campuses yet. Add your first one below.

} {activeList.map((c, i) => editing === c.id ? ( save(d, c.id)} onCancel={() => setEditing(null)} /> ) : (

{c.name}

/campus/{c.slug} {" · "}{c._count.events} event{c._count.events === 1 ? "" : "s"}{" · "}{c._count.homeOf} {c._count.homeOf === 1 ? "person" : "people"} call it home {c.address && <> · {c.address}}

{c._count.events === 0 && ( )}
))}
{editing === "new" ? ( save(d)} onCancel={() => setEditing(null)} /> ) : ( )} {archivedList.length > 0 && (

Archived

Archived campuses aren't offered for new events or as a home campus. Events that already have one keep it.

{archivedList.map(c => (

{c.name} · {c._count.events} event{c._count.events === 1 ? "" : "s"}

{c._count.events === 0 && ( )}
))}
)} )} {msg &&
{msg.text}
}
); }