<script lang="ts">
	import { goto } from '$app/navigation';
	import { authStore } from '$lib/stores/auth.svelte';
	import { apiFetch } from '$lib/utils/api';
	import { browser } from '$app/environment';
	import { Button } from '$lib/components/ui/button';
	import * as Card from '$lib/components/ui/card';
	import { Skeleton } from '$lib/components/ui/skeleton';
	import { Separator } from '$lib/components/ui/separator';
	import { SvelteMap } from 'svelte/reactivity';

	type GdprData = {
		user_profile: {
			id: string;
			first_name: string;
			last_name: string;
			full_name: string;
			email: string;
			phone: string;
			date_of_birth: string;
			profile_pic_url?: string;
			account_role: string;
			account_type: string;
			last_login_at: string;
			loyalty_stamps: number;
			deposits_required: number;
			referral_code: string;
			privacy_policy_and_terms_consent: boolean;
			policy_consent_updated_at: string;
			data_retention_consent: boolean;
			data_consent_updated_at: string;
			created_at: string;
			updated_at: string;
			failed_attempts?: number;
			locked_until?: string;
		};
		bookings: Array<{
			booking_id: string;
			start_time: string;
			status: string;
			notes?: string;
			created_by?: string;
			created_at: string;
			updated_at: string;
			total_price: number;
			services: Array<{
				service_id: string;
				name: string;
				description: string;
				price: number;
				duration_minutes: number;
			}>;
		}>;
		payments: Array<{
			payment_id: string;
			booking_id: string;
			payment_type: string;
			payment_method: string;
			vendor_code?: string;
			invoice_number: number;
			status: string;
			amount: number;
			vat_amount: number;
			net_amount: number;
			created_at: string;
			updated_at: string;
		}>;
		patch_tests?: Array<{
			patch_test_id: string;
			name: string;
			description: string;
			tested_at: string;
		}>;
		referrals: {
			referred_by?: {
				referrer_id: string;
				referrer_name: string;
				referred_at: string;
			};
			referred_users: Array<{
				referred_id: string;
				referred_name: string;
				referred_at: string;
			}>;
		};
		referral_discounts?: Array<{
			id: string;
			discount_percent: number;
			used: boolean;
			created_at: string;
			used_at?: string;
		}>;
		notification_preferences?: Array<{
			email_enabled: boolean;
			sms_enabled: boolean;
			browser_push_enabled: boolean;
			updated_at: string;
		}>;
		saved_cards?: Array<{
			card_id: string;
			brand: string;
			last_4: string;
			exp_month: number;
			exp_year: number;
			fingerprint?: string;
			is_default: boolean;
			deleted_at?: string;
			retained_until?: string;
			created_at: string;
		}>;
		refunds?: Array<{
			refund_id: string;
			payment_id: string;
			booking_id: string;
			amount: number;
			status: string;
			reason: string;
			created_at: string;
		}>;
		social_logins?: Array<{
			provider: string;
			created_at: string;
		}>;
		loyalty_redemptions?: Array<{
			id: string;
			stamps_redeemed: number;
			status: string;
			booking_date?: string;
			booking_services?: string;
			redeemed_at: string;
			applied_at?: string;
			expires_at?: string;
		}>;
		booking_discounts?: Array<{
			id: string;
			booking_id: string;
			campaign_name: string;
			discount_source: string;
			source_id?: string;
			campaign_type: string;
			milestone_type?: string;
			discount_percent: number;
			original_total: number;
			discount_amount: number;
			applied_at: string;
		}>;
		edit_requests?: Array<{
			id: string;
			booking_id: string;
			new_start_time?: string;
			new_services?: string[];
			notes?: string;
			has_overrides: boolean;
			updated_at: string;
		}>;
		affiliate_payouts?: Array<{
			id: string;
			amount: number;
			status: string;
			created_at: string;
		}>;
		verification_codes?: Array<{
			purpose: string;
			created_at: string;
			used_at?: string;
			expires_at: string;
		}>;
		forgiven_no_shows?: Array<{
			id: string;
			booking_id: string;
			created_at: string;
		}>;
		name_history?: Array<{
			previous_first_name: string;
			previous_last_name: string;
			booking_id?: string;
			changed_at: string;
		}>;
		login_audit?: Array<{
			attempt_type: string;
			ip_address: string;
			success: boolean;
			created_at: string;
		}>;
		refresh_tokens?: Array<{
			role: string;
			revoked: boolean;
			created_at: string;
			expires_at: string;
		}>;
		export_metadata?: {
			exported_at: string;
			exported_by: string;
			user_id: string;
			format_version: string;
		};
	};

	let pageState = $state<'loading' | 'unauthorized' | 'generating' | 'loaded' | 'error'>('loading');
	let gdprData = $state<GdprData | null>(null);
	let errorMessage = $state('');
	let pollTimer: ReturnType<typeof setTimeout> | null = null;

	$effect(() => {
		if (!browser) return;
		if (authStore.isLoading) {
			pageState = 'loading';
			return;
		}
		if (!authStore.isAuthenticated) {
			pageState = 'unauthorized';
			// eslint-disable-next-line svelte/no-navigation-without-resolve
			goto('/login', { replaceState: true });
			return;
		}
		if (pageState === 'loading') {
			pageState = 'generating';
			fetchGdprData();
		}
	});

	function stopPolling() {
		if (pollTimer) {
			clearTimeout(pollTimer);
			pollTimer = null;
		}
	}

	async function fetchGdprData() {
		stopPolling();
		try {
			const res = await apiFetch('/api/user/gdpr-export');
			if (res.ok) {
				const data = await res.json();
				if (data.status === 'generating') {
					pageState = 'generating';
					pollTimer = setTimeout(fetchGdprData, 2000);
				} else {
					gdprData = data as GdprData;
					pageState = 'loaded';
				}
			} else {
				const text = await res.text();
				errorMessage = `Failed to fetch data (${res.status}): ${text}`;
				pageState = 'error';
			}
			// eslint-disable-next-line @typescript-eslint/no-unused-vars
		} catch (e) {
			errorMessage = 'Network error — could not connect to server.';
			pageState = 'error';
		}
	}

	function handleGotoAccount() {
		// eslint-disable-next-line svelte/no-navigation-without-resolve
		goto('/account');
	}

	function handlePrint() {
		window.print();
	}

	function fmt(amount: number): string {
		return `£${Number(amount).toFixed(2)}`;
	}

	function fmtDate(dateStr: string): string {
		if (!dateStr) return '—';
		const d = new Date(dateStr);
		return d.toLocaleDateString('en-GB', {
			day: 'numeric',
			month: 'short',
			year: 'numeric',
			timeZone: 'Europe/London'
		});
	}

	function fmtDateTime(dateStr: string): string {
		if (!dateStr) return '—';
		const d = new Date(dateStr);
		return d.toLocaleString('en-GB', {
			day: 'numeric',
			month: 'short',
			year: 'numeric',
			hour: '2-digit',
			minute: '2-digit',
			timeZone: 'Europe/London'
		});
	}

	function badge(status: string): string {
		const s = status.toLowerCase();
		if (['completed', 'confirmed', 'successful', 'active', 'paid', 'approved'].includes(s))
			return 'bg-green-100 text-green-700';
		if (['pending', 'processing', 'initiated'].includes(s)) return 'bg-yellow-100 text-yellow-700';
		if (['cancelled', 'failed', 'refunded', 'deleted'].includes(s))
			return 'bg-red-100 text-red-700';
		return 'bg-gray-100 text-gray-600';
	}

	function hasReferralData(r: GdprData['referrals']): boolean {
		return !!(r?.referred_by || (r?.referred_users && r.referred_users.length > 0));
	}

	const hasVat = $derived(
		gdprData?.payments?.some((p) => p.vat_amount && Number(p.vat_amount) > 0) ?? false
	);

	type BookingStats = {
		totalBookings: number;
		completed: number;
		cancelled: number;
		noShow: number;
		pending: number;
		totalSpent: number;
		totalRefunded: number;
		netSpent: number;
		avgBookingValue: number;
		memberSince: string;
		totalLoyaltyStamps: number;
		stampsRedeemed: number;
		totalDiscounts: number;
		topServices: Array<{ name: string; count: number; total: number }>;
		paymentMethods: Array<{ method: string; count: number; total: number }>;
		forgivenNoShows: number;
		editRequests: number;
		patchTests: number;
		savedCards: number;
		referredBy: string | null;
		referredCount: number;
	};

	type SecondaryStat = {
		label: string;
		value: string;
		subtitle: string;
		highlight?: boolean;
	};

	function computeSecondaryStats(stats: BookingStats, data: GdprData): SecondaryStat[] {
		const candidates: SecondaryStat[] = [
			{
				label: 'Loyalty Stamps',
				value: `${stats.totalLoyaltyStamps} total`,
				subtitle: `${stats.stampsRedeemed} redeemed, ${data.user_profile.loyalty_stamps} remaining`
			},
			{
				label: 'Discounts Received',
				value: fmt(stats.totalDiscounts),
				subtitle: `${data.booking_discounts?.length ?? 0} discount(s) applied`,
				highlight: true
			},
			{
				label: 'Patch Tests',
				value: `${stats.patchTests}`,
				subtitle: 'completed'
			},
			{
				label: 'Edits or Reschedules',
				value: `${stats.editRequests}`,
				subtitle: 'submitted'
			},
			{
				label: 'Saved Cards',
				value: `${stats.savedCards}`,
				subtitle: 'on file'
			}
		];

		const nonZero = candidates.filter((c) => {
			const num = parseInt(c.value.replace(/[^0-9.-]+/g, ''), 10);
			return num > 0;
		});
		const zero = candidates.filter((c) => {
			const num = parseInt(c.value.replace(/[^0-9.-]+/g, ''), 10);
			return num <= 0;
		});

		const result = [...nonZero, ...zero];
		return result.slice(0, 3);
	}

	function computeBookingStats(data: GdprData | null): BookingStats | null {
		if (!data) return null;
		const bookings = data.bookings ?? [];
		const payments = data.payments ?? [];
		const refunds = data.refunds ?? [];
		const discounts = data.booking_discounts ?? [];
		const redemptions = data.loyalty_redemptions ?? [];
		const noShows = data.forgiven_no_shows ?? [];
		const edits = data.edit_requests ?? [];
		const patchTests = data.patch_tests ?? [];

		const completedBookings = bookings.filter((b) => b.status === 'completed');
		const cancelledBookings = bookings.filter(
			(b) =>
				b.status === 'client_cancelled' || b.status === 'we_cancelled' || b.status === 'no_show'
		);
		const noShowBookings = bookings.filter((b) => b.status === 'no_show');
		const pendingBookings = bookings.filter(
			(b) => b.status === 'pending' || b.status === 'confirmed'
		);

		const totalSpent = payments
			.filter((p) => p.status === 'completed')
			.reduce((sum, p) => sum + Number(p.amount), 0);
		const totalRefunded = refunds
			.filter((r) => r.status === 'completed')
			.reduce((sum, r) => sum + Number(r.amount), 0);

		const serviceMap = new SvelteMap<string, { count: number; total: number }>();
		for (const b of bookings) {
			for (const s of b.services ?? []) {
				const existing = serviceMap.get(s.name) ?? { count: 0, total: 0 };
				existing.count++;
				existing.total += Number(s.price);
				serviceMap.set(s.name, existing);
			}
		}
		const topServices = Array.from(serviceMap.entries())
			.map(([name, data]) => ({ name, ...data }))
			.sort((a, b) => b.count - a.count)
			.slice(0, 5);

		const methodMap = new SvelteMap<string, { count: number; total: number }>();
		for (const p of payments.filter((p) => p.status === 'completed')) {
			if (p.payment_method === 'discount') continue;
			const method = p.payment_method.replace(/_/g, ' ');
			const existing = methodMap.get(method) ?? { count: 0, total: 0 };
			existing.count++;
			existing.total += Number(p.amount);
			methodMap.set(method, existing);
		}
		const paymentMethods = Array.from(methodMap.entries())
			.map(([method, data]) => ({ method, ...data }))
			.sort((a, b) => b.total - a.total);

		const totalDiscounts = discounts.reduce((sum, d) => sum + Number(d.discount_amount), 0);
		const stampsRedeemed = redemptions.reduce((sum, r) => sum + Number(r.stamps_redeemed), 0);

		return {
			totalBookings: bookings.length,
			completed: completedBookings.length,
			cancelled: cancelledBookings.length,
			noShow: noShowBookings.length,
			pending: pendingBookings.length,
			totalSpent,
			totalRefunded,
			netSpent: totalSpent - totalRefunded,
			avgBookingValue:
				completedBookings.length > 0
					? completedBookings.reduce((s, b) => s + Number(b.total_price), 0) /
						completedBookings.length
					: 0,
			memberSince: data.user_profile?.created_at ?? '',
			totalLoyaltyStamps: (data.user_profile?.loyalty_stamps ?? 0) + stampsRedeemed,
			stampsRedeemed,
			totalDiscounts,
			topServices,
			paymentMethods,
			forgivenNoShows: noShows.length,
			editRequests: edits.length,
			patchTests: patchTests.length,
			savedCards: (data.saved_cards ?? []).length,
			referredBy: data.referrals?.referred_by?.referrer_name ?? null,
			referredCount: data.referrals?.referred_users?.length ?? 0
		};
	}

	function downloadJson() {
		if (!gdprData) return;
		const blob = new Blob([JSON.stringify(gdprData, null, 2)], { type: 'application/json' });
		const url = URL.createObjectURL(blob);
		const a = document.createElement('a');
		a.href = url;
		a.download = `gdpr-export-${new Date().toLocaleDateString('en-CA', { timeZone: 'Europe/London' })}.json`;
		a.click();
		URL.revokeObjectURL(url);
	}
