"use client"; import React, { useMemo, useState } from "react"; import { CalendarDays, Plus, RotateCcw, Trash2, Ban, FileText, Repeat } from "lucide-react"; import type { CertificateConfig, CertificateTemplate } from "@/types"; import { generateSessions, formatSessionWhen, CERTIFICATE_TEMPLATES, REMINDER_OPTIONS, DEFAULT_CERTIFICATE_BODY, type SessionDraft, type SessionPattern, } from "@/lib/sessions"; // ─── Sessions (Basic Details step) ──────────────────────────────────────────── const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const newKey = () => Math.random().toString(36).slice(2, 10); export type KeyedSession = SessionDraft & { key: string }; export function keyed(s: SessionDraft): KeyedSession { return { ...s, key: s.id || newKey() }; } function todayISO() { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; } /** Sorts by start; rows still missing a date go last. */ export function sortSessions(list: KeyedSession[]): KeyedSession[] { return [...list].sort((a, b) => (a.startsAt || "9999").localeCompare(b.startsAt || "9999")); } /** Problems that block saving, or null. */ export function sessionsProblem(list: KeyedSession[]): string | null { if (!list.some(s => !s.cancelled)) return "Add at least one session"; for (const [i, s] of sortSessions(list).entries()) { if (!s.startsAt || !s.endsAt) return `Session ${i + 1} needs a start and end`; if (new Date(s.endsAt) <= new Date(s.startsAt)) return `Session ${i + 1} must end after it starts`; } return null; } function PatternBuilder({ onGenerate }: { onGenerate: (rows: SessionDraft[], mode: "replace" | "add") => void }) { const [p, setP] = useState(() => ({ frequency: "weekly", interval: 1, weekdays: [new Date().getDay()], startDate: todayISO(), startTime: "18:30", endTime: "20:30", endsBy: "count", count: 5, until: "", })); const set = (patch: Partial) => setP(x => ({ ...x, ...patch })); const preview = useMemo(() => generateSessions(p), [p]); const toggleDay = (d: number) => set({ weekdays: p.weekdays.includes(d) ? p.weekdays.filter(x => x !== d) : [...p.weekdays, d] }); return (
Repeat pattern
{p.frequency === "weekly" && (
On
{WEEKDAYS.map((d, i) => ( ))}
)}
{p.endsBy === "count" ? ( ) : ( )}

