"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { fetchManagedEvents } 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 { BundleGroupPricing, BundleKind, EventBundle } from "@/types"; import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; 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; kind: BundleKind; price: string; setSize: string; freeCount: string; groupPricing: BundleGroupPricing; items: ItemDraft[]; validFrom: string; validUntil: string; isActive: boolean; }; const blankDraft = (options: OptionLite[]): Draft => ({ name: "", description: "", kind: "exact", price: "", setSize: "4", freeCount: "1", groupPricing: "per_ticket", 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 || "", kind: b.kind || "exact", price: b.kind === "free" ? "" : String(b.price), setSize: b.setSize ? String(b.setSize) : "4", freeCount: b.freeCount ? String(b.freeCount) : "1", groupPricing: b.groupPricing || "per_ticket", 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 KIND_INFO: Record = { exact: { label: "Exact set", hint: "These tickets in these numbers", example: "2 adults + 3 kids for R220" }, mix: { label: "Pick any", hint: "Any mix of the chosen tickets", example: "Any 4 tickets for R250" }, free: { label: "Buy X get Y free", hint: "Cheapest ones in each set are free", example: "Buy 3, get 1 free" }, group: { label: "Group discount", hint: "A lower price from a group size up", example: "10+ tickets: R70 each" }, }; /** 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 [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; fetchManagedEvents(token, { past: true }) .then(list => setAllEvents(list || [])) .catch(e => setError(errorMessage(e) || "Failed to load events")); }, [token, canView, setError]); // Start on the next upcoming event (or the latest one). useEffect(() => { if (!allEvents.some(e => e.id === eventId)) setEventId(defaultEventId(allEvents)); }, [allEvents, eventId]); const event = allEvents.find(e => e.id === eventId) || null; const options = event?.eventOptions || []; const load = useCallback(async () => { if (!token || !eventId) { setBundles([]); return; } setFetching(true); try { setBundles(await (apiV2Data("get", "/events/{id}/bundles", { params: { id: eventId }, authToken: token }) as Promise)); } 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 apiV2Data("patch", "/bundles/{id}", { params: { id: b.id }, 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 (apiV2Data("delete", "/bundles/{id}", { params: { id: b.id }, authToken: token }) as Promise<{ message: string }>); 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 kind = b.kind || "exact"; 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}
{KIND_INFO[kind].label}{kind === "exact" ? "" : ` · ${kind === "group" ? "qualifying" : "any of"}:`}
{b.items.map(i => ( {kind === "exact" && {i.quantity} ×} {i.eventOption?.name || "Ticket"}{i.variant ? ` (${i.variant.name})` : ""} ))}
{kind === "exact" || kind === "mix" ? ( <> {fmtRand(b.price)} {kind === "mix" ? `for any ${b.setSize}` : "for the set"} {b.standardValue !== null && {fmtRand(b.standardValue)}} ) : kind === "free" ? ( Buy {(b.setSize || 0) - (b.freeCount || 0)}, get {b.freeCount} free ) : ( <> {b.groupPricing === "percent" ? `${b.price}% off` : `${fmtRand(b.price)} each`} from {b.setSize} tickets )}
{b.savingText || (kind === "free" || (kind === "group" && b.groupPricing === "percent") ? "" : "No saving at the standard prices")}
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 exact = d.kind === "exact"; const price = Number(d.price) || 0; const size = Math.max(0, Math.floor(Number(d.setSize) || 0)); const free = Math.max(0, Math.floor(Number(d.freeCount) || 0)); const dearest = d.items.reduce((m, it) => Math.max(m, unitPrice(options, it)), 0); // Exact: what the set costs separately. Pick any: the dearest possible set. const standardValue = exact ? d.items.reduce((s, it) => s + unitPrice(options, it) * (Number(it.quantity) || 0), 0) : dearest * size; const saving_ = standardValue - price; const priceLabel = exact ? "Bundle price (R)" : d.kind === "mix" ? "Price for the set (R)" : d.groupPricing === "percent" ? "Percentage off (%)" : "Price per ticket (R)"; const save = async (e: React.FormEvent) => { e.preventDefault(); setError(null); setSaving(true); try { const body = { name: d.name.trim(), description: d.description.trim() || null, kind: d.kind, price: d.kind === "free" ? 0 : Number(d.price), setSize: exact ? null : Number(d.setSize), freeCount: d.kind === "free" ? Number(d.freeCount) : null, groupPricing: d.kind === "group" ? d.groupPricing : null, items: d.items.map(it => ({ eventOptionId: it.eventOptionId, variantId: it.variantId, quantity: exact ? Number(it.quantity) : 1 })), validFrom: d.validFrom ? new Date(d.validFrom).toISOString() : null, validUntil: d.validUntil ? new Date(d.validUntil).toISOString() : null, isActive: d.isActive, }; if (bundleId) { await apiV2Data("patch", "/bundles/{id}", { params: { id: bundleId }, authToken: token, body: body as never }); onSaved(`${body.name} saved.`); } else { await apiV2Data("post", "/events/{id}/bundles", { params: { id: event.id }, authToken: token, body: body as never }); 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" />
{(Object.keys(KIND_INFO) as BundleKind[]).map(k => ( ))}
{!exact &&

Any of these count towards the deal.

}
{d.items.map((it, i) => { const opt = options.find(o => o.id === it.eventOptionId); const hasVariants = (opt?.variants || []).length > 0; return (
{exact && ( <> setItem(i, { quantity: e.target.value })} aria-label="Quantity" required /> × )}
{hasVariants && ( )}
); })}
{!exact && (
set("setSize", e.target.value)} required />
{d.kind === "free" && (
set("freeCount", e.target.value)} required />
)} {d.kind === "group" && (
)}
)} {d.kind === "free" ? (
{size > free && free > 0 ? <>Buy {size - free}, get {free} free. In every {size} qualifying tickets, the cheapest {free === 1 ? "one is" : `${free} are`} free. : The set needs more tickets than are free.}
) : (
set("price", e.target.value)} required /> {d.kind === "group" ? (

{size >= 2 ? `From ${size} qualifying tickets, every one of them ` : "Every qualifying ticket "} {d.groupPricing === "percent" ? `gets ${d.price || "…"}% off.` : `costs ${d.price === "" ? "…" : fmtRand(price)} (tickets already cheaper stay as they are).`}

) : ( <>
{exact ? "Separately" : "Dearest set"}
{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.

} {!exact &&

The saving depends on which tickets are picked; it only applies when the set price is cheaper.

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