This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/components/events/ScheduleEditor.tsx
T
joshuaandClaude Opus 5.5 8cc2cefe80 WIP 2.0.0: React Compiler lint rules back to errors; docs
- The 192 places the rules flagged are fixed and the rules are errors
  again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state
  that follows other state, set while rendering), useExternalEffect
  (API loads and browser reads), useNow; lib/navigation.ts hardNavigate
  for full reloads after sign-out or identity switches; other pages use
  the router. Resets moved into the handlers that cause them.
- The banner shows and hides at its times on open pages.
- HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated;
  2.0.0 section drafted in WHATS-NEW.

e2e 102/102 (PayFast sandbox skipped); production build passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:45:25 +02:00

432 lines
27 KiB
TypeScript

"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<SessionPattern>(() => ({
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<SessionPattern>) => 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 (
<div className="border rounded-lg p-3 bg-brand-50/40 space-y-3">
<div className="flex items-center gap-2 text-sm font-medium text-gray-800"><Repeat className="w-4 h-4 text-brand-600" /> Repeat pattern</div>
<div className="grid sm:grid-cols-3 gap-2">
<label className="text-xs text-gray-600">Repeats
<select className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={p.frequency} onChange={e => set({ frequency: e.target.value as SessionPattern["frequency"] })}>
<option value="weekly">Weekly</option>
<option value="daily">Daily</option>
</select>
</label>
<label className="text-xs text-gray-600">Every
<div className="mt-1 flex items-center gap-1.5">
<input type="number" min={1} max={12} className="w-16 border rounded px-2 py-1.5 text-sm" value={p.interval} onChange={e => set({ interval: Math.max(1, parseInt(e.target.value) || 1) })} />
<span className="text-sm text-gray-600">{p.frequency === "weekly" ? (p.interval === 1 ? "week" : "weeks") : (p.interval === 1 ? "day" : "days")}</span>
</div>
</label>
<label className="text-xs text-gray-600">First date
<input type="date" className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={p.startDate} onChange={e => set({ startDate: e.target.value })} />
</label>
</div>
{p.frequency === "weekly" && (
<div>
<div className="text-xs text-gray-600 mb-1">On</div>
<div className="flex flex-wrap gap-1">
{WEEKDAYS.map((d, i) => (
<button key={d} type="button" onClick={() => toggleDay(i)}
className={`px-2.5 py-1 text-xs rounded-full border ${p.weekdays.includes(i) ? "bg-brand-600 text-white border-brand-600" : "bg-white text-gray-700 border-gray-200 hover:bg-gray-50"}`}>{d}</button>
))}
</div>
</div>
)}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
<label className="text-xs text-gray-600">From
<input type="time" className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={p.startTime} onChange={e => set({ startTime: e.target.value })} />
</label>
<label className="text-xs text-gray-600">To
<input type="time" className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={p.endTime} onChange={e => set({ endTime: e.target.value })} />
</label>
<label className="text-xs text-gray-600">Ends
<select className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={p.endsBy} onChange={e => set({ endsBy: e.target.value as SessionPattern["endsBy"] })}>
<option value="count">After a number of sessions</option>
<option value="until">On a date</option>
</select>
</label>
{p.endsBy === "count" ? (
<label className="text-xs text-gray-600">Sessions
<input type="number" min={1} max={200} className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={p.count} onChange={e => set({ count: Math.max(1, Math.min(200, parseInt(e.target.value) || 1)) })} />
</label>
) : (
<label className="text-xs text-gray-600">Last date
<input type="date" className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={p.until} onChange={e => set({ until: e.target.value })} />
</label>
)}
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-xs text-gray-500">
{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 })}` : ""}`}
</p>
<div className="flex gap-2">
<button type="button" disabled={!preview.length} onClick={() => onGenerate(preview, "add")} className="px-3 py-1.5 text-xs rounded border border-gray-200 bg-white hover:bg-gray-50 disabled:opacity-50">Add to list</button>
<button type="button" disabled={!preview.length} onClick={() => onGenerate(preview, "replace")} className="px-3 py-1.5 text-xs rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">Create sessions</button>
</div>
</div>
</div>
);
}
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<KeyedSession>) => 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 || "" })]);
};
// Each active session's number (cancelled ones don't count).
const positions = sorted.map((s, i) => (s.cancelled ? 0 : sorted.slice(0, i + 1).filter(x => !x.cancelled).length));
return (
<div className="space-y-3">
{showPattern
? <PatternBuilder onGenerate={generate} />
: (
<button type="button" onClick={() => setShowPattern(true)} className="inline-flex items-center gap-1.5 text-xs text-brand-700 hover:underline">
<Repeat className="w-3.5 h-3.5" /> Create sessions from a repeat pattern
</button>
)}
{sorted.length > 0 && (
<div className="border rounded-lg divide-y">
<div className="px-3 py-2 text-xs text-gray-500 bg-gray-50 rounded-t-lg">
{activeCount} session{activeCount === 1 ? "" : "s"} — edit any date, add a label, or cancel one (e.g. a public holiday).
</div>
{sorted.map((s, i) => {
const position = positions[i];
return (
<div key={s.key} className={`p-3 space-y-2 ${s.cancelled ? "bg-gray-50" : ""}`}>
<div className="flex items-center gap-2">
<span className={`text-xs font-semibold w-6 shrink-0 ${s.cancelled ? "text-gray-400" : "text-brand-700"}`}>{s.cancelled ? "—" : position}</span>
<input className={`flex-1 min-w-0 border rounded px-2 py-1 text-sm ${s.cancelled ? "line-through text-gray-400" : ""}`} placeholder={s.cancelled ? "Cancelled" : `Session ${position} (optional label)`}
value={s.label} onChange={e => update(s.key, { label: e.target.value })} disabled={s.cancelled} />
{s.cancelled ? (
<button type="button" onClick={() => update(s.key, { cancelled: false })} className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border bg-white hover:bg-gray-50" title="Restore this session">
<RotateCcw className="w-3.5 h-3.5" /> Restore
</button>
) : s.id ? (
<button type="button" onClick={() => update(s.key, { cancelled: true })} className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100" title="Cancel this session (kept for history)">
<Ban className="w-3.5 h-3.5" /> Cancel
</button>
) : null}
{!s.hasCheckIns && (
<button type="button" onClick={() => remove(s.key)} className="p-1.5 rounded text-gray-400 hover:text-red-600 hover:bg-red-50" title="Remove">
<Trash2 className="w-4 h-4" />
</button>
)}
</div>
{!s.cancelled && (
<div className={`grid gap-2 pl-8 ${showCapacity ? "sm:grid-cols-4" : "sm:grid-cols-3"}`}>
<label className="text-[11px] text-gray-500">Starts
<input type="datetime-local" className="mt-0.5 w-full border rounded px-2 py-1 text-sm" value={s.startsAt} onChange={e => {
const v = e.target.value;
// Keep the session's length when the start moves.
const len = s.startsAt && s.endsAt ? new Date(s.endsAt).getTime() - new Date(s.startsAt).getTime() : 0;
const p2 = (n: number) => String(n).padStart(2, "0");
const end = v && len > 0 ? new Date(new Date(v).getTime() + len) : null;
update(s.key, { startsAt: v, ...(end ? { endsAt: `${end.getFullYear()}-${p2(end.getMonth() + 1)}-${p2(end.getDate())}T${p2(end.getHours())}:${p2(end.getMinutes())}` } : {}) });
}} />
</label>
<label className="text-[11px] text-gray-500">Ends
<input type="datetime-local" className="mt-0.5 w-full border rounded px-2 py-1 text-sm" value={s.endsAt} onChange={e => update(s.key, { endsAt: e.target.value })} />
</label>
<label className="text-[11px] text-gray-500">Location (optional)
<input className="mt-0.5 w-full border rounded px-2 py-1 text-sm" placeholder={defaultLocation || "Event location"} value={s.location} onChange={e => update(s.key, { location: e.target.value })} />
</label>
{showCapacity && (
<label className="text-[11px] text-gray-500" title="Most people at this session (picked places plus whole-course tickets). Blank = no limit.">Capacity
<input type="number" min={1} className="mt-0.5 w-full border rounded px-2 py-1 text-sm" placeholder="No limit" value={s.capacity} onChange={e => update(s.key, { capacity: e.target.value })} />
</label>
)}
</div>
)}
{s.hasCheckIns && <p className="pl-8 text-[10px] text-gray-400">Has check-ins — it can be cancelled but not removed.</p>}
</div>
);
})}
</div>
)}
<button type="button" onClick={addOne} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded border border-gray-200 bg-white hover:bg-gray-50">
<Plus className="w-3.5 h-3.5" /> Add a date
</button>
</div>
);
}
// ─── 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 (
<div className="flex items-start gap-2">
<input id={id} type="checkbox" className="mt-0.5" checked={checked} onChange={e => onChange(e.target.checked)} />
<label htmlFor={id} className="text-sm text-gray-800">
<span className="font-medium">{title}</span>
{children && <span className="block text-xs text-gray-500 mt-0.5">{children}</span>}
</label>
</div>
);
}
export function AttendanceSettings({ value, onChange, multi, sessions, mainPrice, onPreview, uploadButton }: {
value: AttendanceDraft;
onChange: (patch: Partial<AttendanceDraft>) => void;
multi: boolean;
sessions: KeyedSession[];
mainPrice: number;
onPreview: () => Promise<void>;
uploadButton: (onUploaded: (url: string) => void) => React.ReactNode;
}) {
const [previewing, setPreviewing] = useState(false);
const [previewError, setPreviewError] = useState<string | null>(null);
const active = sortSessions(sessions).filter(s => !s.cancelled);
const cert = value.certificate;
const setCert = (patch: Partial<CertificateConfig>) => 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 (
<div className="space-y-5">
{multi && (
<section className="space-y-3">
<h3 className="text-sm font-semibold text-gray-900 flex items-center gap-1.5"><CalendarDays className="w-4 h-4 text-brand-600" /> Late joining</h3>
<Toggle id="late-join" checked={value.lateJoinEnabled} onChange={v => onChange({ lateJoinEnabled: v })} title="Let people join after the first session">
Without this, registration closes when the first session starts.
</Toggle>
{value.lateJoinEnabled && (
<div className="pl-6 space-y-3">
<label className="block text-xs text-gray-600">Registration stays open until the start of
<select className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={value.lateJoinUntilKey} onChange={e => onChange({ lateJoinUntilKey: e.target.value })}>
<option value="">Choose a session…</option>
{active.slice(1).map((s, i) => (
<option key={s.key} value={s.key}>{s.label || `Session ${i + 2}`} — {s.startsAt ? formatSessionWhen(s) : "no date yet"}</option>
))}
</select>
</label>
<fieldset className="space-y-1.5">
<legend className="text-xs text-gray-600 mb-1">Price for late joiners (main tickets only)</legend>
{([
["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]) => (
<label key={v} className="flex items-center gap-2 text-sm">
<input type="radio" name="late-pricing" checked={value.latePricing === v} onChange={() => onChange({ latePricing: v })} /> {label}
</label>
))}
{value.latePricing === "prorata" && example && <p className="text-xs text-gray-500 pl-6">{example}</p>}
{value.latePricing === "fixed" && (
<div className="pl-6">
<input type="number" min={0} step="1" className="w-32 border rounded px-2 py-1.5 text-sm" placeholder="R" value={value.lateFixedPrice} onChange={e => onChange({ lateFixedPrice: e.target.value })} />
<p className="text-[10px] text-gray-400 mt-0.5">Only ever lowers the price — anyone whose normal price is already lower keeps it.</p>
</div>
)}
</fieldset>
</div>
)}
</section>
)}
{multi && (
<section className="space-y-2">
<h3 className="text-sm font-semibold text-gray-900">Check-in</h3>
{([
["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]) => (
<label key={v} className="flex items-start gap-2 text-sm">
<input type="radio" name="checkin-window" className="mt-1" checked={value.checkInWindow === v} onChange={() => onChange({ checkInWindow: v })} />
<span><span className="font-medium">{title}</span><span className="block text-xs text-gray-500">{hint}</span></span>
</label>
))}
</section>
)}
{multi && (
<section className="space-y-2">
<h3 className="text-sm font-semibold text-gray-900">Session reminders</h3>
<Toggle id="reminders" checked={value.remindersEnabled} onChange={v => onChange({ remindersEnabled: v })} title="Remind ticket holders before each session" />
{value.remindersEnabled && (
<div className="pl-6 grid sm:grid-cols-2 gap-3">
<div className="space-y-1">
<div className="text-xs text-gray-600">When</div>
{REMINDER_OPTIONS.map(o => (
<label key={o.minutes} className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={value.reminderOffsets.includes(o.minutes)} onChange={e => onChange({ reminderOffsets: e.target.checked ? [...value.reminderOffsets, o.minutes] : value.reminderOffsets.filter(x => x !== o.minutes) })} /> {o.label}
</label>
))}
</div>
<div className="space-y-1">
<div className="text-xs text-gray-600">How</div>
{(["email", "whatsapp"] as const).map(c => (
<label key={c} className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={value.reminderChannels.includes(c)} onChange={e => onChange({ reminderChannels: e.target.checked ? [...value.reminderChannels, c] : value.reminderChannels.filter(x => x !== c) })} /> {c === "email" ? "Email" : "WhatsApp"}
</label>
))}
<p className="text-[10px] text-gray-400">Each person&apos;s notification preference still applies.</p>
</div>
</div>
)}
</section>
)}
<section className="space-y-3">
<h3 className="text-sm font-semibold text-gray-900 flex items-center gap-1.5"><FileText className="w-4 h-4 text-brand-600" /> Certificates</h3>
<Toggle id="certificates" checked={value.certificatesEnabled} onChange={v => 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.
</Toggle>
{value.certificatesEnabled && (
<div className="pl-6 space-y-3">
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
{CERTIFICATE_TEMPLATES.map(t => (
<button key={t.id} type="button" onClick={() => setCert({ template: t.id as CertificateTemplate })}
className={`text-left p-2 rounded-lg border ${cert.template === t.id ? "border-brand-500 ring-2 ring-brand-200 bg-brand-50" : "border-gray-200 hover:bg-gray-50"}`}>
<span className="block text-sm font-medium">{t.name}</span>
<span className="block text-[11px] text-gray-500">{t.blurb}</span>
</button>
))}
</div>
<label className="block text-xs text-gray-600">Title
<input className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={cert.title} onChange={e => setCert({ title: e.target.value })} />
</label>
<label className="block text-xs text-gray-600">Wording
<textarea rows={3} className="mt-1 w-full border rounded px-2 py-1.5 text-sm" value={cert.body} onChange={e => setCert({ body: e.target.value })} />
<span className="block text-[10px] text-gray-400 mt-0.5">Fills in: {"{name}"}, {"{event}"}, {"{sessionsAttended}"}, {"{totalSessions}"}, {"{endDate}"}</span>
</label>
<div className="grid sm:grid-cols-2 gap-2">
<label className="text-xs text-gray-600">Signed by (optional)
<input className="mt-1 w-full border rounded px-2 py-1.5 text-sm" placeholder="e.g. Pastor John" value={cert.signatureName || ""} onChange={e => setCert({ signatureName: e.target.value })} />
</label>
<label className="text-xs text-gray-600">Their role (optional)
<input className="mt-1 w-full border rounded px-2 py-1.5 text-sm" placeholder="e.g. Senior Pastor" value={cert.signatureRole || ""} onChange={e => setCert({ signatureRole: e.target.value })} />
</label>
</div>
<div className="flex flex-wrap items-center gap-2 text-xs text-gray-600">
Signature image (optional):
{uploadButton(url => setCert({ signatureImage: url }))}
{cert.signatureImage && <button type="button" className="text-red-600 hover:underline" onClick={() => setCert({ signatureImage: "" })}>Remove</button>}
</div>
{multi ? (
<fieldset className="space-y-1.5">
<legend className="text-xs text-gray-600 mb-1">Who gets one</legend>
<label className="flex items-center gap-2 text-sm"><input type="radio" name="cert-rule" checked={cert.rule.type === "all"} onChange={() => setCert({ rule: { type: "all", value: null } })} /> Attended every session</label>
<label className="flex items-center gap-2 text-sm">
<input type="radio" name="cert-rule" checked={cert.rule.type === "count"} onChange={() => setCert({ rule: { type: "count", value: Math.max(1, total - 1) } })} /> Attended at least
<input type="number" min={1} className="w-16 border rounded px-2 py-0.5 text-sm" disabled={cert.rule.type !== "count"} value={cert.rule.type === "count" ? cert.rule.value ?? 1 : ""} onChange={e => setCert({ rule: { type: "count", value: Math.max(1, parseInt(e.target.value) || 1) } })} /> sessions
</label>
<label className="flex items-center gap-2 text-sm">
<input type="radio" name="cert-rule" checked={cert.rule.type === "percent"} onChange={() => setCert({ rule: { type: "percent", value: 80 } })} /> Attended at least
<input type="number" min={1} max={100} className="w-16 border rounded px-2 py-0.5 text-sm" disabled={cert.rule.type !== "percent"} value={cert.rule.type === "percent" ? cert.rule.value ?? 80 : ""} onChange={e => setCert({ rule: { type: "percent", value: Math.min(100, Math.max(1, parseInt(e.target.value) || 1)) } })} /> % of sessions
</label>
</fieldset>
) : (
<p className="text-xs text-gray-500">Everyone who was checked in gets one.</p>
)}
<Toggle id="cert-send" checked={!!cert.sendOnIssue} onChange={v => setCert({ sendOnIssue: v })} title="Send certificates automatically">
Email/WhatsApp each certificate when it&apos;s issued. Otherwise people download theirs from My Events, and you can send them from the attendance register.
</Toggle>
<div>
<button type="button" disabled={previewing} onClick={async () => {
setPreviewing(true); setPreviewError(null);
try { await onPreview(); } catch (e) { setPreviewError(e instanceof Error ? e.message : "Couldn't make the preview"); } finally { setPreviewing(false); }
}} className="px-3 py-1.5 text-xs rounded border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50">
{previewing ? "Making preview…" : "Preview certificate"}
</button>
{previewError && <p className="text-xs text-red-600 mt-1">{previewError}</p>}
</div>
</div>
)}
</section>
</div>
);
}