{preview.length === 0 ? "Pick the dates and times to see the sessions." : `${preview.length} session${preview.length === 1 ? "" : "s"}: ${formatSessionWhen({ startsAt: preview[0].startsAt, endsAt: preview[0].endsAt })}${preview.length > 1 ? ` … ${formatSessionWhen({ startsAt: preview[preview.length - 1].startsAt, endsAt: preview[preview.length - 1].endsAt })}` : ""}`}

); } export function SessionsEditor({ sessions, onChange, defaultLocation, showCapacity }: { sessions: KeyedSession[]; onChange: (s: KeyedSession[]) => void; defaultLocation?: string; showCapacity?: boolean }) { const [showPattern, setShowPattern] = useState(sessions.length === 0); const sorted = sortSessions(sessions); const activeCount = sessions.filter(s => !s.cancelled).length; const update = (key: string, patch: Partial) => onChange(sessions.map(s => (s.key === key ? { ...s, ...patch } : s))); const remove = (key: string) => onChange(sessions.filter(s => s.key !== key)); const generate = (rows: SessionDraft[], mode: "replace" | "add") => { const fresh = rows.map(keyed); // Saved sessions with check-ins can't be removed, so "replace" keeps them. const kept = mode === "replace" ? sessions.filter(s => s.hasCheckIns) : sessions; onChange(sortSessions([...kept, ...fresh])); setShowPattern(false); }; const addOne = () => { const last = sorted[sorted.length - 1]; const base = last?.startsAt ? new Date(last.startsAt) : new Date(); const dur = last?.startsAt && last?.endsAt ? new Date(last.endsAt).getTime() - new Date(last.startsAt).getTime() : 2 * 60 * 60 * 1000; const start = new Date(base.getTime() + (last ? 7 * 24 * 60 * 60 * 1000 : 0)); const p = (n: number) => String(n).padStart(2, "0"); const fmt = (d: Date) => `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`; onChange([...sessions, keyed({ label: "", startsAt: fmt(start), endsAt: fmt(new Date(start.getTime() + dur)), location: "", cancelled: false, capacity: last?.capacity || "" })]); }; let position = 0; return (
{showPattern ? : ( )} {sorted.length > 0 && (
{activeCount} session{activeCount === 1 ? "" : "s"} — edit any date, add a label, or cancel one (e.g. a public holiday).
{sorted.map((s) => { if (!s.cancelled) position += 1; return (
{s.cancelled ? "—" : position} update(s.key, { label: e.target.value })} disabled={s.cancelled} /> {s.cancelled ? ( ) : s.id ? ( ) : null} {!s.hasCheckIns && ( )}
{!s.cancelled && (
{showCapacity && ( )}
)} {s.hasCheckIns &&

Has check-ins — it can be cancelled but not removed.

}
); })}
)}
); } // ─── Attendance step ────────────────────────────────────────────────────────── export type AttendanceDraft = { lateJoinEnabled: boolean; lateJoinUntilKey: string; latePricing: "full" | "prorata" | "fixed"; lateFixedPrice: string; checkInWindow: "whole_day" | "session_only"; remindersEnabled: boolean; reminderOffsets: number[]; reminderChannels: ("email" | "whatsapp")[]; certificatesEnabled: boolean; certificate: CertificateConfig; }; export function defaultCertificate(): CertificateConfig { return { template: "classic", title: "Certificate of Completion", body: DEFAULT_CERTIFICATE_BODY, signatureName: "", signatureRole: "", signatureImage: "", rule: { type: "all", value: null }, sendOnIssue: false }; } function Toggle({ id, checked, onChange, title, children }: { id: string; checked: boolean; onChange: (v: boolean) => void; title: string; children?: React.ReactNode }) { return (
onChange(e.target.checked)} />
); } export function AttendanceSettings({ value, onChange, multi, sessions, mainPrice, onPreview, uploadButton }: { value: AttendanceDraft; onChange: (patch: Partial) => void; multi: boolean; sessions: KeyedSession[]; mainPrice: number; onPreview: () => Promise; uploadButton: (onUploaded: (url: string) => void) => React.ReactNode; }) { const [previewing, setPreviewing] = useState(false); const [previewError, setPreviewError] = useState(null); const active = sortSessions(sessions).filter(s => !s.cancelled); const cert = value.certificate; const setCert = (patch: Partial) => onChange({ certificate: { ...cert, ...patch } }); const total = active.length; const examplePrice = mainPrice > 0 ? mainPrice : 300; const example = total > 1 ? (() => { const left = total - 1; const v = Math.min(examplePrice, Math.max(10, Math.round((examplePrice * left / total) / 10) * 10)); return `e.g. R${examplePrice} with ${left} of ${total} sessions left → R${v}`; })() : null; return (
{multi && (

Late joining

onChange({ lateJoinEnabled: v })} title="Let people join after the first session"> Without this, registration closes when the first session starts. {value.lateJoinEnabled && (
Price for late joiners (main tickets only) {([ ["full", "Full price"], ["prorata", "Pro-rata on the sessions left (rounded to the nearest R10)"], ["fixed", "A fixed late price"], ] as const).map(([v, label]) => ( ))} {value.latePricing === "prorata" && example &&

{example}

} {value.latePricing === "fixed" && (
onChange({ lateFixedPrice: e.target.value })} />

Only ever lowers the price — anyone whose normal price is already lower keeps it.

)}
)}
)} {multi && (

Check-in

{([ ["whole_day", "Whole day", "Any time on the session's date — handy if someone was let in without being scanned."], ["session_only", "Session time only", "From 2 hours before the session starts until it ends."], ] as const).map(([v, title, hint]) => ( ))}
)} {multi && (

Session reminders

onChange({ remindersEnabled: v })} title="Remind ticket holders before each session" /> {value.remindersEnabled && (
When
{REMINDER_OPTIONS.map(o => ( ))}
How
{(["email", "whatsapp"] as const).map(c => ( ))}

Each person's notification preference still applies.

)}
)}

Certificates

onChange({ certificatesEnabled: v })} title="Give completion certificates"> Issued automatically when the event ends to everyone who meets the rule below. You can also issue them from the attendance register. {value.certificatesEnabled && (
{CERTIFICATE_TEMPLATES.map(t => ( ))}