"use client"; import React, { useCallback, useEffect, useState } from "react"; import Link from "next/link"; import { useAuth } from "@/hooks/useAuth"; import { API_BASE } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { Megaphone, Download, PencilLine, Trash2, ListChecks, type LucideIcon } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { apiV2Data } from "@/lib/apiV2"; type RequestType = "access" | "correction" | "deletion"; type RequestStatus = "open" | "completed" | "rejected" | "cancelled"; type DataRequest = { id: string; type: RequestType; status: RequestStatus; details: string | null; response: string | null; createdAt: string; closedAt: string | null }; type ConsentEntry = { id: string; channel: "email" | "whatsapp"; granted: boolean; source: string; createdAt: string }; type PrivacyInfo = { news: { email: boolean; whatsapp: boolean }; canWhatsApp: boolean; notificationPreference: "email" | "whatsapp" | "both"; history: ConsentEntry[]; requests: DataRequest[]; }; type Msg = { type: "ok" | "err"; text: string } | null; const SOURCE_LABEL: Record = { signup: "when you signed up", activation: "when you activated your account", privacy_centre: "in your privacy settings", prompt: "when we asked after logging in", unsubscribe_link: "with an unsubscribe link", whatsapp_stop: "by replying STOP on WhatsApp", existing_account: "your account existed before we asked", admin: "by an administrator", }; const TYPE_LABEL: Record = { access: "Access", correction: "Correction", deletion: "Account deletion" }; const STATUS_TONE: Record = { open: "bg-amber-50 text-amber-700", completed: "bg-green-50 text-green-700", rejected: "bg-red-50 text-red-700", cancelled: "bg-gray-100 text-gray-600", }; const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"; function Alert({ msg }: { msg: NonNullable }) { return (
{msg.text}
); } function SectionHeader({ icon: Icon, title, tone = "brand" }: { icon: LucideIcon; title: string; tone?: "brand" | "red" }) { return (

{title}

); } function Toggle({ label, hint, checked, disabled, onChange }: { label: string; hint?: string; checked: boolean; disabled?: boolean; onChange: (v: boolean) => void }) { return ( ); } export default function PrivacyCentrePage() { const { token, logout } = useAuth(); const [info, setInfo] = useState(null); const [loadError, setLoadError] = useState(null); const load = useCallback(async () => { if (!token) return; try { setInfo(await (apiV2Data("get", "/me/privacy", { authToken: token }) as Promise)); setLoadError(null); } catch (e) { setLoadError(errorMessage(e) || "Could not load your privacy settings."); } }, [token]); useEffect(() => { load(); }, [load]); // ── News & announcements ────────────────────────────────────────────────── const [newsMsg, setNewsMsg] = useDismissingState(null); const [savingNews, setSavingNews] = useState(false); const setNews = async (channel: "email" | "whatsapp", value: boolean) => { if (!token || !info) return; setSavingNews(true); setNewsMsg(null); // Show the new state straight away; load() puts back the saved one if it fails. setInfo({ ...info, news: { ...info.news, [channel]: value } }); try { await apiV2Data("put", "/me/privacy/news", { authToken: token, body: { [channel]: value } }); await load(); setNewsMsg({ type: "ok", text: value ? "You're subscribed." : "You're unsubscribed." }); } catch (e) { await load(); setNewsMsg({ type: "err", text: errorMessage(e) || "Could not save." }); } finally { setSavingNews(false); } }; // ── Download my data ────────────────────────────────────────────────────── const [downloadMsg, setDownloadMsg] = useDismissingState(null); const [downloading, setDownloading] = useState<"json" | "pdf" | null>(null); const download = async (format: "json" | "pdf") => { if (!token) return; setDownloading(format); setDownloadMsg(null); try { const res = await fetch(`${API_BASE}/api/v2/me/privacy/export${format === "pdf" ? "?format=pdf" : ""}`, { headers: { Authorization: `Bearer ${token}` } }); if (!res.ok) { const body = await res.json().catch(() => null); throw new Error(body?.error?.message || body?.message || `Download failed (${res.status})`); } const blob = await res.blob(); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `my-data-${new Date().toISOString().slice(0, 10)}.${format}`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 2000); } catch (e) { setDownloadMsg({ type: "err", text: errorMessage(e) || "Download failed." }); } finally { setDownloading(null); } }; // ── Correction request ──────────────────────────────────────────────────── const [correction, setCorrection] = useState(""); const [correctionMsg, setCorrectionMsg] = useDismissingState(null); const [sendingCorrection, setSendingCorrection] = useState(false); const requestCorrection = async (e: React.FormEvent) => { e.preventDefault(); if (!token) return; setSendingCorrection(true); setCorrectionMsg(null); try { const res = await (apiV2Data("post", "/me/privacy/requests", { authToken: token, body: { type: "correction", details: correction } }) as Promise<{ message?: string }>); setCorrection(""); setCorrectionMsg({ type: "ok", text: res?.message || "Request sent." }); load(); } catch (e) { setCorrectionMsg({ type: "err", text: errorMessage(e) || "Could not send the request." }); } finally { setSendingCorrection(false); } }; // ── Delete my account ───────────────────────────────────────────────────── const [deleteStep, setDeleteStep] = useState<"idle" | "confirm">("idle"); const [deletePassword, setDeletePassword] = useState(""); const [deleteReason, setDeleteReason] = useState(""); const [deleteMsg, setDeleteMsg] = useDismissingState(null); const [deleting, setDeleting] = useState(false); const requestDeletion = async (e: React.FormEvent) => { e.preventDefault(); if (!token) return; setDeleting(true); setDeleteMsg(null); try { const res = await (apiV2Data("post", "/me/privacy/requests", { authToken: token, body: { type: "deletion", password: deletePassword, details: deleteReason || undefined }, }) as Promise<{ message?: string }>); setDeleteMsg({ type: "ok", text: res?.message || "Your account is closed." }); setTimeout(() => logout(), 3000); } catch (e) { setDeleteMsg({ type: "err", text: errorMessage(e) || "Could not send the request." }); } finally { setDeleting(false); } }; const openCorrection = info?.requests.some(r => r.type === "correction" && r.status === "open"); return (

Privacy

What we send you, a copy of the information we hold about you, and your rights under POPIA. Read the Privacy Policy.

{loadError && }
{/* ── News & announcements ───────────────────────────────────────── */}

Occasional messages about upcoming events. Messages about events you've registered for — tickets, reminders, changes — are always sent{info ? ` (by ${info.notificationPreference === "both" ? "email and WhatsApp" : info.notificationPreference === "whatsapp" ? "WhatsApp" : "email"}; change this in ` : " (change how in "} Profile & Security).

{info ? (
setNews("email", v)} /> setNews("whatsapp", v)} />
) : !loadError &&

