"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { apiFetch } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { Gift, Plus, X, Trash2, Pencil, Power, CalendarClock } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import type { EventBundle } from "@/types"; type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] }; type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] }; type ItemDraft = { eventOptionId: string; variantId: string | null; quantity: string }; type Draft = { name: string; description: string; price: string; items: ItemDraft[]; validFrom: string; validUntil: string; isActive: boolean; }; const blankDraft = (options: OptionLite[]): Draft => ({ name: "", description: "", price: "", items: options.slice(0, 2).map(o => ({ eventOptionId: o.id, variantId: null, quantity: "1" })), validFrom: "", validUntil: "", isActive: true, }); // wants local "YYYY-MM-DDTHH:mm". const toLocalInput = (iso: string | null | undefined) => { if (!iso) return ""; const d = new Date(iso); const pad = (n: number) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; }; const draftFromBundle = (b: EventBundle): Draft => ({ name: b.name, description: b.description || "", price: String(b.price), items: b.items.map(i => ({ eventOptionId: i.eventOptionId, variantId: i.variantId || null, quantity: String(i.quantity) })), validFrom: toLocalInput(b.validFrom), validUntil: toLocalInput(b.validUntil), isActive: b.isActive, }); const fmtDate = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : ""); const fmtRand = (n: number) => `R ${(n || 0).toFixed(2)}`; // fieldCls has no width, for fields sized by their row (inputCls is full width). const fieldCls = "border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"; const inputCls = `w-full ${fieldCls}`; const isPast = (ev: EventLite) => new Date(ev.endDate || ev.startDate).getTime() < Date.now(); /** Standard price of one unit of an item (variant price, else the option's). */ function unitPrice(options: OptionLite[], item: { eventOptionId: string; variantId: string | null }) { const o = options.find(x => x.id === item.eventOptionId); if (!o) return 0; const v = item.variantId ? (o.variants || []).find(x => x.id === item.variantId) : null; return Number(v && v.price !== null && v.price !== undefined ? v.price : o.price) || 0; } function bundleStatus(b: EventBundle): { label: string; cls: string } { const now = Date.now(); if (!b.isActive) return { label: "Off", cls: "bg-gray-100 text-gray-600" }; if (b.validUntil && new Date(b.validUntil).getTime() < now) return { label: "Ended", cls: "bg-gray-100 text-gray-600" }; if (b.validFrom && new Date(b.validFrom).getTime() > now) return { label: "Scheduled", cls: "bg-amber-100 text-amber-800" }; return { label: "On sale", cls: "bg-green-100 text-green-800" }; } export default function BundlesPage() { const { user, loading, token } = useAuth(); const router = useRouter(); const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]); useEffect(() => { if (loading) return; if (!user) router.replace("/login"); }, [user, loading, router]); const [allEvents, setAllEvents] = useState([]); const [showPast, setShowPast] = useState(false); const [eventId, setEventId] = useState(""); const [bundles, setBundles] = useState([]); const [fetching, setFetching] = useState(false); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); const [editing, setEditing] = useState<{ id: string | null; draft: Draft } | null>(null); useEffect(() => { if (!token || !canView) return; apiFetch("/api/events/all?includePast=true", { authToken: token }) .then(list => setAllEvents(list || [])) .catch(e => setError(errorMessage(e) || "Failed to load events")); }, [token, canView, setError]); // Upcoming events soonest first; past ones (when shown) after them, most recent first. const events = useMemo(() => { const upcoming = allEvents.filter(e => !isPast(e)).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()); const past = allEvents.filter(isPast).sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()); return showPast ? [...upcoming, ...past] : upcoming; }, [allEvents, showPast]); // Keep the picked event while it's in the list; otherwise start on the next upcoming one. useEffect(() => { if (!events.some(e => e.id === eventId)) setEventId(events[0]?.id || ""); }, [events, eventId]); const event = events.find(e => e.id === eventId) || null; const options = event?.eventOptions || []; const load = useCallback(async () => { if (!token || !eventId) { setBundles([]); return; } setFetching(true); try { setBundles(await apiFetch(`/api/bundles/event/${eventId}`, { authToken: token }) || []); } catch (e) { setError(errorMessage(e) || "Failed to load bundles"); } finally { setFetching(false); } }, [token, eventId, setError]); useEffect(() => { load(); }, [load]); const toggleActive = async (b: EventBundle) => { try { await apiFetch(`/api/bundles/${b.id}`, { method: "PUT", authToken: token!, body: { isActive: !b.isActive } }); setInfo(`${b.name} turned ${b.isActive ? "off" : "on"}.`); load(); } catch (e) { setError(errorMessage(e) || "Failed to update bundle"); } }; const remove = async (b: EventBundle) => { if (!window.confirm(`Delete "${b.name}"?`)) return; try { const res = await apiFetch<{ message: string }>(`/api/bundles/${b.id}`, { method: "DELETE", authToken: token! }); setInfo(res?.message || "Bundle deleted"); load(); } catch (e) { setError(errorMessage(e) || "Failed to delete bundle"); } }; const startNew = () => setEditing({ id: null, draft: blankDraft(options) }); const canAdd = !!event && options.length > 0; return (

