refactor: move discounts into admin panel as component, rebuild modal with proper field handling

- DiscountsManagement component integrated into admin/+page.svelte
- Removed standalone /admin/discounts route
- Modal rebuilt with toggle buttons for campaign type, conditional field groups
- Milestone unit auto-restricted based on milestone type (bookings-only for count types, months/years for anniversary)
- Mobile-first: card layout on mobile, table on desktop (md: breakpoint)
- Native select elements instead of broken bits-ui Select components
This commit is contained in:
2026-05-08 17:54:05 +01:00
parent 1f54d8565c
commit 5c4041ded9
3 changed files with 666 additions and 978 deletions
@@ -0,0 +1,622 @@
<script lang="ts">
import { authStore } from '$lib/stores/auth.svelte';
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Input } from '$lib/components/ui/input';
import * as Label from '$lib/components/ui/label';
import * as Textarea from '$lib/components/ui/textarea';
import { Skeleton } from '$lib/components/ui/skeleton';
import * as Modal from '$lib/components/ui/dialog';
import { Badge } from '$lib/components/ui/badge';
type Campaign = {
id: string;
name: string;
description: string;
campaign_type: 'time_based' | 'milestone';
discount_percent: number;
scope: string;
start_date: string;
end_date: string;
milestone_type: string;
milestone_value: number;
milestone_unit: string;
status: 'draft' | 'active' | 'completed' | 'cancelled';
max_redemptions: number;
times_redeemed: number;
created_at: string;
updated_at: string;
};
type CampaignStats = {
campaign: Campaign;
total_discount_amount: number;
booking_count: number;
};
const MILESTONE_UNIT_MAP: Record<string, string[]> = {
per_user_booking_count: ['bookings'],
global_booking_count: ['bookings'],
anniversary: ['months', 'years']
};
const MILESTONE_LABELS: Record<string, string> = {
per_user_booking_count: 'Per-user bookings',
global_booking_count: 'Global bookings',
anniversary: 'Anniversary'
};
const SCOPE_LABELS: Record<string, string> = {
all_bookings: 'All bookings',
first_booking_only: 'First booking only',
new_customers_only: 'New customers only'
};
let campaigns = $state<Campaign[]>([]);
let loading = $state(true);
let actionInProgress = $state<string | null>(null);
let showModal = $state(false);
let showStatsModal = $state(false);
let submitting = $state(false);
let statsLoading = $state(false);
let editingCampaign = $state<Campaign | null>(null);
let statsData = $state<CampaignStats | null>(null);
let form = $state({
name: '',
description: '',
campaign_type: 'time_based' as 'time_based' | 'milestone',
discount_percent: 10,
scope: 'all_bookings',
start_date: '',
end_date: '',
milestone_type: 'per_user_booking_count',
milestone_value: 0,
milestone_unit: 'bookings',
max_redemptions: 0
});
let errors = $state<Record<string, string>>({});
$effect(() => {
if (form.milestone_type in MILESTONE_UNIT_MAP) {
const allowed = MILESTONE_UNIT_MAP[form.milestone_type];
if (!allowed.includes(form.milestone_unit)) {
form.milestone_unit = allowed[0];
}
}
});
let isFormValid = $derived.by(() => {
if (!form.name.trim()) return false;
if (form.discount_percent <= 0 || form.discount_percent > 100) return false;
if (form.campaign_type === 'time_based') {
if (!form.start_date || !form.end_date) return false;
if (new Date(form.end_date) <= new Date(form.start_date)) return false;
}
if (form.campaign_type === 'milestone') {
if (form.milestone_value <= 0) return false;
}
return true;
});
async function loadCampaigns() {
loading = true;
try {
const res = await fetch('/api/admin/discount-campaigns', {
headers: { Authorization: `Bearer ${authStore.currentToken}` }
});
if (res.ok) campaigns = await res.json();
else toast.error('Failed to load campaigns');
} catch {
toast.error('Failed to load campaigns');
} finally {
loading = false;
}
}
function openCreateModal() {
editingCampaign = null;
form = {
name: '',
description: '',
campaign_type: 'time_based',
discount_percent: 10,
scope: 'all_bookings',
start_date: '',
end_date: '',
milestone_type: 'per_user_booking_count',
milestone_value: 0,
milestone_unit: 'bookings',
max_redemptions: 0
};
errors = {};
showModal = true;
}
function openEditModal(c: Campaign) {
editingCampaign = c;
form = {
name: c.name,
description: c.description || '',
campaign_type: c.campaign_type,
discount_percent: c.discount_percent,
scope: c.scope || 'all_bookings',
start_date: c.start_date ? new Date(c.start_date).toISOString().slice(0, 16) : '',
end_date: c.end_date ? new Date(c.end_date).toISOString().slice(0, 16) : '',
milestone_type: c.milestone_type || 'per_user_booking_count',
milestone_value: c.milestone_value || 0,
milestone_unit: c.milestone_unit || 'bookings',
max_redemptions: c.max_redemptions || 0
};
errors = {};
showModal = true;
}
async function submitForm() {
errors = {};
if (!form.name.trim()) errors.name = 'Required';
if (form.discount_percent <= 0) errors.discount_percent = 'Must be > 0';
if (form.discount_percent > 100) errors.discount_percent = 'Max 100';
if (form.campaign_type === 'time_based') {
if (!form.start_date) errors.start_date = 'Required';
if (!form.end_date) errors.end_date = 'Required';
if (form.start_date && form.end_date && new Date(form.end_date) <= new Date(form.start_date)) {
errors.end_date = 'Must be after start';
}
}
if (form.campaign_type === 'milestone' && form.milestone_value <= 0) {
errors.milestone_value = 'Must be > 0';
}
if (Object.keys(errors).length > 0) return;
submitting = true;
try {
const payload: Record<string, unknown> = {
name: form.name.trim(),
description: form.description.trim() || undefined,
campaign_type: form.campaign_type,
discount_percent: form.discount_percent
};
if (form.campaign_type === 'time_based') {
payload.scope = form.scope;
payload.start_date = new Date(form.start_date).toISOString();
payload.end_date = new Date(form.end_date).toISOString();
} else {
payload.milestone_type = form.milestone_type;
payload.milestone_value = form.milestone_value;
payload.milestone_unit = form.milestone_unit;
}
if (form.max_redemptions > 0) payload.max_redemptions = form.max_redemptions;
const url = editingCampaign
? `/api/admin/discount-campaigns/${editingCampaign.id}`
: '/api/admin/discount-campaigns';
const method = editingCampaign ? 'PUT' : 'POST';
const res = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify(payload)
});
if (res.ok) {
toast.success(editingCampaign ? 'Campaign updated' : 'Campaign created');
showModal = false;
await loadCampaigns();
} else {
const text = await res.text();
toast.error(text || 'Failed to save campaign');
}
} catch {
toast.error('Failed to save campaign');
} finally {
submitting = false;
}
}
async function updateStatus(c: Campaign, status: string) {
actionInProgress = c.id;
try {
const res = await fetch(`/api/admin/discount-campaigns/${c.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify({ status })
});
if (res.ok) {
toast.success(`Campaign ${status}`);
await loadCampaigns();
} else toast.error('Failed to update status');
} catch {
toast.error('Failed to update status');
} finally {
actionInProgress = null;
}
}
async function cancelCampaign(c: Campaign) {
actionInProgress = c.id;
try {
const res = await fetch(`/api/admin/discount-campaigns/${c.id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${authStore.currentToken}` }
});
if (res.ok) {
toast.success('Campaign cancelled');
await loadCampaigns();
} else toast.error('Failed to cancel campaign');
} catch {
toast.error('Failed to cancel campaign');
} finally {
actionInProgress = null;
}
}
async function viewStats(c: Campaign) {
statsLoading = true;
showStatsModal = true;
try {
const res = await fetch(`/api/admin/discount-campaigns/${c.id}/stats`, {
headers: { Authorization: `Bearer ${authStore.currentToken}` }
});
if (res.ok) statsData = await res.json();
else toast.error('Failed to load stats');
} catch {
toast.error('Failed to load stats');
} finally {
statsLoading = false;
}
}
function statusBadge(status: string) {
const map: Record<string, { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline' }> = {
draft: { label: 'Draft', variant: 'secondary' },
active: { label: 'Active', variant: 'default' },
completed: { label: 'Completed', variant: 'outline' },
cancelled: { label: 'Cancelled', variant: 'destructive' }
};
const s = map[status] || map.draft;
return `<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
s.variant === 'default' ? 'bg-emerald-100 text-emerald-800' :
s.variant === 'secondary' ? 'bg-gray-100 text-gray-800' :
s.variant === 'destructive' ? 'bg-red-100 text-red-800' :
'bg-blue-100 text-blue-800'
}">${s.label}</span>`;
}
function typeLabel(c: Campaign): string {
if (c.campaign_type === 'time_based') return 'Time-based';
return MILESTONE_LABELS[c.milestone_type] || c.milestone_type;
}
function redemptionDisplay(c: Campaign): string {
const max = c.max_redemptions > 0 ? `/${c.max_redemptions}` : '/∞';
return `${c.times_redeemed}${max}`;
}
$effect(() => {
loadCampaigns();
});
</script>
<Card.Root>
<Card.Header>
<div class="flex w-full flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<Card.Title>Discount Campaigns</Card.Title>
<Card.Description>Manage loyalty discounts, sales, and milestone campaigns</Card.Description>
</div>
<Button onclick={openCreateModal} class="w-full sm:w-auto">Create Campaign</Button>
</div>
</Card.Header>
<Card.Content>
{#if loading}
<div class="space-y-3">
{#each Array(3) as _, i (i)}
<Skeleton class="h-16 w-full" />
{/each}
</div>
{:else if campaigns.length === 0}
<div class="py-8 text-center text-sm text-gray-500">
No campaigns yet. Create one to get started.
</div>
{:else}
<!-- Desktop table -->
<div class="hidden w-full overflow-x-auto md:block">
<table class="w-full table-auto border-collapse text-sm">
<thead>
<tr class="border-b text-left text-xs text-gray-500">
<th class="py-3">Name</th>
<th class="py-3">Type</th>
<th class="py-3">Discount</th>
<th class="py-3">Status</th>
<th class="py-3">Redeemed</th>
<th class="py-3 text-right">Actions</th>
</tr>
</thead>
<tbody>
{#each campaigns as c (c.id)}
<tr class="border-b">
<td class="py-3 font-medium">{c.name}</td>
<td class="py-3 text-gray-600">{typeLabel(c)}</td>
<td class="py-3">{c.discount_percent}%</td>
<td class="py-3">{@html statusBadge(c.status)}</td>
<td class="py-3 text-gray-600">{redemptionDisplay(c)}</td>
<td class="py-3">
<div class="flex justify-end gap-1">
{#if c.status === 'draft'}
<Button size="sm" variant="outline"
disabled={actionInProgress === c.id}
onclick={() => updateStatus(c, 'active')}>
Activate
</Button>
{/if}
{#if c.status === 'active'}
<Button size="sm" variant="outline"
disabled={actionInProgress === c.id}
onclick={() => updateStatus(c, 'completed')}>
Complete
</Button>
{/if}
{#if c.status !== 'cancelled'}
<Button size="sm" variant="destructive"
disabled={actionInProgress === c.id}
onclick={() => cancelCampaign(c)}>
Cancel
</Button>
{/if}
{#if c.status === 'active' || c.status === 'completed'}
<Button size="sm" variant="ghost"
onclick={() => viewStats(c)}>
Stats
</Button>
{/if}
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<!-- Mobile cards -->
<div class="space-y-3 md:hidden">
{#each campaigns as c (c.id)}
<div class="rounded-lg border p-4">
<div class="mb-2 flex items-start justify-between">
<div class="font-medium">{c.name}</div>
{@html statusBadge(c.status)}
</div>
<div class="mb-3 grid grid-cols-2 gap-2 text-xs text-gray-600">
<div>Type: {typeLabel(c)}</div>
<div>Discount: {c.discount_percent}%</div>
<div>Redeemed: {redemptionDisplay(c)}</div>
</div>
<div class="flex flex-wrap gap-2">
{#if c.status === 'draft'}
<Button size="sm" variant="outline"
disabled={actionInProgress === c.id}
onclick={() => updateStatus(c, 'active')}>
Activate
</Button>
{/if}
{#if c.status === 'active'}
<Button size="sm" variant="outline"
disabled={actionInProgress === c.id}
onclick={() => updateStatus(c, 'completed')}>
Complete
</Button>
{/if}
{#if c.status !== 'cancelled'}
<Button size="sm" variant="destructive"
disabled={actionInProgress === c.id}
onclick={() => cancelCampaign(c)}>
Cancel
</Button>
{/if}
{#if c.status === 'active' || c.status === 'completed'}
<Button size="sm" variant="ghost"
onclick={() => viewStats(c)}>
Stats
</Button>
{/if}
</div>
</div>
{/each}
</div>
{/if}
</Card.Content>
</Card.Root>
<!-- Create/Edit Modal -->
<Modal.Root bind:open={showModal}>
<Modal.Content class="sm:max-w-lg">
<Modal.Header>
<Modal.Title>{editingCampaign ? 'Edit Campaign' : 'Create Campaign'}</Modal.Title>
<Modal.Description>Configure discount rules and campaign parameters</Modal.Description>
</Modal.Header>
<div class="space-y-4 py-4">
<!-- Name -->
<div class="space-y-2">
<Label.Root for="dc-name">Name *</Label.Root>
<Input id="dc-name" bind:value={form.name} placeholder="e.g. Easter Sale" />
{#if errors.name}<p class="text-xs text-red-500">{errors.name}</p>{/if}
</div>
<!-- Description -->
<div class="space-y-2">
<Label.Root for="dc-desc">Description</Label.Root>
<Textarea.Root id="dc-desc" bind:value={form.description} placeholder="Optional notes" rows={2} />
</div>
<!-- Campaign Type -->
<div class="space-y-2">
<Label.Root>Campaign Type *</Label.Root>
<div class="flex gap-2">
<button
type="button"
class="flex-1 rounded-md border px-3 py-2 text-sm transition-colors {form.campaign_type === 'time_based' ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'hover:bg-gray-50'}"
onclick={() => { form.campaign_type = 'time_based'; }}>
Time-based
</button>
<button
type="button"
class="flex-1 rounded-md border px-3 py-2 text-sm transition-colors {form.campaign_type === 'milestone' ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'hover:bg-gray-50'}"
onclick={() => { form.campaign_type = 'milestone'; }}>
Milestone
</button>
</div>
</div>
<!-- Discount Percent -->
<div class="space-y-2">
<Label.Root for="dc-pct">Discount Percent *</Label.Root>
<div class="flex items-center gap-2">
<Input id="dc-pct" type="number" min="1" max="100" bind:value={form.discount_percent} class="w-24" />
<span class="text-sm text-gray-500">%</span>
</div>
{#if errors.discount_percent}<p class="text-xs text-red-500">{errors.discount_percent}</p>{/if}
</div>
<!-- Time-based fields -->
{#if form.campaign_type === 'time_based'}
<div class="space-y-3 rounded-lg border p-3">
<p class="text-xs font-medium text-gray-500">TIME-BASED SETTINGS</p>
<!-- Scope -->
<div class="space-y-2">
<Label.Root for="dc-scope">Scope</Label.Root>
<select
id="dc-scope"
bind:value={form.scope}
class="flex h-9 w-full rounded-md border border-gray-300 bg-transparent px-3 py-1 text-sm shadow-sm">
<option value="all_bookings">All bookings</option>
<option value="first_booking_only">First booking only</option>
<option value="new_customers_only">New customers only</option>
</select>
</div>
<!-- Dates -->
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div class="space-y-2">
<Label.Root for="dc-start">Start Date *</Label.Root>
<Input id="dc-start" type="datetime-local" bind:value={form.start_date} />
{#if errors.start_date}<p class="text-xs text-red-500">{errors.start_date}</p>{/if}
</div>
<div class="space-y-2">
<Label.Root for="dc-end">End Date *</Label.Root>
<Input id="dc-end" type="datetime-local" bind:value={form.end_date} />
{#if errors.end_date}<p class="text-xs text-red-500">{errors.end_date}</p>{/if}
</div>
</div>
</div>
{/if}
<!-- Milestone fields -->
{#if form.campaign_type === 'milestone'}
<div class="space-y-3 rounded-lg border p-3">
<p class="text-xs font-medium text-gray-500">MILESTONE SETTINGS</p>
<!-- Milestone Type -->
<div class="space-y-2">
<Label.Root for="dc-ms-type">Milestone Type *</Label.Root>
<select
id="dc-ms-type"
bind:value={form.milestone_type}
class="flex h-9 w-full rounded-md border border-gray-300 bg-transparent px-3 py-1 text-sm shadow-sm">
<option value="per_user_booking_count">Per-user booking count</option>
<option value="global_booking_count">Global booking count</option>
<option value="anniversary">Anniversary</option>
</select>
</div>
<!-- Milestone Value + Unit -->
<div class="grid grid-cols-2 gap-3">
<div class="space-y-2">
<Label.Root for="dc-ms-val">Value *</Label.Root>
<Input id="dc-ms-val" type="number" min="1" bind:value={form.milestone_value} />
{#if errors.milestone_value}<p class="text-xs text-red-500">{errors.milestone_value}</p>{/if}
</div>
<div class="space-y-2">
<Label.Root for="dc-ms-unit">Unit</Label.Root>
{#if form.milestone_type === 'anniversary'}
<select
id="dc-ms-unit"
bind:value={form.milestone_unit}
class="flex h-9 w-full rounded-md border border-gray-300 bg-transparent px-3 py-1 text-sm shadow-sm">
<option value="months">Months</option>
<option value="years">Years</option>
</select>
{:else}
<Input id="dc-ms-unit" value="bookings" disabled class="bg-gray-50" />
{/if}
</div>
</div>
<p class="text-xs text-gray-500">
{#if form.milestone_type === 'per_user_booking_count'}
Discount applies when a user completes their {form.milestone_value}th booking
{:else if form.milestone_type === 'global_booking_count'}
Discount applies on the {form.milestone_value}th completed booking across all users
{:else}
Discount applies on a user's first booking after {form.milestone_value} {form.milestone_unit} since their first visit
{/if}
</p>
</div>
{/if}
<!-- Max Redemptions -->
<div class="space-y-2">
<Label.Root for="dc-max">Max Redemptions</Label.Root>
<Input id="dc-max" type="number" min="0" bind:value={form.max_redemptions} class="w-32" />
<p class="text-xs text-gray-500">0 = unlimited</p>
</div>
</div>
<Modal.Footer>
<Button variant="outline" onclick={() => { showModal = false; }}>Cancel</Button>
<Button onclick={submitForm} disabled={!isFormValid || submitting}>
{submitting ? 'Saving...' : (editingCampaign ? 'Update' : 'Create')}
</Button>
</Modal.Footer>
</Modal.Content>
</Modal.Root>
<!-- Stats Modal -->
<Modal.Root bind:open={showStatsModal}>
<Modal.Content class="sm:max-w-sm">
<Modal.Header>
<Modal.Title>Campaign Stats</Modal.Title>
</Modal.Header>
{#if statsLoading}
<div class="space-y-3 py-4">
<Skeleton class="h-12 w-full" />
<Skeleton class="h-12 w-full" />
</div>
{:else if statsData}
<div class="space-y-4 py-4">
<div class="rounded-lg bg-gray-50 p-4 text-center">
<p class="text-sm text-gray-500">Total Discount Given</p>
<p class="text-2xl font-bold text-emerald-600">£{statsData.total_discount_amount.toFixed(2)}</p>
</div>
<div class="rounded-lg bg-gray-50 p-4 text-center">
<p class="text-sm text-gray-500">Bookings Discounted</p>
<p class="text-2xl font-bold">{statsData.booking_count}</p>
</div>
</div>
{/if}
<Modal.Footer>
<Button onclick={() => { showStatsModal = false; }}>Close</Button>
</Modal.Footer>
</Modal.Content>
</Modal.Root>
+44
View File
@@ -11,6 +11,7 @@
import HolidayHours from '$lib/components/admin/HolidayHours.svelte'; import HolidayHours from '$lib/components/admin/HolidayHours.svelte';
import WeeklySchedule from '$lib/components/admin/WeeklySchedule.svelte'; import WeeklySchedule from '$lib/components/admin/WeeklySchedule.svelte';
import ServicesManagement from '$lib/components/admin/ServicesManagement.svelte'; import ServicesManagement from '$lib/components/admin/ServicesManagement.svelte';
import DiscountsManagement from '$lib/components/admin/DiscountsManagement.svelte';
import UserModal from '$lib/components/admin/UserModal.svelte'; import UserModal from '$lib/components/admin/UserModal.svelte';
import BookingModal from '$lib/components/admin/BookingModal.svelte'; import BookingModal from '$lib/components/admin/BookingModal.svelte';
@@ -209,6 +210,48 @@
</table> </table>
</div> </div>
</div> </div>
<!-- Discounts Management Card Skeleton -->
<div class="rounded-lg border p-6">
<div class="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div class="space-y-2">
<Skeleton class="h-6 w-40" />
<Skeleton class="h-4 w-64" />
</div>
<Skeleton class="h-10 w-32" />
</div>
<div class="mt-4 hidden w-full overflow-x-auto md:block">
<table class="w-full table-auto border-collapse text-sm">
<thead>
<tr class="border-b text-left text-xs text-gray-500">
<th class="py-3"><Skeleton class="h-4 w-24" /></th>
<th class="py-3"><Skeleton class="h-4 w-20" /></th>
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
<th class="py-3"><Skeleton class="h-4 w-40" /></th>
</tr>
</thead>
<tbody>
{#each Array(2) as _, i (i)}
<tr class="border-b">
<td class="py-3"><Skeleton class="h-4 w-32" /></td>
<td class="py-3"><Skeleton class="h-4 w-24" /></td>
<td class="py-3"><Skeleton class="h-4 w-12" /></td>
<td class="py-3"><Skeleton class="h-4 w-16" /></td>
<td class="py-3"><Skeleton class="h-4 w-12" /></td>
<td class="py-3">
<div class="flex justify-end gap-2">
<Skeleton class="h-8 w-16" />
<Skeleton class="h-8 w-16" />
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
</div> </div>
{:else if pageState === 'authorized'} {:else if pageState === 'authorized'}
<div class="mx-auto max-w-6xl space-y-6 p-6"> <div class="mx-auto max-w-6xl space-y-6 p-6">
@@ -227,6 +270,7 @@
<HolidayHours /> <HolidayHours />
<WeeklySchedule /> <WeeklySchedule />
<ServicesManagement /> <ServicesManagement />
<DiscountsManagement />
</div> </div>
<!-- Modals --> <!-- Modals -->
@@ -1,978 +0,0 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { authStore } from '$lib/stores/auth.svelte';
import { browser } from '$app/environment';
import { toast } from 'svelte-sonner';
// UI Components
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Input } from '$lib/components/ui/input';
import * as Label from '$lib/components/ui/label';
import * as Textarea from '$lib/components/ui/textarea';
import { Skeleton } from '$lib/components/ui/skeleton';
import * as Modal from '$lib/components/ui/dialog';
import * as Select from '$lib/components/ui/select';
// Types from booking.ts
import type {
DiscountCampaign,
CampaignStats,
CampaignType,
MilestoneType,
MilestoneUnit,
DiscountCampaignScope,
DiscountCampaignStatus
} from '$lib/types/booking';
// =============== Auth & Permissions ===============
let pageState = $state<'loading' | 'authorized' | 'unauthorized'>('loading');
$effect(() => {
if (!browser) return;
if (authStore.isLoading) {
pageState = 'loading';
return;
}
if (!authStore.isAuthenticated) {
pageState = 'unauthorized';
goto('/login', { replaceState: true });
return;
}
if (authStore.currentUser?.role !== 'admin') {
pageState = 'unauthorized';
goto('/', { replaceState: true });
return;
}
pageState = 'authorized';
});
// =============== State ===============
let campaigns = $state<DiscountCampaign[]>([]);
let campaignsLoading = $state(true);
let campaignActionInProgress = $state<string | null>(null);
// Create Modal State
let showCreateModal = $state(false);
let creatingCampaign = $state(false);
let newCampaign = $state({
name: '',
description: '',
campaign_type: 'time_based' as CampaignType,
discount_percent: 10,
scope: 'all_bookings' as DiscountCampaignScope,
start_date: '',
end_date: '',
milestone_type: 'per_user_booking_count' as MilestoneType,
milestone_value: 0,
milestone_unit: 'bookings' as MilestoneUnit,
max_redemptions: 0
});
let formErrors = $state<Record<string, string>>({});
// Stats Modal State
let showStatsModal = $state(false);
let selectedCampaign = $state<DiscountCampaign | null>(null);
let campaignStats = $state<CampaignStats | null>(null);
let statsLoading = $state(false);
// =============== Validations ===============
function validateName(name: string): string {
if (!name.trim()) return 'Campaign name is required';
if (name.length > 100) return 'Name must be 100 characters or less';
return '';
}
function validateDiscount(percent: number): string {
if (isNaN(percent)) return 'Discount must be a valid number';
if (percent <= 0) return 'Discount must be greater than 0';
if (percent > 100) return 'Discount must be 100 or less';
return '';
}
function validateDates(start: string, end: string): string {
if (!start) return 'Start date is required';
if (!end) return 'End date is required';
const startTime = new Date(start).getTime();
const endTime = new Date(end).getTime();
if (isNaN(startTime)) return 'Invalid start date format';
if (isNaN(endTime)) return 'Invalid end date format';
if (endTime <= startTime) return 'End date must be after start date';
return '';
}
function validateMilestone(value: number, type: MilestoneType | undefined): string {
if (type === undefined) return '';
if (value <= 0) return 'Milestone value must be greater than 0';
return '';
}
let isFormValid = $derived.by(() => {
const nameError = validateName(newCampaign.name);
const discountError = validateDiscount(newCampaign.discount_percent);
if (nameError || discountError) return false;
if (newCampaign.campaign_type === 'time_based') {
const dateError = validateDates(newCampaign.start_date, newCampaign.end_date);
if (dateError) return false;
}
if (newCampaign.campaign_type === 'milestone') {
const milestoneError = validateMilestone(newCampaign.milestone_value, newCampaign.milestone_type);
if (milestoneError) return false;
}
return true;
});
// =============== API Functions ===============
async function fetchCampaigns() {
campaignsLoading = true;
try {
const response = await fetch('/api/admin/discount-campaigns', {
headers: {
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (response.ok) {
const data = await response.json();
campaigns = data;
} else {
toast.error('Failed to load campaigns');
}
} catch (err) {
console.error('Error fetching campaigns:', err);
toast.error('Network error loading campaigns');
} finally {
campaignsLoading = false;
}
}
async function activateCampaign(campaignId: string) {
campaignActionInProgress = campaignId;
try {
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify({ status: 'active' })
});
if (response.ok) {
toast.success('Campaign activated');
await fetchCampaigns();
} else {
const errorText = await response.text();
toast.error(`Failed to activate: ${errorText}`);
}
} catch (err) {
console.error('Error activating campaign:', err);
toast.error('Network error');
} finally {
campaignActionInProgress = null;
}
}
async function completeCampaign(campaignId: string) {
campaignActionInProgress = campaignId;
try {
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify({ status: 'completed' })
});
if (response.ok) {
toast.success('Campaign completed');
await fetchCampaigns();
} else {
const errorText = await response.text();
toast.error(`Failed to complete: ${errorText}`);
}
} catch (err) {
console.error('Error completing campaign:', err);
toast.error('Network error');
} finally {
campaignActionInProgress = null;
}
}
async function cancelCampaign(campaignId: string) {
if (!confirm('Are you sure you want to cancel this campaign? This action cannot be undone.')) {
return;
}
campaignActionInProgress = campaignId;
try {
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (response.ok) {
toast.success('Campaign cancelled');
await fetchCampaigns();
} else {
const errorText = await response.text();
toast.error(`Failed to cancel: ${errorText}`);
}
} catch (err) {
console.error('Error cancelling campaign:', err);
toast.error('Network error');
} finally {
campaignActionInProgress = null;
}
}
async function fetchCampaignStats(campaignId: string) {
statsLoading = true;
try {
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}/stats`, {
headers: {
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (response.ok) {
campaignStats = await response.json();
} else {
toast.error('Failed to load campaign stats');
}
} catch (err) {
console.error('Error fetching stats:', err);
toast.error('Network error loading stats');
} finally {
statsLoading = false;
}
}
async function createCampaign() {
// Validate
const nameError = validateName(newCampaign.name);
const discountError = validateDiscount(newCampaign.discount_percent);
if (nameError || discountError) {
toast.error('Please fix validation errors');
return;
}
creatingCampaign = true;
const loadingToast = toast.loading('Creating campaign...');
try {
const payload: Record<string, unknown> = {
name: newCampaign.name.trim(),
description: newCampaign.description.trim() || undefined,
campaign_type: newCampaign.campaign_type,
discount_percent: newCampaign.discount_percent
};
if (newCampaign.campaign_type === 'time_based') {
payload.scope = newCampaign.scope;
payload.start_date = new Date(newCampaign.start_date).toISOString();
payload.end_date = new Date(newCampaign.end_date).toISOString();
} else if (newCampaign.campaign_type === 'milestone') {
payload.milestone_type = newCampaign.milestone_type;
payload.milestone_value = newCampaign.milestone_value;
payload.milestone_unit = newCampaign.milestone_unit;
}
if (newCampaign.max_redemptions > 0) {
payload.max_redemptions = newCampaign.max_redemptions;
}
const response = await fetch('/api/admin/discount-campaigns', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify(payload)
});
if (response.ok) {
toast.success('Campaign created successfully!', { id: loadingToast });
resetForm();
showCreateModal = false;
await fetchCampaigns();
} else if (response.status === 400) {
const errorText = await response.text();
toast.error(`Validation error: ${errorText}`, { id: loadingToast });
} else {
const errorText = await response.text();
toast.error(`Failed to create: ${errorText}`, { id: loadingToast });
}
} catch (err) {
console.error('Error creating campaign:', err);
toast.error('Network error', { id: loadingToast });
} finally {
creatingCampaign = false;
}
}
function resetForm() {
newCampaign = {
name: '',
description: '',
campaign_type: 'time_based',
discount_percent: 10,
scope: 'all_bookings',
start_date: '',
end_date: '',
milestone_type: 'per_user_booking_count',
milestone_value: 0,
milestone_unit: 'bookings',
max_redemptions: 0
};
formErrors = {};
}
function openCreateModal() {
resetForm();
showCreateModal = true;
}
async function openStatsModal(campaign: DiscountCampaign) {
selectedCampaign = campaign;
campaignStats = null;
showStatsModal = true;
await fetchCampaignStats(campaign.id);
}
// =============== Helpers ===============
function getStatusBadgeVariant(status: DiscountCampaignStatus): 'default' | 'secondary' | 'destructive' | 'outline' {
switch (status) {
case 'draft':
return 'secondary';
case 'active':
return 'default';
case 'completed':
return 'outline';
case 'cancelled':
return 'destructive';
default:
return 'secondary';
}
}
function getCampaignTypeLabel(type: CampaignType, milestoneType?: MilestoneType): string {
if (type === 'time_based') return 'Time-based';
if (type === 'milestone') {
switch (milestoneType) {
case 'per_user_booking_count':
return 'Milestone: Per-user';
case 'global_booking_count':
return 'Milestone: Global';
case 'anniversary':
return 'Milestone: Anniversary';
default:
return 'Milestone';
}
}
return type;
}
// =============== Lifecycle ===============
$effect(() => {
if (pageState === 'authorized') {
fetchCampaigns();
}
});
</script>
{#if pageState === 'loading'}
<!-- Loading Skeleton -->
<div class="mx-auto max-w-6xl space-y-6 p-6">
<div class="mb-8 flex items-center justify-between">
<div class="space-y-2">
<Skeleton class="h-8 w-64" />
<Skeleton class="h-4 w-96" />
</div>
<Skeleton class="h-10 w-40" />
</div>
<Card.Root>
<Card.Header>
<Skeleton class="h-6 w-48" />
</Card.Header>
<Card.Content>
<table class="w-full table-auto">
<thead>
<tr class="border-b text-left text-xs text-gray-500">
<th class="py-3"><Skeleton class="h-4 w-24" /></th>
<th class="py-3"><Skeleton class="h-4 w-20" /></th>
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
<th class="py-3"><Skeleton class="h-4 w-24" /></th>
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
</tr>
</thead>
<tbody>
{#each Array(3) as _, i (i)}
<tr class="border-b">
<td class="py-3"><Skeleton class="h-4 w-32" /></td>
<td class="py-3"><Skeleton class="h-5 w-20" /></td>
<td class="py-3"><Skeleton class="h-4 w-12" /></td>
<td class="py-3"><Skeleton class="h-5 w-16" /></td>
<td class="py-3"><Skeleton class="h-4 w-8" /></td>
<td class="py-3">
<div class="flex gap-2">
<Skeleton class="h-8 w-20" />
<Skeleton class="h-8 w-16" />
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</Card.Content>
</Card.Root>
</div>
{:else if pageState === 'authorized'}
<div class="mx-auto max-w-6xl space-y-6 p-6">
<!-- Header -->
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold">Discount Campaigns</h1>
<p class="text-gray-600">Create and manage discount campaigns for your customers</p>
</div>
<Button onclick={openCreateModal}>
<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"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
Create Campaign
</Button>
</div>
<!-- Campaigns List -->
<Card.Root>
<Card.Header>
<Card.Title>All Campaigns</Card.Title>
<Card.Description>View and manage your discount campaigns</Card.Description>
</Card.Header>
<Card.Content>
<!-- Desktop Table -->
<div class="hidden w-full overflow-x-auto md:block">
<table class="w-full table-auto border-collapse text-sm">
<thead>
<tr class="border-b text-left text-xs text-gray-500">
<th class="w-[25%] py-3 font-medium">Name</th>
<th class="w-[15%] py-3 font-medium">Type</th>
<th class="w-[10%] py-3 text-right font-medium">Discount</th>
<th class="w-[12%] py-3 text-center font-medium">Status</th>
<th class="w-[12%] py-3 text-center font-medium">Redeemed</th>
<th class="w-[26%] py-3 text-center font-medium">Actions</th>
</tr>
</thead>
<tbody>
{#if campaignsLoading}
{#each Array(3) as _, i (i)}
<tr class="border-b">
<td class="py-3"><Skeleton class="h-4 w-32" /></td>
<td class="py-3"><Skeleton class="h-5 w-20" /></td>
<td class="py-3 text-right"><Skeleton class="ml-auto h-4 w-12" /></td>
<td class="py-3 text-center"><Skeleton class="mx-auto h-5 w-16" /></td>
<td class="py-3 text-center"><Skeleton class="mx-auto h-4 w-8" /></td>
<td class="py-3">
<div class="flex justify-center gap-2">
<Skeleton class="h-8 w-20" />
<Skeleton class="h-8 w-16" />
</div>
</td>
</tr>
{/each}
{:else}
{#each campaigns as campaign (campaign.id)}
<tr class="border-b hover:bg-gray-50">
<td class="py-3">
<div class="font-medium">{campaign.name}</div>
{#if campaign.description}
<div class="text-xs text-gray-500 line-clamp-1">{campaign.description}</div>
{/if}
</td>
<td class="py-3">
<span
class="inline-flex items-center rounded-full bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800"
>
{getCampaignTypeLabel(
campaign.campaign_type,
campaign.milestone_type as MilestoneType
)}
</span>
</td>
<td class="py-3 text-right font-medium">{campaign.discount_percent}%</td>
<td class="py-3 text-center">
<span
class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {getStatusBadgeVariant(
campaign.status
) === 'default'
? 'bg-emerald-100 text-emerald-800'
: getStatusBadgeVariant(campaign.status) === 'secondary'
? 'bg-gray-100 text-gray-800'
: getStatusBadgeVariant(campaign.status) === 'destructive'
? 'bg-red-100 text-red-800'
: 'bg-blue-100 text-blue-800'}"
>
{campaign.status}
</span>
</td>
<td class="py-3 text-center">
{campaign.times_redeemed}
{campaign.max_redemptions ? `/${campaign.max_redemptions}` : '/∞'}
</td>
<td class="py-3">
<div class="flex justify-center gap-2">
{#if campaign.status === 'draft'}
<Button
variant="outline"
size="sm"
onclick={() => activateCampaign(campaign.id)}
disabled={campaignActionInProgress === campaign.id}
>
{campaignActionInProgress === campaign.id
? '...'
: 'Activate'}
</Button>
{:else if campaign.status === 'active'}
<Button
variant="outline"
size="sm"
onclick={() => completeCampaign(campaign.id)}
disabled={campaignActionInProgress === campaign.id}
>
{campaignActionInProgress === campaign.id
? '...'
: 'Complete'}
</Button>
{:else}
<Button
variant="outline"
size="sm"
disabled
class="opacity-50"
>
{campaign.status}
</Button>
{/if}
<Button
variant="outline"
size="sm"
onclick={() => openStatsModal(campaign)}
>
Stats
</Button>
{#if campaign.status !== 'cancelled'}
<Button
variant="destructive"
size="sm"
onclick={() => cancelCampaign(campaign.id)}
disabled={campaignActionInProgress === campaign.id}
>
Cancel
</Button>
{/if}
</div>
</td>
</tr>
{/each}
{/if}
</tbody>
</table>
</div>
<!-- Mobile Cards -->
<div class="space-y-4 md:hidden">
{#if campaignsLoading}
{#each Array(3) as _, i (i)}
<div class="rounded-lg border p-4">
<div class="space-y-3">
<Skeleton class="h-5 w-32" />
<Skeleton class="h-4 w-48" />
<div class="flex gap-2">
<Skeleton class="h-8 w-16" />
<Skeleton class="h-8 w-16" />
</div>
</div>
</div>
{/each}
{:else}
{#each campaigns as campaign (campaign.id)}
<div class="rounded-lg border p-4 hover:bg-gray-50">
<div class="space-y-3">
<div class="flex items-start justify-between">
<div>
<h3 class="font-medium">{campaign.name}</h3>
{#if campaign.description}
<p class="text-sm text-gray-500">{campaign.description}</p>
{/if}
</div>
<span
class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {getStatusBadgeVariant(
campaign.status
) === 'default'
? 'bg-emerald-100 text-emerald-800'
: getStatusBadgeVariant(campaign.status) === 'secondary'
? 'bg-gray-100 text-gray-800'
: getStatusBadgeVariant(campaign.status) === 'destructive'
? 'bg-red-100 text-red-800'
: 'bg-blue-100 text-blue-800'}"
>
{campaign.status}
</span>
</div>
<div class="flex flex-wrap gap-2 text-sm">
<span class="font-medium">{campaign.discount_percent}% off</span>
<span class="text-gray-500">•</span>
<span class="text-gray-600">
{getCampaignTypeLabel(
campaign.campaign_type,
campaign.milestone_type as MilestoneType
)}
</span>
<span class="text-gray-500">•</span>
<span class="text-gray-600">
{campaign.times_redeemed}
{campaign.max_redemptions ? `/${campaign.max_redemptions}` : '/∞'}
redeemed
</span>
</div>
<div class="flex flex-wrap gap-2 pt-2">
{#if campaign.status === 'draft'}
<Button
variant="outline"
size="sm"
onclick={() => activateCampaign(campaign.id)}
disabled={campaignActionInProgress === campaign.id}
class="flex-1"
>
{campaignActionInProgress === campaign.id ? '...' : 'Activate'}
</Button>
{:else if campaign.status === 'active'}
<Button
variant="outline"
size="sm"
onclick={() => completeCampaign(campaign.id)}
disabled={campaignActionInProgress === campaign.id}
class="flex-1"
>
{campaignActionInProgress === campaign.id ? '...' : 'Complete'}
</Button>
{/if}
<Button
variant="outline"
size="sm"
onclick={() => openStatsModal(campaign)}
class="flex-1"
>
Stats
</Button>
{#if campaign.status !== 'cancelled'}
<Button
variant="destructive"
size="sm"
onclick={() => cancelCampaign(campaign.id)}
disabled={campaignActionInProgress === campaign.id}
class="flex-1"
>
Cancel
</Button>
{/if}
</div>
</div>
</div>
{/each}
{/if}
</div>
{#if !campaignsLoading && campaigns.length === 0}
<div class="py-8 text-center text-gray-500">
No campaigns found. Click "Create Campaign" to create your first campaign.
</div>
{/if}
</Card.Content>
</Card.Root>
</div>
<!-- Create Campaign Modal -->
<Modal.Root bind:open={showCreateModal}>
<Modal.Content class="max-h-[90vh] max-w-sm overflow-y-auto md:max-w-lg">
<Modal.Header>
<Modal.Title class="text-lg font-semibold">Create Campaign</Modal.Title>
<Modal.Description>Create a new discount campaign for your customers.</Modal.Description>
</Modal.Header>
<div class="space-y-4 px-4 pb-4">
<!-- Campaign Name -->
<div class="space-y-2">
<Label.Root for="campaign-name">Campaign Name *</Label.Root>
<Input
id="campaign-name"
type="text"
maxlength={100}
placeholder="e.g., Summer Sale, New Year Discount"
bind:value={newCampaign.name}
/>
{#if formErrors.name}
<p class="text-sm text-red-600">{formErrors.name}</p>
{/if}
</div>
<!-- Description -->
<div class="space-y-2">
<Label.Root for="milestone-unit">Milestone Unit</Label.Root>
<Select.Root type="single" value={newCampaign.milestone_unit} onValueChange={(v: string) => { newCampaign.milestone_unit = v as MilestoneUnit; }}>
<Select.Trigger id="milestone-unit" disabled />
<Select.Content>
<Select.Item value="bookings">Bookings</Select.Item>
<Select.Item value="months">Months</Select.Item>
<Select.Item value="years">Years</Select.Item>
</Select.Content>
</Select.Root>
</div>
<!-- Campaign Type -->
<div class="space-y-2">
<Label.Root for="campaign-type">Campaign Type *</Label.Root>
<Select.Root type="single" value={newCampaign.campaign_type} onValueChange={(v: string) => { newCampaign.campaign_type = v as CampaignType; }}>
<Select.Trigger id="campaign-type" />
<Select.Content>
<Select.Item value="time_based">Time-based</Select.Item>
<Select.Item value="milestone">Milestone</Select.Item>
</Select.Content>
</Select.Root>
</div>
<!-- Discount Percent -->
<div class="space-y-2">
<Label.Root for="discount-percent">Discount Percent *</Label.Root>
<Input
id="discount-percent"
type="number"
min="1"
max="100"
bind:value={newCampaign.discount_percent}
/>
<p class="text-xs text-gray-500">Percentage off the booking total</p>
</div>
<!-- Conditional Fields: Time-based -->
{#if newCampaign.campaign_type === 'time_based'}
<!-- Scope -->
<div class="space-y-2">
<Label.Root for="scope">Scope</Label.Root>
<Select.Root type="single" value={newCampaign.scope} onValueChange={(v: string) => { newCampaign.scope = v as DiscountCampaignScope; }}>
<Select.Trigger id="scope" />
<Select.Content>
<Select.Item value="all_bookings">All bookings</Select.Item>
<Select.Item value="first_booking_only">First booking only</Select.Item>
<Select.Item value="new_customers_only">New customers only</Select.Item>
</Select.Content>
</Select.Root>
</div>
<!-- Start Date -->
<div class="space-y-2">
<Label.Root for="start-date">Start Date *</Label.Root>
<Input
id="start-date"
type="datetime-local"
bind:value={newCampaign.start_date}
/>
</div>
<!-- End Date -->
<div class="space-y-2">
<Label.Root for="end-date">End Date *</Label.Root>
<Input
id="end-date"
type="datetime-local"
bind:value={newCampaign.end_date}
/>
</div>
{/if}
<!-- Conditional Fields: Milestone -->
{#if newCampaign.campaign_type === 'milestone'}
<!-- Milestone Type -->
<div class="space-y-2">
<Label.Root for="milestone-type">Milestone Type *</Label.Root>
<Select.Root type="single" value={newCampaign.milestone_type} onValueChange={(v: string) => {
newCampaign.milestone_type = v as MilestoneType;
if (v === 'anniversary') {
newCampaign.milestone_unit = 'years';
} else if (v === 'global_booking_count') {
newCampaign.milestone_unit = 'bookings';
} else {
newCampaign.milestone_unit = 'bookings';
}
}}>
<Select.Trigger id="milestone-type" />
<Select.Content>
<Select.Item value="per_user_booking_count"
>Per-user booking count</Select.Item
>
<Select.Item value="global_booking_count">Global booking count</Select.Item>
<Select.Item value="anniversary">Anniversary</Select.Item>
</Select.Content>
</Select.Root>
</div>
<!-- Milestone Value -->
<div class="space-y-2">
<Label.Root for="milestone-value">Milestone Value *</Label.Root>
<Input
id="milestone-value"
type="number"
min="1"
bind:value={newCampaign.milestone_value}
/>
</div>
<!-- Milestone Unit -->
<div class="space-y-2">
<Label.Root for="milestone-unit">Milestone Unit</Label.Root>
<Select.Root type="single" value={newCampaign.milestone_unit} onValueChange={(v: string) => { newCampaign.milestone_unit = v as MilestoneUnit; }}>
<Select.Trigger id="milestone-unit" disabled />
<Select.Content>
<Select.Item value="bookings">Bookings</Select.Item>
<Select.Item value="months">Months</Select.Item>
<Select.Item value="years">Years</Select.Item>
</Select.Content>
</Select.Root>
</div>
{/if}
<!-- Max Redemptions -->
<div class="space-y-2">
<Label.Root for="max-redemptions">Max Redemptions</Label.Root>
<Input
id="max-redemptions"
type="number"
min="0"
bind:value={newCampaign.max_redemptions}
/>
<p class="text-xs text-gray-500">Leave at 0 for unlimited</p>
</div>
</div>
<Modal.Footer class="flex items-center justify-end gap-2">
<Button
variant="outline"
onclick={() => {
showCreateModal = false;
resetForm();
}}
disabled={creatingCampaign}
>
Cancel
</Button>
<Button onclick={createCampaign} disabled={creatingCampaign || !isFormValid}>
{creatingCampaign ? 'Creating...' : 'Create Campaign'}
</Button>
</Modal.Footer>
</Modal.Content>
</Modal.Root>
<!-- Stats Modal -->
<Modal.Root bind:open={showStatsModal}>
<Modal.Content class="max-h-[90vh] max-w-sm overflow-y-auto md:max-w-lg">
<Modal.Header>
<Modal.Title class="text-lg font-semibold">
Campaign Stats
</Modal.Title>
<Modal.Description>
{selectedCampaign?.name || 'Campaign'} statistics
</Modal.Description>
</Modal.Header>
<div class="space-y-4 px-4 pb-4">
{#if statsLoading}
<div class="space-y-4">
<Skeleton class="h-20 w-full" />
<Skeleton class="h-20 w-full" />
</div>
{:else if campaignStats}
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<!-- Total Discount Amount -->
<div class="rounded-lg border p-4">
<div class="text-sm text-gray-500">Total Discount Given</div>
<div class="text-2xl font-bold">
£{campaignStats.total_discount_amount.toFixed(2)}
</div>
</div>
<!-- Bookings Discounted -->
<div class="rounded-lg border p-4">
<div class="text-sm text-gray-500">Bookings Discounted</div>
<div class="text-2xl font-bold">
{campaignStats.booking_count}
</div>
</div>
</div>
<!-- Campaign Details -->
<div class="rounded-lg border p-4">
<div class="text-sm font-medium">Campaign Details</div>
<div class="mt-2 space-y-1 text-sm">
<div class="flex justify-between">
<span class="text-gray-500">Discount:</span>
<span class="font-medium">
{campaignStats.campaign.discount_percent}%
</span>
</div>
<div class="flex justify-between">
<span class="text-gray-500">Status:</span>
<span class="font-medium capitalize">
{campaignStats.campaign.status}
</span>
</div>
<div class="flex justify-between">
<span class="text-gray-500">Redeemed:</span>
<span class="font-medium">
{campaignStats.campaign.times_redeemed}
{campaignStats.campaign.max_redemptions
? `/${campaignStats.campaign.max_redemptions}`
: '/∞'}
</span>
</div>
</div>
</div>
{:else}
<div class="py-8 text-center text-gray-500">
No stats available for this campaign.
</div>
{/if}
</div>
<Modal.Footer class="flex items-center justify-end gap-2">
<Button variant="outline" onclick={() => (showStatsModal = false)}>
Close
</Button>
</Modal.Footer>
</Modal.Content>
</Modal.Root>
{/if}