Loading…

} {newsMsg && } {info && info.history.length > 0 && (
History of your choices
    {info.history.slice(0, 20).map(h => (
  • {new Date(h.createdAt).toLocaleString()} — {h.channel === "email" ? "email" : "WhatsApp"} {h.granted ? "on" : "off"}, {SOURCE_LABEL[h.source] || h.source}
  • ))}
)}
{/* ── Download my data ───────────────────────────────────────────── */}

A copy of everything we hold about you: your account, registrations, the people you registered, form answers, payments, tickets and check-ins, certificates, feedback and your communication choices.

{downloadMsg && }
{/* ── My requests ────────────────────────────────────────────────── */} {info && info.requests.length > 0 && (
    {info.requests.map(r => (
  • {TYPE_LABEL[r.type]} {r.status} {new Date(r.createdAt).toLocaleDateString()}
    {r.details &&

    {r.details}

    } {r.response &&

    Our answer: {r.response}

    }
  • ))}
)}
{/* ── Correct my data ────────────────────────────────────────────── */}

Change your name, email or phone number yourself in{" "} Profile & Security. For anything you can't change there — such as details on a past registration, an attendee's date of birth or a form answer — tell us what is wrong and we'll correct it.

{openCorrection ? (

You have a correction request open — we'll email you when it's done.

) : (