"use client"; import React, { useEffect, useState } from "react"; import { Gift } from "lucide-react"; import { apiFetch } from "@/lib/api"; import type { BundleItem, BundleQuote, PublicBundle } from "@/types"; import type { BasketItem } from "@/components/shared/CouponCodeField"; const fmt = (n: number) => `R${n.toFixed(2)}`; /** * The bundle deals a basket gets, from POST /api/bundles/quote (the server prices the * basket the same way registration will). Null while there's nothing to show. Pass * `enabled={false}` when the event has no bundles to skip the request. * * Staff pricing on someone's behalf pass `forUserId` (the attendee), or `null` for a * walk-in with no account yet. */ export function useBundleQuote({ eventId, basket, token, forUserId, enabled = true }: { eventId: string; basket: BasketItem[]; token?: string | null; forUserId?: string | null; enabled?: boolean; }): BundleQuote | null { const [quote, setQuote] = useState(null); const items = basket.filter(b => b.quantity > 0); const key = JSON.stringify(items); useEffect(() => { const options = JSON.parse(key) as BasketItem[]; if (!enabled || !eventId || options.length === 0) { setQuote(null); return; } let cancelled = false; const timer = setTimeout(async () => { try { const body: Record = { eventId, options }; if (forUserId !== undefined) body.forUserId = forUserId; const res = await apiFetch("/api/bundles/quote", { method: "POST", authToken: token || undefined, body }); if (!cancelled) setQuote(res.bundleDiscount > 0 ? res : null); } catch { if (!cancelled) setQuote(null); } }, 300); return () => { cancelled = true; clearTimeout(timer); }; }, [eventId, key, token, forUserId, enabled]); return quote; } /** The event's deals, so buyers know what to pick. Applied automatically. */ export function BundleOffers({ bundles, className = "" }: { bundles?: PublicBundle[] | null; className?: string }) { if (!bundles || bundles.length === 0) return null; return (
Bundle deals
    {bundles.map(b => (
  • {b.name}: {b.headline} {b.savingText && ({b.savingText})} {b.description && {b.description}}
  • ))}

Applied automatically when your tickets match.

); } /** "Family deal ×2 −R100.00" lines for a quote or a saved registration's bundles. */ export function BundleSavings({ applications, className = "" }: { applications?: { bundleId: string; name?: string; count: number; discount: number; bundle?: { name: string } | null }[] | null; className?: string; }) { const rows = (applications || []).filter(a => a.discount > 0); if (rows.length === 0) return null; return (
{rows.map(a => (
{a.name || a.bundle?.name || "Bundle deal"}{a.count > 1 ? ` ×${a.count}` : ""} −{fmt(a.discount)}
))}
); } // Just what the builder reads, so pages with their own option types can pass them in. type BuilderOption = { id: string; name: string; stockLimit?: number | null; availableCount?: number | null; variants?: { id: string; name: string; stockLimit?: number | null; availableCount?: number | null }[] | null; }; type Qty = (optionId: string, variantId: string | null) => number; type Change = { optionId: string; variantId: string | null; quantity: number }; const leftOf = (stockLimit?: number | null, availableCount?: number | null) => ((stockLimit ?? 0) > 0 && availableCount !== undefined && availableCount !== null ? availableCount : Infinity); /** Tickets of this item already in the basket. An "any variant" item counts every variant. */ function itemHave(item: BundleItem, opt: BuilderOption | undefined, qty: Qty) { if (!opt) return 0; if (item.variantId) return qty(opt.id, item.variantId); const variants = opt.variants || []; return variants.length > 0 ? variants.reduce((s, v) => s + qty(opt.id, v.id), 0) : qty(opt.id, null); } /** Every basket line (option, or option + variant) that counts towards a bundle, without repeats. */ function qualifyingKeys(bundle: PublicBundle, options: BuilderOption[]) { const keys: { opt: BuilderOption; variantId: string | null }[] = []; const seen = new Set(); for (const item of bundle.items) { const opt = options.find(o => o.id === item.eventOptionId); if (!opt) continue; const variants = opt.variants || []; const ids = variants.length === 0 ? [null] : item.variantId ? [item.variantId] : variants.map(v => v.id); for (const variantId of ids) { const k = `${opt.id}::${variantId || ""}`; if (!seen.has(k)) { seen.add(k); keys.push({ opt, variantId }); } } } return keys; } /** Places left for one basket line, or Infinity. */ function roomFor(opt: BuilderOption, variantId: string | null, qty: Qty) { const variant = variantId ? (opt.variants || []).find(v => v.id === variantId) : null; return Math.min(leftOf(opt.stockLimit, opt.availableCount), variant ? leftOf(variant.stockLimit, variant.availableCount) : Infinity) - qty(opt.id, variantId); } /** * Exact bundles: quantities that make up `sets` full sets, or null when there aren't * enough tickets left. Only ever raises quantities. An "any variant" item tops up the * variant already picked most (or the first one with places left). */ function exactChanges(bundle: PublicBundle, options: BuilderOption[], qty: Qty, sets: number): Change[] | null { const changes: Change[] = []; for (const item of bundle.items) { const opt = options.find(o => o.id === item.eventOptionId); if (!opt) return null; const short = sets * item.quantity - itemHave(item, opt, qty); if (short <= 0) continue; let variantId = item.variantId || null; if (!variantId && (opt.variants || []).length > 0) { const pick = (opt.variants || []).filter(v => roomFor(opt, v.id, qty) >= short).sort((a, b) => qty(opt.id, b.id) - qty(opt.id, a.id))[0]; if (!pick) return null; variantId = pick.id; } if (roomFor(opt, variantId, qty) < short) return null; changes.push({ optionId: opt.id, variantId, quantity: qty(opt.id, variantId) + short }); } return changes; } /** Pick-any and group bundles: add `count` tickets to the qualifying line picked most. */ function topUpChange(bundle: PublicBundle, options: BuilderOption[], qty: Qty, count: number): Change[] | null { if (count <= 0) return []; const pick = qualifyingKeys(bundle, options) .filter(k => roomFor(k.opt, k.variantId, qty) >= count) .sort((a, b) => qty(b.opt.id, b.variantId) - qty(a.opt.id, a.variantId))[0]; if (!pick) return null; return [{ optionId: pick.opt.id, variantId: pick.variantId, quantity: qty(pick.opt.id, pick.variantId) + count }]; } const orList = (summary: string) => summary.replace(/, ([^,]*)$/, " or $1"); const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`; type Row = { bundle: PublicBundle; // Something from the bundle is in the basket. touched: boolean; // Full sets in the basket (for a group discount: 1 once it applies). sets: number; // A set (or the group) has been started but isn't complete. partial: boolean; // What's missing, in words. missing: string; // Quantities to complete it (partial) or add another set (complete); null = no room. next: Change[] | null; // false for a group discount once it applies: it has no "another one". canAddMore: boolean; }; function rowFor(bundle: PublicBundle, options: BuilderOption[], qty: Qty): Row { const kind = bundle.kind || "exact"; if (kind === "exact") { const have = bundle.items.map(item => { const opt = options.find(o => o.id === item.eventOptionId); return { item, opt, n: itemHave(item, opt, qty) }; }); const sets = Math.min(...have.map(h => Math.floor(h.n / h.item.quantity))); // Tickets beyond the full sets mean the next set has been started. const partial = have.some(h => h.n > sets * h.item.quantity); const missing = have .filter(h => h.n < (sets + 1) * h.item.quantity) .map(h => { const v = h.item.variantId ? (h.opt?.variants || []).find(x => x.id === h.item.variantId) : null; return `${(sets + 1) * h.item.quantity - h.n} × ${h.opt?.name || "ticket"}${v ? ` (${v.name})` : ""}`; }) .join(" and "); return { bundle, touched: have.some(h => h.n > 0), sets, partial, missing, next: exactChanges(bundle, options, qty, sets + 1), canAddMore: true }; } const size = Number(bundle.setSize) || 1; const have = qualifyingKeys(bundle, options).reduce((s, k) => s + qty(k.opt.id, k.variantId), 0); const names = orList(bundle.summary); if (kind === "group") { const short = Math.max(0, size - have); return { bundle, touched: have > 0, sets: short === 0 ? 1 : 0, partial: short > 0, missing: `${plural(short, "more ticket")} (${names})`, next: topUpChange(bundle, options, qty, short), canAddMore: false, }; } const sets = Math.floor(have / size); const short = have % size === 0 ? size : size - (have % size); return { bundle, touched: have > 0, sets, partial: have % size > 0, missing: `${plural(short, "more ticket")} (${names})`, next: topUpChange(bundle, options, qty, short), canAddMore: true, }; } /** * On the register form, at the door, manual registration and the kiosk: each bundle the * basket has started on, with what's missing and a "Complete" button, then "+" to add * another full set. Buttons set the ticket quantities through `onSetQuantity`. */ export function BundleBuilder({ bundles, options, qty, onSetQuantity, className = "" }: { bundles?: PublicBundle[] | null; options: BuilderOption[]; qty: Qty; onSetQuantity: (optionId: string, variantId: string | null, quantity: number) => void; className?: string; }) { const rows = (bundles || []).map(b => rowFor(b, options, qty)).filter(r => r.touched); if (rows.length === 0) return null; const apply = (changes: Change[]) => changes.forEach(c => onSetQuantity(c.optionId, c.variantId, c.quantity)); return (
{rows.map(({ bundle, sets, partial, missing, next, canAddMore }) => { const isGroup = bundle.kind === "group"; const done = isGroup ? `✓ Group price on all your ${orList(bundle.summary)} tickets` : `✓ ${sets > 1 ? `${sets} bundles` : "Bundle"} in your basket`; return (
{bundle.name}
{bundle.headline}{bundle.savingText ? ` (${bundle.savingText})` : ""}
{partial ? (
Add {missing} to {isGroup ? "get the group price" : sets > 0 ? "complete another bundle" : "complete it"}.
) : (
{done}
)} {!next && (partial || canAddMore) &&
Not enough tickets left for {partial ? "this bundle" : "another one"}.
}
{partial ? ( ) : canAddMore ? (
×{sets}
) : null}
); })}
); }