Bundle deals

Tickets sold together for one price

{canView && ( )}
{!canView && (
You need supervisor access to manage bundle deals.
)} {error &&
{error}
} {info &&
{info}
} {canView && (
{event && options.length === 0 && (

This event has no tickets yet. Add ticket options to the event first.

)} {event && options.length > 0 && !fetching && bundles.length === 0 && (

No bundle deals for this event yet

e.g. "Family deal: 2 adults + 3 kids for R220". Buyers get it automatically when their tickets match.

)} {bundles.length > 0 && (
{bundles.map(b => ( setEditing({ id: b.id, draft: draftFromBundle(b) })} onToggle={() => toggleActive(b)} onDelete={() => remove(b)} /> ))}
)}

Bundles apply automatically, as many times as someone's tickets allow, and only when cheaper than the tickets at the prices actually charged (early-bird and staff prices included). Coupon codes come off afterwards.

)} {editing && event && ( setEditing(null)} onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }} /> )}
); } function BundleCard({ bundle: b, onEdit, onToggle, onDelete }: { bundle: EventBundle; onEdit: () => void; onToggle: () => void; onDelete: () => void }) { const status = bundleStatus(b); const save = b.standardValue - b.price; const dates = b.validFrom || b.validUntil ? `${b.validFrom ? fmtDate(b.validFrom) : "Now"} – ${b.validUntil ? fmtDate(b.validUntil) : "no end date"}` : null; return (
{b.name}
{b.description &&
{b.description}
}
{status.label}
{b.items.map(i => ( {i.quantity} × {i.eventOption?.name || "Ticket"}{i.variant ? ` (${i.variant.name})` : ""} ))}
{fmtRand(b.price)} {fmtRand(b.standardValue)} 0 ? "text-green-700" : "text-amber-700"}`}> {save > 0 ? `saves ${fmtRand(save)}` : "no saving at the standard price"}
Used {b.uses || 0}× on {b.registrations || 0} registration{b.registrations === 1 ? "" : "s"} · {fmtRand(b.totalDiscount || 0)} given
{dates &&
{dates}
}
); } function BundleModal({ token, event, bundleId, initial, onClose, onSaved }: { token: string; event: EventLite; bundleId: string | null; initial: Draft; onClose: () => void; onSaved: (message: string) => void; }) { const [d, setD] = useState(initial); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const set = (key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value })); const options = event.eventOptions || []; const setItem = (i: number, patch: Partial) => set("items", d.items.map((it, j) => (j === i ? { ...it, ...patch } : it))); const standardValue = d.items.reduce((s, it) => s + unitPrice(options, it) * (Number(it.quantity) || 0), 0); const price = Number(d.price) || 0; const saving_ = standardValue - price; const save = async (e: React.FormEvent) => { e.preventDefault(); setError(null); setSaving(true); try { const body = { name: d.name.trim(), description: d.description.trim() || null, price: Number(d.price), items: d.items.map(it => ({ eventOptionId: it.eventOptionId, variantId: it.variantId, quantity: Number(it.quantity) })), validFrom: d.validFrom ? new Date(d.validFrom).toISOString() : null, validUntil: d.validUntil ? new Date(d.validUntil).toISOString() : null, isActive: d.isActive, }; if (bundleId) { await apiFetch(`/api/bundles/${bundleId}`, { method: "PUT", authToken: token, body }); onSaved(`${body.name} saved.`); } else { await apiFetch(`/api/bundles/event/${event.id}`, { method: "POST", authToken: token, body }); onSaved(`${body.name} created.`); } } catch (err) { setError(errorMessage(err) || "Failed to save"); } finally { setSaving(false); } }; return (
e.stopPropagation()}>

{bundleId ? "Edit bundle" : "New bundle deal"}

{event.title}

set("name", e.target.value)} placeholder="Family deal" required maxLength={80} />

Shown to buyers and on receipts.

set("description", e.target.value)} placeholder="Bring the whole family" />
{d.items.map((it, i) => { const opt = options.find(o => o.id === it.eventOptionId); const hasVariants = (opt?.variants || []).length > 0; return (
setItem(i, { quantity: e.target.value })} aria-label="Quantity" required /> ×
{hasVariants && ( )}
); })}
set("price", e.target.value)} required />
Separately
{fmtRand(standardValue)}
Bundle
{d.price === "" ? "—" : fmtRand(price)}
Saving
{d.price === "" ? "—" : fmtRand(Math.max(0, saving_))}
{d.price !== "" && saving_ <= 0 &&

The bundle isn't cheaper than the standard prices, so it won't apply unless prices change.

}
set("validFrom", e.target.value)} />
set("validUntil", e.target.value)} />
{error &&
{error}
}
); }