</script>

<svelte:head>
	<script>
		(function () {
			// Pre-hydration auth guard: reads localStorage directly because the Svelte
			// authStore hasn't initialized yet at this point (async+$state). This runs
			// synchronously before any rendering, preventing a flash of protected content.
			// The authStore handles post-hydration auth.
			try {
				var token = localStorage.getItem('authToken');
				if (!token) {
					window.location.replace('/login');
					return;
				}
				var payload = JSON.parse(atob(token.split('.')[1]));
				if (payload.exp * 1000 <= Date.now()) {
					window.location.replace('/login');
				}
			} catch (e) {
				window.location.replace('/login');
			}
		})();
	</script>
	<title>Your Personal Data — Crussell</title>
</svelte:head>

<div class="mx-auto max-w-4xl p-6">
	{#if pageState === 'loading' || pageState === 'generating'}
		<h1 class="mb-6 text-2xl font-bold">Your Personal Data Report</h1>
		<div class="mb-4 flex items-center gap-3">
			<div
				class="inline-block h-6 w-6 animate-spin rounded-full border-2 border-solid border-gray-300 border-r-transparent"
				role="status"
			>
				<span class="sr-only">Loading…</span>
			</div>
			<p class="text-sm text-gray-500">Generating report…</p>
		</div>
		<div class="space-y-4">
			{#each [1, 2, 3] as _i (_i)}
				<div class="rounded-xl border bg-card p-6">
					<Skeleton class="mb-3 h-5 w-40" />
					<div class="space-y-2">
						<Skeleton class="h-4 w-full" />
						<Skeleton class="h-4 w-3/4" />
						<Skeleton class="h-4 w-2/3" />
					</div>
				</div>
			{/each}
		</div>
	{:else if pageState === 'error'}
		<div class="flex flex-col items-center justify-center py-20">
			<h2 class="mb-2 text-xl font-bold">Something went wrong</h2>
			<p class="mb-6 text-sm text-gray-500">{errorMessage}</p>
			<div class="flex gap-3">
				<Button onclick={fetchGdprData}>Try Again</Button>
				<Button onclick={handleGotoAccount} variant="outline">Back to Account</Button>
			</div>
		</div>
	{:else if pageState === 'loaded' && gdprData}
		<div class="print-area">
			<div class="mb-6 flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
				<div>
					<button
						onclick={handleGotoAccount}
						class="mb-2 inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-900"
					>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"><path d="M19 12H5M12 19l-7-7 7-7" /></svg
						>
						Back to Account
					</button>
					<h1 class="text-2xl font-bold">Your Personal Data Report</h1>
					<p class="mt-1 text-sm text-gray-500">
						{gdprData.export_metadata?.exported_at
							? fmtDateTime(gdprData.export_metadata.exported_at)
							: 'Generated now'}
					</p>
				</div>
				<div class="no-print flex gap-2">
					<Button onclick={downloadJson} variant="outline" class="shrink-0">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="mr-2 h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
							><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline
								points="14 2 14 8 20 8"
							/><line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" /></svg
						>
						Download JSON
					</Button>
					<Button onclick={handlePrint} variant="default" class="shrink-0">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							class="mr-2 h-4 w-4"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
							><polyline points="6 9 6 2 18 2 18 9" /><path
								d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"
							/><rect x="6" y="14" width="12" height="8" /></svg
						>
						Export PDF
					</Button>
				</div>
			</div>

			<!-- Summary Stats -->
			{#if computeBookingStats(gdprData)}
				{@const stats = computeBookingStats(gdprData)!}
				<h2 class="mb-3 text-xl font-bold">Summary</h2>
				<div class="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
					<div class="rounded-xl border bg-card p-4">
						<span class="text-xs text-gray-400">Member Since</span>
						<p class="mt-1 text-lg font-semibold">{fmtDate(stats.memberSince)}</p>
					</div>
					<div class="rounded-xl border bg-card p-4">
						<span class="text-xs text-gray-400">Total Bookings</span>
						<p class="mt-1 text-lg font-semibold">{stats.totalBookings}</p>
						<p class="text-xs text-gray-400">
							{stats.completed} completed, {stats.cancelled} cancelled
							{#if stats.noShow > 0}, {stats.noShow} no-show{/if}
							{#if stats.pending > 0}, {stats.pending} pending{/if}
						</p>
					</div>
					<div class="rounded-xl border bg-card p-4">
						<span class="text-xs text-gray-400">Total Spent</span>
						<p class="mt-1 text-lg font-semibold">{fmt(stats.totalSpent)}</p>
						{#if stats.totalRefunded > 0}
							<p class="text-xs text-red-500">−{fmt(stats.totalRefunded)} refunded</p>
							<p class="text-xs text-gray-400">net {fmt(stats.netSpent)}</p>
						{/if}
					</div>
					<div class="rounded-xl border bg-card p-4">
						<span class="text-xs text-gray-400">Avg Booking</span>
						<p class="mt-1 text-lg font-semibold">{fmt(stats.avgBookingValue)}</p>
						<p class="text-xs text-gray-400">per completed booking</p>
					</div>
				</div>

				{#if stats.topServices.length > 0}
					<div class="mb-6 rounded-xl border bg-card p-4">
						<h3 class="mb-3 text-sm font-semibold text-gray-500">Most Booked Services</h3>
						<div class="space-y-2">
							{#each stats.topServices as svc (svc.name)}
								<div class="flex items-center justify-between">
									<div class="flex items-center gap-2">
										<span
											class="flex h-6 w-6 items-center justify-center rounded-full bg-fuchsia-100 text-xs font-semibold text-fuchsia-700"
										>
											{svc.count}
										</span>
										<span class="text-sm">{svc.name}</span>
									</div>
									<span class="text-sm text-gray-500">{fmt(svc.total)} total</span>
								</div>
							{/each}
						</div>
					</div>
				{/if}

				{#if stats.paymentMethods.length > 0}
					<div class="mb-6 rounded-xl border bg-card p-4">
						<h3 class="mb-3 text-sm font-semibold text-gray-500">Payment Methods</h3>
						<div class="flex flex-wrap gap-3">
							{#each stats.paymentMethods as pm (pm.method)}
								<div class="flex items-center gap-2 rounded-lg bg-gray-50 px-3 py-2">
									<span class="text-sm font-medium">{pm.method}</span>
									<span class="text-xs text-gray-400">({pm.count}×, {fmt(pm.total)})</span>
								</div>
							{/each}
						</div>
					</div>
				{/if}

				{@const secondary = computeSecondaryStats(stats, gdprData)}
				<div class="mb-6 grid grid-cols-3 gap-3">
					{#each secondary as s (s.label)}
						<div class="rounded-xl border bg-card p-4">
							<span class="text-xs text-gray-400">{s.label}</span>
							<p class="mt-1 text-lg font-semibold {s.highlight ? 'text-green-600' : ''}">
								{s.value}
							</p>
							<p class="text-xs text-gray-400">{s.subtitle}</p>
						</div>
					{/each}
				</div>

				<Separator class="mb-6" />
			{/if}

			<h2 class="mb-4 text-xl font-bold">Personal Data</h2>

			<!-- User Profile -->
			<Card.Root class="mb-4">
				<Card.Header><Card.Title>User Profile</Card.Title></Card.Header>
				<Card.Content>
					<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
						<div>
							<span class="text-xs text-gray-400">Name</span>
							<p class="text-sm font-medium">{gdprData.user_profile.full_name}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Email</span>
							<p class="text-sm">{gdprData.user_profile.email}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Phone</span>
							<p class="text-sm">{gdprData.user_profile.phone || '—'}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Date of Birth</span>
							<p class="text-sm">{fmtDate(gdprData.user_profile.date_of_birth)}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Account Role</span>
							<p class="text-sm">{gdprData.user_profile.account_role.replace(/_/g, ' ')}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Account Type</span>
							<p class="text-sm">{gdprData.user_profile.account_type}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Account Created</span>
							<p class="text-sm">{fmtDate(gdprData.user_profile.created_at)}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Last Updated</span>
							<p class="text-sm">{fmtDateTime(gdprData.user_profile.updated_at)}</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Last Login</span>
							<p class="text-sm">
								{gdprData.user_profile.last_login_at
									? fmtDateTime(gdprData.user_profile.last_login_at)
									: '—'}
							</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Loyalty Stamps</span>
							<p class="text-sm">{gdprData.user_profile.loyalty_stamps}</p>
						</div>
						{#if gdprData.user_profile.deposits_required > 0}
							<div>
								<span class="text-xs text-gray-400">Deposits Required</span>
								<p class="text-sm">{gdprData.user_profile.deposits_required}</p>
							</div>
						{/if}
						<div>
							<span class="text-xs text-gray-400">Referral Code</span>
							<p class="font-mono text-sm">{gdprData.user_profile.referral_code || '—'}</p>
						</div>
						{#if gdprData.user_profile.failed_attempts != null && gdprData.user_profile.failed_attempts > 0}
							<div>
								<span class="text-xs text-gray-400">Failed Login Attempts</span>
								<p class="text-sm">{gdprData.user_profile.failed_attempts}</p>
							</div>
						{/if}
						{#if gdprData.user_profile.locked_until}
							<div>
								<span class="text-xs text-gray-400">Account Locked Until</span>
								<p class="text-sm">{fmtDateTime(gdprData.user_profile.locked_until)}</p>
							</div>
						{/if}
						<div>
							<span class="text-xs text-gray-400">Privacy Policy Consent</span>
							<p class="text-sm">
								{gdprData.user_profile.privacy_policy_and_terms_consent
									? 'Accepted'
									: 'Declined'}{gdprData.user_profile.policy_consent_updated_at
									? ' — ' + fmtDateTime(gdprData.user_profile.policy_consent_updated_at)
									: ''}
							</p>
						</div>
						<div>
							<span class="text-xs text-gray-400">Data Retention Consent</span>
							<p class="text-sm">
								{gdprData.user_profile.data_retention_consent ? 'Accepted' : 'Declined'}{gdprData
									.user_profile.data_consent_updated_at
									? ' — ' + fmtDateTime(gdprData.user_profile.data_consent_updated_at)
									: ''}
							</p>
						</div>
					</div>
				</Card.Content>
			</Card.Root>

			<!-- Name History -->
			{#if gdprData.name_history && gdprData.name_history.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Name Change History</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Previous Name</th><th
											class="px-4 py-3 font-medium text-gray-500">Changed At</th
										><th class="px-4 py-3 font-medium text-gray-500">Booking</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.name_history as nh (nh.changed_at)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 font-medium"
												>{nh.previous_first_name} {nh.previous_last_name}</td
											>
											<td class="px-4 py-3 whitespace-nowrap">{fmtDateTime(nh.changed_at)}</td>
											<td class="px-4 py-3 font-mono text-xs text-gray-500"
												>{nh.booking_id || '—'}</td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Social Logins -->
			{#if gdprData.social_logins && gdprData.social_logins.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Connected Social Accounts</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Provider</th><th
											class="px-4 py-3 font-medium text-gray-500">Connected Since</th
										></tr
									></thead
								>
								<tbody>
									{#each gdprData.social_logins as l (l.provider + l.created_at)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 font-medium capitalize">{l.provider}</td>
											<td class="px-4 py-3 whitespace-nowrap text-gray-500"
												>{fmtDate(l.created_at)}</td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Affiliate Payouts -->
			{#if gdprData.affiliate_payouts && gdprData.affiliate_payouts.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Affiliate Payouts</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Date</th><th
											class="px-4 py-3 font-medium text-gray-500">Amount</th
										><th class="px-4 py-3 font-medium text-gray-500">Status</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.affiliate_payouts as ap (ap.id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(ap.created_at)}</td>
											<td class="px-4 py-3 font-medium whitespace-nowrap">{fmt(ap.amount)}</td>
											<td class="px-4 py-3"
												><span
													class="rounded-full px-2 py-0.5 text-xs font-medium {badge(ap.status)}"
													>{ap.status}</span
												></td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Booking Discounts -->
			{#if gdprData.booking_discounts && gdprData.booking_discounts.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Discounts Applied</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Date</th><th
											class="px-4 py-3 font-medium text-gray-500">Campaign</th
										><th class="px-4 py-3 font-medium text-gray-500">Original</th><th
											class="px-4 py-3 font-medium text-gray-500">Discount</th
										><th class="px-4 py-3 font-medium text-gray-500">Source</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.booking_discounts as d (d.id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(d.applied_at)}</td>
											<td class="px-4 py-3"
												>{d.campaign_name}{d.milestone_type
													? ' (' + d.milestone_type.replace(/_/g, ' ') + ')'
													: ''}</td
											>
											<td class="px-4 py-3 whitespace-nowrap">{fmt(d.original_total)}</td>
											<td class="px-4 py-3 text-right font-medium whitespace-nowrap text-green-600"
												>-{fmt(d.discount_amount)} ({d.discount_percent}%)</td
											>
											<td class="px-4 py-3 text-xs text-gray-500">{d.discount_source}</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Loyalty Redemptions -->
			{#if gdprData.loyalty_redemptions && gdprData.loyalty_redemptions.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Loyalty Redemptions</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Redeemed</th><th
											class="px-4 py-3 font-medium text-gray-500">Stamps</th
										><th class="px-4 py-3 font-medium text-gray-500">Status</th><th
											class="px-4 py-3 font-medium text-gray-500">Booking</th
										><th class="px-4 py-3 font-medium text-gray-500">Expires</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.loyalty_redemptions as lr (lr.id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(lr.redeemed_at)}</td>
											<td class="px-4 py-3">{lr.stamps_redeemed}</td>
											<td class="px-4 py-3"
												><span
													class="rounded-full px-2 py-0.5 text-xs font-medium {badge(lr.status)}"
													>{lr.status}</span
												></td
											>
											<td class="px-4 py-3 text-gray-500">
												{#if lr.booking_date}
													{fmtDate(lr.booking_date)}{lr.booking_services
														? ' — ' + lr.booking_services
														: ''}
												{:else}
													—
												{/if}
											</td>
											<td class="px-4 py-3 whitespace-nowrap text-gray-500"
												>{lr.expires_at ? fmtDate(lr.expires_at) : '—'}</td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Referrals -->
			{#if hasReferralData(gdprData.referrals)}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Referrals</Card.Title></Card.Header>
					<Card.Content>
						{#if gdprData.referrals.referred_by}
							<div class="mb-3">
								<span class="text-xs text-gray-400">Referred By</span>
								<p class="text-sm font-medium">
									{gdprData.referrals.referred_by.referrer_name}
									<span class="text-gray-400"
										>— {fmtDate(gdprData.referrals.referred_by.referred_at)}</span
									>
								</p>
							</div>
						{/if}
						{#if gdprData.referrals.referred_users && gdprData.referrals.referred_users.length > 0}
							<div>
								<span class="text-xs text-gray-400">People You Referred</span>
								<div class="mt-1 space-y-1">
									{#each gdprData.referrals.referred_users as ru (ru.referred_id)}
										<div class="flex items-center justify-between text-sm">
											<span class="font-medium">{ru.referred_name}</span>
											<span class="text-gray-400">{fmtDate(ru.referred_at)}</span>
										</div>
									{/each}
								</div>
							</div>
						{/if}
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Referral Discounts -->
			{#if gdprData.referral_discounts && gdprData.referral_discounts.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Referral Discounts</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Created</th><th
											class="px-4 py-3 font-medium text-gray-500">Discount</th
										><th class="px-4 py-3 font-medium text-gray-500">Status</th><th
											class="px-4 py-3 font-medium text-gray-500">Used At</th
										></tr
									></thead
								>
								<tbody>
									{#each gdprData.referral_discounts as rd (rd.id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDateTime(rd.created_at)}</td>
											<td class="px-4 py-3">{rd.discount_percent}%</td>
											<td class="px-4 py-3"
												><span
													class="rounded-full px-2 py-0.5 text-xs font-medium {rd.used
														? 'bg-green-100 text-green-700'
														: 'bg-yellow-100 text-yellow-700'}"
													>{rd.used ? 'Used' : 'Available'}</span
												></td
											>
											<td class="px-4 py-3 whitespace-nowrap"
												>{rd.used_at ? fmtDateTime(rd.used_at) : '—'}</td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Login Audit -->
			{#if gdprData.login_audit && gdprData.login_audit.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Login Activity</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Date</th><th
											class="px-4 py-3 font-medium text-gray-500">Type</th
										><th class="px-4 py-3 font-medium text-gray-500">Success</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.login_audit as la (la.created_at)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDateTime(la.created_at)}</td>
											<td class="px-4 py-3">{la.attempt_type.replace(/_/g, ' ')}</td>
											<td class="px-4 py-3">
												<span
													class="rounded-full px-2 py-0.5 text-xs font-medium {la.success
														? 'bg-green-100 text-green-700'
														: 'bg-red-100 text-red-700'}">{la.success ? 'Yes' : 'No'}</span
												>
											</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Refresh Tokens -->
			{#if gdprData.refresh_tokens && gdprData.refresh_tokens.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Session Tokens</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Issued</th><th
											class="px-4 py-3 font-medium text-gray-500">Expires</th
										><th class="px-4 py-3 font-medium text-gray-500">Status</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.refresh_tokens as rt (rt.created_at)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDateTime(rt.created_at)}</td>
											<td class="px-4 py-3 whitespace-nowrap">{fmtDateTime(rt.expires_at)}</td>
											<td class="px-4 py-3">
												<span
													class="rounded-full px-2 py-0.5 text-xs font-medium {rt.revoked
														? 'bg-gray-100 text-gray-600'
														: 'bg-green-100 text-green-700'}"
													>{rt.revoked ? 'Revoked' : 'Active'}</span
												>
											</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Patch Tests -->
			{#if gdprData.patch_tests && gdprData.patch_tests.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Patch Tests</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Test</th><th
											class="px-4 py-3 font-medium text-gray-500">Date</th
										><th class="px-4 py-3 font-medium text-gray-500">Description</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.patch_tests as t (t.patch_test_id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 font-medium">{t.name}</td>
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(t.tested_at)}</td>
											<td class="px-4 py-3 text-gray-500">{t.description || '—'}</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Saved Cards -->
			{#if gdprData.saved_cards && gdprData.saved_cards.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Saved Cards</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Card</th><th
											class="px-4 py-3 font-medium text-gray-500">Last 4</th
										><th class="px-4 py-3 font-medium text-gray-500">Expires</th><th
											class="px-4 py-3 font-medium text-gray-500">Default</th
										><th class="px-4 py-3 font-medium text-gray-500">Status</th><th
											class="px-4 py-3 font-medium text-gray-500">Retained Until</th
										><th class="px-4 py-3 font-medium text-gray-500">Added</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.saved_cards as c (c.card_id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 font-medium">{c.brand}</td>
											<td class="px-4 py-3 font-mono text-xs">•••• {c.last_4}</td>
											<td class="px-4 py-3">{String(c.exp_month).padStart(2, '0')}/{c.exp_year}</td>
											<td class="px-4 py-3">{c.is_default ? 'Yes' : 'No'}</td>
											<td class="px-4 py-3">{c.deleted_at ? 'Deleted' : 'Active'}</td>
											<td class="px-4 py-3 whitespace-nowrap text-gray-500"
												>{c.retained_until ? fmtDate(c.retained_until) : '7 years after expiry'}</td
											>
											<td class="px-4 py-3 whitespace-nowrap text-gray-500"
												>{fmtDate(c.created_at)}</td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Refunds -->
			{#if gdprData.refunds && gdprData.refunds.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Refunds</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Date</th><th
											class="px-4 py-3 font-medium text-gray-500">Amount</th
										><th class="px-4 py-3 font-medium text-gray-500">Reason</th><th
											class="px-4 py-3 font-medium text-gray-500">Booking</th
										><th class="px-4 py-3 font-medium text-gray-500">Status</th></tr
									></thead
								>
								<tbody>
									{#each gdprData.refunds as r (r.refund_id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(r.created_at)}</td>
											<td class="px-4 py-3 font-medium whitespace-nowrap">{fmt(r.amount)}</td>
											<td class="px-4 py-3">{r.reason}</td>
											<td class="px-4 py-3 font-mono text-xs text-gray-500">{r.booking_id}</td>
											<td class="px-4 py-3"
												><span
													class="rounded-full px-2 py-0.5 text-xs font-medium {badge(r.status)}"
													>{r.status}</span
												></td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Edit Requests -->
			{#if gdprData.edit_requests && gdprData.edit_requests.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Edits and Reschedules</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Updated</th><th
											class="px-4 py-3 font-medium text-gray-500">Booking</th
										><th class="px-4 py-3 font-medium text-gray-500">New Time</th><th
											class="px-4 py-3 font-medium text-gray-500">Notes</th
										></tr
									></thead
								>
								<tbody>
									{#each gdprData.edit_requests as req (req.id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(req.updated_at)}</td>
											<td class="px-4 py-3 font-mono text-xs text-gray-500">{req.booking_id}</td>
											<td class="px-4 py-3 whitespace-nowrap"
												>{req.new_start_time ? fmtDate(req.new_start_time) : '—'}</td
											>
											<td class="px-4 py-3 text-gray-500">{req.notes || '—'}</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Bookings -->
			<Card.Root class="mb-4">
				<Card.Header>
					<Card.Title
						>Booking History <span class="ml-1 text-sm font-normal text-gray-400"
							>({gdprData.bookings.length})</span
						></Card.Title
					>
				</Card.Header>
				<Card.Content>
					{#if gdprData.bookings.length === 0}
						<p class="text-sm text-gray-400">No bookings found.</p>
					{:else}
						<div class="space-y-4">
							{#each gdprData.bookings as b (b.booking_id)}
								<div class="rounded-lg border p-4">
									<div class="mb-2 flex flex-wrap items-center justify-between gap-2">
										<div>
											<p class="font-medium">{fmtDate(b.start_time)}</p>
											<p class="text-xs text-gray-400">
												{fmtDateTime(b.start_time)} · {b.booking_id}
											</p>
										</div>
										<div class="flex items-center gap-2">
											<span class="rounded-full px-2 py-0.5 text-xs font-medium {badge(b.status)}"
												>{b.status}</span
											>
											<span class="font-semibold">{fmt(b.total_price)}</span>
										</div>
									</div>
									<div class="space-y-1">
										{#each b.services as s (s.service_id)}
											<div class="flex items-center justify-between text-sm">
												<div>
													<span class="font-medium">{s.name}</span>
													{#if s.description}<span class="ml-1 text-gray-400"
															>— {s.description}</span
														>{/if}
												</div>
												<div class="flex items-center gap-3 text-xs text-gray-500">
													<span>{s.duration_minutes} min</span>
													<span class="font-medium text-gray-700">{fmt(s.price)}</span>
												</div>
											</div>
										{/each}
									</div>
									{#if b.notes}
										<div class="mt-2 border-t pt-2">
											<span class="text-xs text-gray-400">Notes</span>
											<p class="text-sm text-gray-600">{b.notes}</p>
										</div>
									{/if}
									<div class="mt-2 border-t pt-2 text-xs text-gray-400">
										Created {fmtDateTime(b.created_at)} · Updated {fmtDateTime(b.updated_at)}
									</div>
								</div>
							{/each}
						</div>
					{/if}
				</Card.Content>
			</Card.Root>

			<!-- Payments -->
			<Card.Root class="mb-4">
				<Card.Header>
					<Card.Title
						>Payment History <span class="ml-1 text-sm font-normal text-gray-400"
							>({gdprData.payments.length})</span
						></Card.Title
					>
				</Card.Header>
				<Card.Content class="p-0">
					{#if gdprData.payments.length === 0}
						<p class="p-6 text-sm text-gray-400">No payments found.</p>
					{:else}
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Date</th><th
											class="px-4 py-3 font-medium text-gray-500">Gross</th
										><th class="px-4 py-3 font-medium text-gray-500">Net</th>{#if hasVat}<th
												class="px-4 py-3 font-medium text-gray-500">VAT</th
											>{/if}<th class="px-4 py-3 font-medium text-gray-500">Method</th><th
											class="px-4 py-3 font-medium text-gray-500">Type</th
										><th class="px-4 py-3 font-medium text-gray-500">Invoice</th><th
											class="px-4 py-3 font-medium text-gray-500">Status</th
										></tr
									></thead
								>
								<tbody>
									{#each gdprData.payments as p (p.payment_id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(p.created_at)}</td>
											<td class="px-4 py-3 font-medium whitespace-nowrap">{fmt(p.amount)}</td>
											<td class="px-4 py-3 whitespace-nowrap">{fmt(p.net_amount)}</td>
											{#if hasVat}<td class="px-4 py-3 whitespace-nowrap text-gray-500"
													>{p.vat_amount ? fmt(p.vat_amount) : '—'}</td
												>{/if}
											<td class="px-4 py-3">{p.payment_method}</td>
											<td class="px-4 py-3">{p.payment_type}</td>
											<td class="px-4 py-3 font-mono text-xs text-gray-500"
												>{p.invoice_number || '—'}</td
											>
											<td class="px-4 py-3"
												><span
													class="rounded-full px-2 py-0.5 text-xs font-medium {badge(p.status)}"
													>{p.status}</span
												></td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					{/if}
				</Card.Content>
			</Card.Root>

			<!-- Verification Codes -->
			{#if gdprData.verification_codes && gdprData.verification_codes.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Verification Codes</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Purpose</th><th
											class="px-4 py-3 font-medium text-gray-500">Created</th
										><th class="px-4 py-3 font-medium text-gray-500">Used At</th><th
											class="px-4 py-3 font-medium text-gray-500">Expires</th
										></tr
									></thead
								>
								<tbody>
									{#each gdprData.verification_codes as vc (vc.purpose + vc.created_at)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 font-medium">{vc.purpose.replace(/_/g, ' ')}</td>
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(vc.created_at)}</td>
											<td class="px-4 py-3 whitespace-nowrap text-gray-500"
												>{vc.used_at ? fmtDate(vc.used_at) : '—'}</td
											>
											<td class="px-4 py-3 whitespace-nowrap text-gray-500"
												>{fmtDate(vc.expires_at)}</td
											>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Forgiven No-Shows -->
			{#if gdprData.forgiven_no_shows && gdprData.forgiven_no_shows.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Forgiven No-Shows</Card.Title></Card.Header>
					<Card.Content class="p-0">
						<div class="overflow-x-auto">
							<table class="w-full text-left text-sm">
								<thead
									><tr class="border-b"
										><th class="px-4 py-3 font-medium text-gray-500">Booking</th><th
											class="px-4 py-3 font-medium text-gray-500">Forgiven</th
										></tr
									></thead
								>
								<tbody>
									{#each gdprData.forgiven_no_shows as f (f.id)}
										<tr class="border-b last:border-b-0">
											<td class="px-4 py-3 font-mono text-xs text-gray-500">{f.booking_id}</td>
											<td class="px-4 py-3 whitespace-nowrap">{fmtDate(f.created_at)}</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Notification Preferences -->
			{#if gdprData.notification_preferences && gdprData.notification_preferences.length > 0}
				<Card.Root class="mb-4">
					<Card.Header><Card.Title>Notification Preferences</Card.Title></Card.Header>
					<Card.Content>
						{#each gdprData.notification_preferences as pref (pref.updated_at)}
							<div class="flex flex-wrap gap-4 text-sm">
								<span>Email: {pref.email_enabled ? 'Enabled' : 'Disabled'}</span>
								<span>SMS: {pref.sms_enabled ? 'Enabled' : 'Disabled'}</span>
								<span>Browser Push: {pref.browser_push_enabled ? 'Enabled' : 'Disabled'}</span>
							</div>
						{/each}
					</Card.Content>
				</Card.Root>
			{/if}

			<!-- Export Metadata -->
			{#if gdprData.export_metadata}
				<p class="text-xs text-gray-400">
					Format v{gdprData.export_metadata.format_version} · {fmtDateTime(
						gdprData.export_metadata.exported_at
					)}
				</p>
			{/if}
		</div>
	{/if}
</div>

<style>
	@media print {
		:global(body) {
			-webkit-print-color-adjust: exact;
			print-color-adjust: exact;
		}
		.no-print,
		.no-print * {
			display: none !important;
		}
		table {
			page-break-inside: auto;
		}
		tr {
			page-break-inside: avoid;
			page-break-after: auto;
		}
		thead {
			display: table-header-group;
		}
	}
</style>
