<script lang="ts">
	import {
		Settings,
		Users,
		CreditCard,
		Calendar,
		FileText,
		Plus,
		Trash2,
		X,
		Mail,
		HardDrive,
		Cog,
		Eye,
		EyeOff,
		TestTube2,
		Loader2,
		CheckCircle,
		XCircle,
		Inbox,
		RefreshCw,
		Key,
		Copy,
		Power,
		PowerOff
	} from 'lucide-svelte';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';

	let { data, form } = $props();
	const { membershipStatuses, membershipTypes, eventTypes, documentCategories, settings, emailTemplates } = data;

	type Tab = 'membership' | 'dues' | 'events' | 'documents' | 'email' | 'poste' | 'storage' | 'system';
	let activeTab = $state<Tab>('membership');

	let showAddStatusModal = $state(false);
	let showAddTypeModal = $state(false);
	let showAddEventTypeModal = $state(false);
	let showAddCategoryModal = $state(false);
	let isSubmitting = $state(false);

	// Poste mail server states
	let testingPoste = $state(false);
	let posteTestResult = $state<{ success: boolean; message: string } | null>(null);
	let loadingMailboxes = $state(false);
	let mailboxes = $state<Array<{ address: string; name: string; disabled: boolean; super_admin: boolean }>>([]);
	let showCreateMailboxModal = $state(false);
	let showPostePassword = $state(false);
	let generatedPassword = $state<string | null>(null);
	let creatingMailbox = $state(false);

	// Password visibility toggles
	let showSmtpPassword = $state(false);
	let showS3SecretKey = $state(false);

	// Connection test states
	let testingSmtp = $state(false);
	let testingS3 = $state(false);
	let smtpTestResult = $state<{ success: boolean; message: string } | null>(null);
	let s3TestResult = $state<{ success: boolean; message: string } | null>(null);

	// Email template testing
	let testingTemplate = $state<string | null>(null);
	let templateTestResult = $state<{ success: boolean; message: string } | null>(null);

	// Group templates by category
	const templatesByCategory = $derived(
		(emailTemplates || []).reduce((acc: Record<string, Array<{ template_key: string; template_name: string; category: string }>>, t) => {
			const cat = t.category || 'other';
			if (!acc[cat]) acc[cat] = [];
			acc[cat].push(t);
			return acc;
		}, {} as Record<string, Array<{ template_key: string; template_name: string; category: string }>>)
	);

	const tabs: Array<{ id: Tab; label: string; icon: any }> = [
		{ id: 'membership', label: 'Membership', icon: Users },
		{ id: 'dues', label: 'Dues', icon: CreditCard },
		{ id: 'events', label: 'Events', icon: Calendar },
		{ id: 'documents', label: 'Documents', icon: FileText },
		{ id: 'email', label: 'Email', icon: Mail },
		{ id: 'poste', label: 'Email Accounts', icon: Inbox },
		{ id: 'storage', label: 'Storage', icon: HardDrive },
		{ id: 'system', label: 'System', icon: Cog }
	];

	// Load mailboxes function
	async function loadMailboxes() {
		loadingMailboxes = true;
		try {
			const formData = new FormData();
			const response = await fetch('?/listMailboxes', { method: 'POST', body: formData });
			const result = await response.json();
			if (result.type === 'success' && result.data?.mailboxes) {
				mailboxes = result.data.mailboxes;
			}
		} catch (error) {
			console.error('Failed to load mailboxes:', error);
		} finally {
			loadingMailboxes = false;
		}
	}

	// Copy password to clipboard
	async function copyPassword(password: string) {
		try {
			await navigator.clipboard.writeText(password);
		} catch (error) {
			console.error('Failed to copy password:', error);
		}
	}

	// Helper to get setting value with fallback
	function getSetting(category: string, key: string, defaultValue: string = ''): string {
		const value = settings[category]?.[key];
		if (value === undefined || value === null) return defaultValue;
		// Remove quotes if it's a JSON string
		if (typeof value === 'string') {
			return value.replace(/^"|"$/g, '');
		}
		return String(value);
	}

	function getBoolSetting(category: string, key: string, defaultValue: boolean = false): boolean {
		const value = settings[category]?.[key];
		if (value === undefined || value === null) return defaultValue;
		return value === true || value === 'true';
	}
</script>

<svelte:head>
	<title>Settings | Monaco USA Admin</title>
</svelte:head>

<div class="space-y-6">
	<div>
		<h1 class="text-2xl font-bold text-slate-900">Settings</h1>
		<p class="text-slate-500">Configure membership types, dues, events, and more</p>
	</div>

	{#if form?.error}
		<div class="rounded-lg bg-red-50 p-4 text-sm text-red-600">
			{form.error}
		</div>
	{/if}

	{#if form?.success}
		<div class="rounded-lg bg-green-50 p-4 text-sm text-green-600">
			{form.success}
		</div>
	{/if}

	<!-- Tabs -->
	<div class="border-b border-slate-200">
		<nav class="flex gap-4">
			{#each tabs as tab}
				<button
					onclick={() => (activeTab = tab.id)}
					class="flex items-center gap-2 border-b-2 px-1 pb-3 text-sm font-medium transition-colors {activeTab ===
					tab.id
						? 'border-monaco-600 text-monaco-600'
						: 'border-transparent text-slate-500 hover:text-slate-700'}"
				>
					<svelte:component this={tab.icon} class="h-4 w-4" />
					{tab.label}
				</button>
			{/each}
		</nav>
	</div>

	<!-- Membership Tab -->
	{#if activeTab === 'membership'}
		<div class="space-y-6">
			<!-- Membership Statuses -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center justify-between">
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Membership Statuses</h2>
						<p class="text-sm text-slate-500">Define the different states a membership can be in</p>
					</div>
					<button
						onclick={() => (showAddStatusModal = true)}
						class="flex items-center gap-1.5 rounded-lg bg-monaco-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-monaco-700"
					>
						<Plus class="h-4 w-4" />
						Add Status
					</button>
				</div>

				<div class="overflow-x-auto">
					<table class="w-full">
						<thead class="bg-slate-50">
							<tr>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Name</th>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Display</th>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Color</th>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Default</th>
								<th class="px-4 py-2 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
							</tr>
						</thead>
						<tbody class="divide-y divide-slate-100">
							{#each membershipStatuses as status}
								<tr class="hover:bg-slate-50">
									<td class="px-4 py-3 text-sm text-slate-600">{status.name}</td>
									<td class="px-4 py-3 text-sm font-medium text-slate-900">{status.display_name}</td>
									<td class="px-4 py-3">
										<span
											class="inline-block h-4 w-4 rounded-full"
											style="background-color: {status.color}"
										></span>
									</td>
									<td class="px-4 py-3 text-sm text-slate-600">
										{status.is_default ? 'Yes' : ''}
									</td>
									<td class="px-4 py-3 text-right">
										<form method="POST" action="?/deleteStatus" class="inline">
											<input type="hidden" name="id" value={status.id} />
											<button
												type="submit"
												class="rounded p-1 text-slate-400 hover:bg-red-100 hover:text-red-600"
												title="Delete"
											>
												<Trash2 class="h-4 w-4" />
											</button>
										</form>
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>

			<!-- Membership Types -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center justify-between">
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Membership Types</h2>
						<p class="text-sm text-slate-500">Define different membership tiers with pricing</p>
					</div>
					<button
						onclick={() => (showAddTypeModal = true)}
						class="flex items-center gap-1.5 rounded-lg bg-monaco-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-monaco-700"
					>
						<Plus class="h-4 w-4" />
						Add Type
					</button>
				</div>

				<div class="overflow-x-auto">
					<table class="w-full">
						<thead class="bg-slate-50">
							<tr>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Name</th>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Display</th>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Annual Dues</th>
								<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Default</th>
								<th class="px-4 py-2 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
							</tr>
						</thead>
						<tbody class="divide-y divide-slate-100">
							{#each membershipTypes as type}
								<tr class="hover:bg-slate-50">
									<td class="px-4 py-3 text-sm text-slate-600">{type.name}</td>
									<td class="px-4 py-3 text-sm font-medium text-slate-900">{type.display_name}</td>
									<td class="px-4 py-3 text-sm text-slate-900">€{type.annual_dues.toFixed(2)}</td>
									<td class="px-4 py-3 text-sm text-slate-600">
										{type.is_default ? 'Yes' : ''}
									</td>
									<td class="px-4 py-3 text-right">
										<form method="POST" action="?/deleteType" class="inline">
											<input type="hidden" name="id" value={type.id} />
											<button
												type="submit"
												class="rounded p-1 text-slate-400 hover:bg-red-100 hover:text-red-600"
												title="Delete"
											>
												<Trash2 class="h-4 w-4" />
											</button>
										</form>
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
		</div>
	{/if}

	<!-- Dues Tab -->
	{#if activeTab === 'dues'}
		<div class="glass-card p-6">
			<h2 class="mb-4 text-lg font-semibold text-slate-900">Payment Settings</h2>
			<p class="mb-6 text-sm text-slate-500">Configure bank details and payment instructions shown to members</p>

			<form method="POST" action="?/updateSettings" class="space-y-4">
				<input type="hidden" name="category" value="dues" />

				<div class="grid gap-4 sm:grid-cols-2">
					<div>
						<Label for="bank_name">Bank Name</Label>
						<Input
							type="text"
							id="bank_name"
							name="setting_payment_bank_name"
							value={settings.dues?.payment_bank_name?.replace(/"/g, '') || ''}
							class="mt-1"
						/>
					</div>

					<div>
						<Label for="account_holder">Account Holder</Label>
						<Input
							type="text"
							id="account_holder"
							name="setting_payment_account_holder"
							value={settings.dues?.payment_account_holder?.replace(/"/g, '') || ''}
							class="mt-1"
						/>
					</div>

					<div class="sm:col-span-2">
						<Label for="iban">IBAN</Label>
						<Input
							type="text"
							id="iban"
							name="setting_payment_iban"
							value={settings.dues?.payment_iban?.replace(/"/g, '') || ''}
							class="mt-1"
						/>
					</div>
				</div>

				<button
					type="submit"
					class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
				>
					Save Payment Settings
				</button>
			</form>
		</div>
	{/if}

	<!-- Events Tab -->
	{#if activeTab === 'events'}
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<div>
					<h2 class="text-lg font-semibold text-slate-900">Event Types</h2>
					<p class="text-sm text-slate-500">Define the different types of events</p>
				</div>
				<button
					onclick={() => (showAddEventTypeModal = true)}
					class="flex items-center gap-1.5 rounded-lg bg-monaco-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-monaco-700"
				>
					<Plus class="h-4 w-4" />
					Add Event Type
				</button>
			</div>

			<div class="overflow-x-auto">
				<table class="w-full">
					<thead class="bg-slate-50">
						<tr>
							<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Name</th>
							<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Display</th>
							<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Color</th>
							<th class="px-4 py-2 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
						</tr>
					</thead>
					<tbody class="divide-y divide-slate-100">
						{#each eventTypes as eventType}
							<tr class="hover:bg-slate-50">
								<td class="px-4 py-3 text-sm text-slate-600">{eventType.name}</td>
								<td class="px-4 py-3 text-sm font-medium text-slate-900">{eventType.display_name}</td>
								<td class="px-4 py-3">
									<span
										class="inline-block rounded-full px-2 py-0.5 text-xs font-medium"
										style="background-color: {eventType.color}20; color: {eventType.color}"
									>
										{eventType.display_name}
									</span>
								</td>
								<td class="px-4 py-3 text-right">
									<form method="POST" action="?/deleteEventType" class="inline">
										<input type="hidden" name="id" value={eventType.id} />
										<button
											type="submit"
											class="rounded p-1 text-slate-400 hover:bg-red-100 hover:text-red-600"
											title="Delete"
										>
											<Trash2 class="h-4 w-4" />
										</button>
									</form>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		</div>
	{/if}

	<!-- Documents Tab -->
	{#if activeTab === 'documents'}
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<div>
					<h2 class="text-lg font-semibold text-slate-900">Document Categories</h2>
					<p class="text-sm text-slate-500">Define categories for organizing documents</p>
				</div>
				<button
					onclick={() => (showAddCategoryModal = true)}
					class="flex items-center gap-1.5 rounded-lg bg-monaco-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-monaco-700"
				>
					<Plus class="h-4 w-4" />
					Add Category
				</button>
			</div>

			<div class="overflow-x-auto">
				<table class="w-full">
					<thead class="bg-slate-50">
						<tr>
							<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Name</th>
							<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Display</th>
							<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Description</th>
							<th class="px-4 py-2 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
						</tr>
					</thead>
					<tbody class="divide-y divide-slate-100">
						{#each documentCategories as category}
							<tr class="hover:bg-slate-50">
								<td class="px-4 py-3 text-sm text-slate-600">{category.name}</td>
								<td class="px-4 py-3 text-sm font-medium text-slate-900">{category.display_name}</td>
								<td class="px-4 py-3 text-sm text-slate-500">{category.description || '-'}</td>
								<td class="px-4 py-3 text-right">
									<form method="POST" action="?/deleteCategory" class="inline">
										<input type="hidden" name="id" value={category.id} />
										<button
											type="submit"
											class="rounded p-1 text-slate-400 hover:bg-red-100 hover:text-red-600"
											title="Delete"
										>
											<Trash2 class="h-4 w-4" />
										</button>
									</form>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		</div>
	{/if}

	<!-- Email Tab -->
	{#if activeTab === 'email'}
		<div class="glass-card p-6">
			<div class="mb-6">
				<h2 class="text-lg font-semibold text-slate-900">SMTP Email Configuration</h2>
				<p class="text-sm text-slate-500">Configure outgoing email settings for notifications and reminders</p>
			</div>

			{#if smtpTestResult}
				<div class="mb-4 flex items-center gap-2 rounded-lg p-3 {smtpTestResult.success ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}">
					{#if smtpTestResult.success}
						<CheckCircle class="h-5 w-5" />
					{:else}
						<XCircle class="h-5 w-5" />
					{/if}
					<span class="text-sm">{smtpTestResult.message}</span>
				</div>
			{/if}

			<form method="POST" action="?/updateSettings" class="space-y-6">
				<input type="hidden" name="category" value="email" />

				<!-- Enable Toggle -->
				<div class="flex items-center gap-3 rounded-lg bg-slate-50 p-4">
					<input
						type="checkbox"
						id="smtp_enabled"
						name="setting_smtp_enabled"
						checked={getBoolSetting('email', 'smtp_enabled')}
						class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
					/>
					<div>
						<Label for="smtp_enabled" class="font-medium">Enable Email Sending</Label>
						<p class="text-xs text-slate-500">When enabled, the system will send email notifications</p>
					</div>
				</div>

				<!-- Server Settings -->
				<div class="space-y-4">
					<h3 class="font-medium text-slate-800">Server Settings</h3>
					<div class="grid gap-4 sm:grid-cols-2">
						<div>
							<Label for="smtp_host">SMTP Host</Label>
							<Input
								type="text"
								id="smtp_host"
								name="setting_smtp_host"
								value={getSetting('email', 'smtp_host')}
								placeholder="smtp.gmail.com"
								class="mt-1"
							/>
						</div>
						<div>
							<Label for="smtp_port">SMTP Port</Label>
							<Input
								type="number"
								id="smtp_port"
								name="setting_smtp_port"
								value={getSetting('email', 'smtp_port', '587')}
								placeholder="587"
								class="mt-1"
							/>
						</div>
					</div>
					<div class="flex items-center gap-3">
						<input
							type="checkbox"
							id="smtp_secure"
							name="setting_smtp_secure"
							checked={getBoolSetting('email', 'smtp_secure', true)}
							class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
						<Label for="smtp_secure">Use TLS/SSL (recommended for ports 465, 587)</Label>
					</div>
				</div>

				<!-- Authentication -->
				<div class="space-y-4">
					<h3 class="font-medium text-slate-800">Authentication</h3>
					<div class="grid gap-4 sm:grid-cols-2">
						<div>
							<Label for="smtp_username">Username</Label>
							<Input
								type="text"
								id="smtp_username"
								name="setting_smtp_username"
								value={getSetting('email', 'smtp_username')}
								placeholder="user@example.com"
								class="mt-1"
							/>
						</div>
						<div>
							<Label for="smtp_password">Password</Label>
							<div class="relative mt-1">
								<Input
									type={showSmtpPassword ? 'text' : 'password'}
									id="smtp_password"
									name="setting_smtp_password"
									value={getSetting('email', 'smtp_password')}
									placeholder="••••••••"
									class="pr-10"
								/>
								<button
									type="button"
									onclick={() => (showSmtpPassword = !showSmtpPassword)}
									class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
								>
									{#if showSmtpPassword}
										<EyeOff class="h-4 w-4" />
									{:else}
										<Eye class="h-4 w-4" />
									{/if}
								</button>
							</div>
						</div>
					</div>
				</div>

				<!-- Sender Settings -->
				<div class="space-y-4">
					<h3 class="font-medium text-slate-800">Sender Settings</h3>
					<div class="grid gap-4 sm:grid-cols-2">
						<div>
							<Label for="smtp_from_address">From Address</Label>
							<Input
								type="email"
								id="smtp_from_address"
								name="setting_smtp_from_address"
								value={getSetting('email', 'smtp_from_address', 'noreply@monacousa.org')}
								placeholder="noreply@monacousa.org"
								class="mt-1"
							/>
						</div>
						<div>
							<Label for="smtp_from_name">From Name</Label>
							<Input
								type="text"
								id="smtp_from_name"
								name="setting_smtp_from_name"
								value={getSetting('email', 'smtp_from_name', 'Monaco USA')}
								placeholder="Monaco USA"
								class="mt-1"
							/>
						</div>
						<div class="sm:col-span-2">
							<Label for="smtp_reply_to">Reply-To Address</Label>
							<Input
								type="email"
								id="smtp_reply_to"
								name="setting_smtp_reply_to"
								value={getSetting('email', 'smtp_reply_to', 'contact@monacousa.org')}
								placeholder="contact@monacousa.org"
								class="mt-1"
							/>
						</div>
					</div>
				</div>

				<div class="flex gap-3 border-t border-slate-200 pt-4">
					<button
						type="submit"
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
					>
						Save Email Settings
					</button>
				</div>
			</form>

			<form
				method="POST"
				action="?/testSmtp"
				class="mt-4"
				use:enhance={() => {
					testingSmtp = true;
					smtpTestResult = null;
					return async ({ result }) => {
						testingSmtp = false;
						if (result.type === 'success' && result.data?.success) {
							smtpTestResult = { success: true, message: result.data.success };
						} else if (result.type === 'failure' && result.data?.error) {
							smtpTestResult = { success: false, message: result.data.error };
						} else {
							smtpTestResult = { success: false, message: 'Test failed. Please check your settings.' };
						}
					};
				}}
			>
				<button
					type="submit"
					disabled={testingSmtp}
					class="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
				>
					{#if testingSmtp}
						<Loader2 class="h-4 w-4 animate-spin" />
					{:else}
						<TestTube2 class="h-4 w-4" />
					{/if}
					Test Connection
				</button>
			</form>
		</div>

		<!-- Email Template Testing -->
		<div class="glass-card p-6">
			<div class="mb-6 flex items-start justify-between">
				<div>
					<h2 class="text-lg font-semibold text-slate-900">Test Email Templates</h2>
					<p class="text-sm text-slate-500">Send test versions of each email template to yourself</p>
				</div>
				<a
					href="/admin/email-templates"
					class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 hover:border-monaco-300 hover:text-monaco-600 transition-colors"
				>
					<FileText class="h-4 w-4" />
					Edit Templates
				</a>
			</div>

			{#if templateTestResult}
				<div class="mb-4 flex items-center gap-2 rounded-lg p-3 {templateTestResult.success ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}">
					{#if templateTestResult.success}
						<CheckCircle class="h-5 w-5" />
					{:else}
						<XCircle class="h-5 w-5" />
					{/if}
					<span class="text-sm">{templateTestResult.message}</span>
				</div>
			{/if}

			<div class="space-y-4">
				{#each Object.entries(templatesByCategory) as [category, templates]}
					<div class="border-b border-slate-100 pb-4 last:border-0 last:pb-0">
						<h3 class="mb-3 text-sm font-medium uppercase tracking-wide text-slate-500">
							{category === 'events' ? 'Events' : category === 'payment' ? 'Payments & Dues' : category === 'auth' ? 'Authentication' : category === 'member' ? 'Membership' : 'Other'}
						</h3>
						<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
							{#each templates as template}
								<form
									method="POST"
									action="?/testEmailTemplate"
									use:enhance={() => {
										testingTemplate = template.template_key;
										templateTestResult = null;
										return async ({ result }) => {
											testingTemplate = null;
											if (result.type === 'success' && result.data?.success) {
												templateTestResult = { success: true, message: result.data.success };
											} else if (result.type === 'failure' && result.data?.error) {
												templateTestResult = { success: false, message: result.data.error };
											} else {
												templateTestResult = { success: false, message: 'Failed to send test email' };
											}
										};
									}}
								>
									<input type="hidden" name="template_key" value={template.template_key} />
									<button
										type="submit"
										disabled={testingTemplate !== null}
										class="flex w-full items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-left text-sm transition-colors hover:bg-slate-50 disabled:opacity-50"
									>
										<div class="min-w-0 flex-1">
											<p class="truncate font-medium text-slate-700">{template.template_name}</p>
											<p class="truncate text-xs text-slate-500">{template.template_key}</p>
										</div>
										{#if testingTemplate === template.template_key}
											<Loader2 class="h-4 w-4 flex-shrink-0 animate-spin text-monaco-600" />
										{:else}
											<Mail class="h-4 w-4 flex-shrink-0 text-slate-400" />
										{/if}
									</button>
								</form>
							{/each}
						</div>
					</div>
				{/each}

				{#if !emailTemplates || emailTemplates.length === 0}
					<p class="text-sm text-slate-500">No email templates found in the database.</p>
				{/if}
			</div>
		</div>
	{/if}

	<!-- Poste Email Accounts Tab -->
	{#if activeTab === 'poste'}
		<div class="space-y-6">
			<!-- Poste Configuration -->
			<div class="glass-card p-6">
				<div class="mb-6">
					<h2 class="text-lg font-semibold text-slate-900">Poste Mail Server Configuration</h2>
					<p class="text-sm text-slate-500">Configure connection to your Poste.io mail server to manage @monacousa.org email accounts</p>
				</div>

				{#if posteTestResult}
					<div class="mb-4 flex items-center gap-2 rounded-lg p-3 {posteTestResult.success ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}">
						{#if posteTestResult.success}
							<CheckCircle class="h-5 w-5" />
						{:else}
							<XCircle class="h-5 w-5" />
						{/if}
						<span class="text-sm">{posteTestResult.message}</span>
					</div>
				{/if}

				<form method="POST" action="?/updateSettings" class="space-y-6">
					<input type="hidden" name="category" value="poste" />

					<div class="grid gap-4 sm:grid-cols-2">
						<div class="sm:col-span-2">
							<Label for="poste_api_host">API Host</Label>
							<Input
								type="text"
								id="poste_api_host"
								name="setting_poste_api_host"
								value={getSetting('poste', 'poste_api_host', 'mail.monacousa.org')}
								placeholder="mail.monacousa.org"
								class="mt-1"
							/>
							<p class="mt-1 text-xs text-slate-500">The hostname of your Poste mail server</p>
						</div>
						<div>
							<Label for="poste_admin_email">Admin Email</Label>
							<Input
								type="email"
								id="poste_admin_email"
								name="setting_poste_admin_email"
								value={getSetting('poste', 'poste_admin_email')}
								placeholder="admin@monacousa.org"
								class="mt-1"
							/>
						</div>
						<div>
							<Label for="poste_admin_password">Admin Password</Label>
							<div class="relative mt-1">
								<Input
									type={showPostePassword ? 'text' : 'password'}
									id="poste_admin_password"
									name="setting_poste_admin_password"
									value={getSetting('poste', 'poste_admin_password')}
									placeholder="••••••••"
									class="pr-10"
								/>
								<button
									type="button"
									onclick={() => (showPostePassword = !showPostePassword)}
									class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
								>
									{#if showPostePassword}
										<EyeOff class="h-4 w-4" />
									{:else}
										<Eye class="h-4 w-4" />
									{/if}
								</button>
							</div>
						</div>
						<div>
							<Label for="poste_domain">Email Domain</Label>
							<Input
								type="text"
								id="poste_domain"
								name="setting_poste_domain"
								value={getSetting('poste', 'poste_domain', 'monacousa.org')}
								placeholder="monacousa.org"
								class="mt-1"
							/>
						</div>
					</div>

					<div class="flex gap-3 border-t border-slate-200 pt-4">
						<button
							type="submit"
							class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
						>
							Save Configuration
						</button>
					</div>
				</form>

				<form
					method="POST"
					action="?/testPoste"
					class="mt-4"
					use:enhance={() => {
						testingPoste = true;
						posteTestResult = null;
						return async ({ result }) => {
							testingPoste = false;
							if (result.type === 'success' && result.data?.success) {
								posteTestResult = { success: true, message: result.data.success };
								await loadMailboxes();
							} else if (result.type === 'failure' && result.data?.error) {
								posteTestResult = { success: false, message: result.data.error };
							} else {
								posteTestResult = { success: false, message: 'Connection test failed.' };
							}
						};
					}}
				>
					<button
						type="submit"
						disabled={testingPoste}
						class="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
					>
						{#if testingPoste}
							<Loader2 class="h-4 w-4 animate-spin" />
						{:else}
							<TestTube2 class="h-4 w-4" />
						{/if}
						Test Connection
					</button>
				</form>
			</div>

			<!-- Mailbox Management -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center justify-between">
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Email Accounts</h2>
						<p class="text-sm text-slate-500">Manage @monacousa.org email accounts for board members</p>
					</div>
					<div class="flex items-center gap-2">
						<button
							onclick={loadMailboxes}
							disabled={loadingMailboxes}
							class="flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-600 hover:bg-slate-50 disabled:opacity-50"
						>
							<RefreshCw class="h-4 w-4 {loadingMailboxes ? 'animate-spin' : ''}" />
							Refresh
						</button>
						<button
							onclick={() => (showCreateMailboxModal = true)}
							class="flex items-center gap-1.5 rounded-lg bg-monaco-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-monaco-700"
						>
							<Plus class="h-4 w-4" />
							Create Mailbox
						</button>
					</div>
				</div>

				{#if generatedPassword}
					<div class="mb-4 rounded-lg bg-green-50 p-4">
						<div class="flex items-center justify-between">
							<div>
								<p class="text-sm font-medium text-green-800">Mailbox created! Generated password:</p>
								<code class="mt-1 block rounded bg-green-100 px-2 py-1 font-mono text-sm text-green-900">{generatedPassword}</code>
							</div>
							<button
								onclick={() => { copyPassword(generatedPassword!); generatedPassword = null; }}
								class="flex items-center gap-1.5 rounded-lg bg-green-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-green-700"
							>
								<Copy class="h-4 w-4" />
								Copy & Dismiss
							</button>
						</div>
						<p class="mt-2 text-xs text-green-700">Save this password now - it cannot be retrieved later.</p>
					</div>
				{/if}

				{#if loadingMailboxes}
					<div class="flex items-center justify-center py-12">
						<Loader2 class="h-8 w-8 animate-spin text-monaco-600" />
					</div>
				{:else if mailboxes.length === 0}
					<div class="rounded-lg border border-dashed border-slate-300 p-8 text-center">
						<Inbox class="mx-auto h-12 w-12 text-slate-300" />
						<p class="mt-2 text-sm text-slate-500">No mailboxes loaded. Click "Test Connection" to load mailboxes.</p>
					</div>
				{:else}
					<div class="overflow-x-auto">
						<table class="w-full">
							<thead class="bg-slate-50">
								<tr>
									<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Email</th>
									<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Display Name</th>
									<th class="px-4 py-2 text-left text-xs font-medium uppercase text-slate-500">Status</th>
									<th class="px-4 py-2 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
								</tr>
							</thead>
							<tbody class="divide-y divide-slate-100">
								{#each mailboxes as mailbox}
									<tr class="hover:bg-slate-50">
										<td class="px-4 py-3">
											<span class="font-medium text-slate-900">{mailbox.address}</span>
											{#if mailbox.super_admin}
												<span class="ml-2 rounded-full bg-purple-100 px-2 py-0.5 text-xs font-medium text-purple-700">Admin</span>
											{/if}
										</td>
										<td class="px-4 py-3 text-sm text-slate-600">{mailbox.name || '-'}</td>
										<td class="px-4 py-3">
											{#if mailbox.disabled}
												<span class="inline-flex items-center gap-1 rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">
													<PowerOff class="h-3 w-3" />
													Disabled
												</span>
											{:else}
												<span class="inline-flex items-center gap-1 rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
													<Power class="h-3 w-3" />
													Active
												</span>
											{/if}
										</td>
										<td class="px-4 py-3 text-right">
											<form
												method="POST"
												action="?/deleteMailbox"
												class="inline"
												use:enhance={() => {
													if (!confirm(`Delete mailbox ${mailbox.address}? This cannot be undone.`)) {
														return async () => {};
													}
													return async ({ result }) => {
														if (result.type === 'success') {
															await loadMailboxes();
														}
													};
												}}
											>
												<input type="hidden" name="email" value={mailbox.address} />
												<button
													type="submit"
													class="rounded p-1 text-slate-400 hover:bg-red-100 hover:text-red-600"
													title="Delete mailbox"
												>
													<Trash2 class="h-4 w-4" />
												</button>
											</form>
										</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{/if}
			</div>
		</div>
	{/if}

	<!-- Storage Tab -->
	{#if activeTab === 'storage'}
		<div class="glass-card p-6">
			<div class="mb-6">
				<h2 class="text-lg font-semibold text-slate-900">S3/MinIO Storage Configuration</h2>
				<p class="text-sm text-slate-500">Configure external S3-compatible storage for documents and files</p>
			</div>

			{#if s3TestResult}
				<div class="mb-4 flex items-center gap-2 rounded-lg p-3 {s3TestResult.success ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}">
					{#if s3TestResult.success}
						<CheckCircle class="h-5 w-5" />
					{:else}
						<XCircle class="h-5 w-5" />
					{/if}
					<span class="text-sm">{s3TestResult.message}</span>
				</div>
			{/if}

			<form method="POST" action="?/updateSettings" class="space-y-6">
				<input type="hidden" name="category" value="storage" />

				<!-- Enable Toggle -->
				<div class="flex items-center gap-3 rounded-lg bg-slate-50 p-4">
					<input
						type="checkbox"
						id="s3_enabled"
						name="setting_s3_enabled"
						checked={getBoolSetting('storage', 's3_enabled')}
						class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
					/>
					<div>
						<Label for="s3_enabled" class="font-medium">Enable S3 Storage</Label>
						<p class="text-xs text-slate-500">Use external S3/MinIO instead of Supabase Storage</p>
					</div>
				</div>

				<!-- Connection Settings -->
				<div class="space-y-4">
					<h3 class="font-medium text-slate-800">Connection Settings</h3>
					<div class="grid gap-4 sm:grid-cols-2">
						<div class="sm:col-span-2">
							<Label for="s3_endpoint">Endpoint URL</Label>
							<Input
								type="text"
								id="s3_endpoint"
								name="setting_s3_endpoint"
								value={getSetting('storage', 's3_endpoint')}
								placeholder="http://minio:9000 or https://s3.amazonaws.com"
								class="mt-1"
							/>
							<p class="mt-1 text-xs text-slate-500">For MinIO, use your MinIO server URL. For AWS S3, leave empty or use regional endpoint.</p>
						</div>
						<div>
							<Label for="s3_bucket">Bucket Name</Label>
							<Input
								type="text"
								id="s3_bucket"
								name="setting_s3_bucket"
								value={getSetting('storage', 's3_bucket', 'monacousa-documents')}
								placeholder="monacousa-documents"
								class="mt-1"
							/>
						</div>
						<div>
							<Label for="s3_region">Region</Label>
							<Input
								type="text"
								id="s3_region"
								name="setting_s3_region"
								value={getSetting('storage', 's3_region', 'us-east-1')}
								placeholder="us-east-1"
								class="mt-1"
							/>
							<p class="mt-1 text-xs text-slate-500">Use us-east-1 for MinIO</p>
						</div>
					</div>
				</div>

				<!-- Credentials -->
				<div class="space-y-4">
					<h3 class="font-medium text-slate-800">Credentials</h3>
					<div class="grid gap-4 sm:grid-cols-2">
						<div>
							<Label for="s3_access_key">Access Key ID</Label>
							<Input
								type="text"
								id="s3_access_key"
								name="setting_s3_access_key"
								value={getSetting('storage', 's3_access_key')}
								placeholder="AKIAIOSFODNN7EXAMPLE"
								class="mt-1"
							/>
						</div>
						<div>
							<Label for="s3_secret_key">Secret Access Key</Label>
							<div class="relative mt-1">
								<Input
									type={showS3SecretKey ? 'text' : 'password'}
									id="s3_secret_key"
									name="setting_s3_secret_key"
									value={getSetting('storage', 's3_secret_key')}
									placeholder="••••••••"
									class="pr-10"
								/>
								<button
									type="button"
									onclick={() => (showS3SecretKey = !showS3SecretKey)}
									class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
								>
									{#if showS3SecretKey}
										<EyeOff class="h-4 w-4" />
									{:else}
										<Eye class="h-4 w-4" />
									{/if}
								</button>
							</div>
						</div>
					</div>
				</div>

				<!-- Options -->
				<div class="space-y-4">
					<h3 class="font-medium text-slate-800">Options</h3>
					<div class="space-y-3">
						<div class="flex items-center gap-3">
							<input
								type="checkbox"
								id="s3_use_ssl"
								name="setting_s3_use_ssl"
								checked={getBoolSetting('storage', 's3_use_ssl')}
								class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
							/>
							<Label for="s3_use_ssl">Use SSL/HTTPS</Label>
						</div>
						<div class="flex items-center gap-3">
							<input
								type="checkbox"
								id="s3_force_path_style"
								name="setting_s3_force_path_style"
								checked={getBoolSetting('storage', 's3_force_path_style', true)}
								class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
							/>
							<div>
								<Label for="s3_force_path_style">Force Path Style</Label>
								<p class="text-xs text-slate-500">Required for MinIO and some S3-compatible services</p>
							</div>
						</div>
					</div>
				</div>

				<div class="flex gap-3 border-t border-slate-200 pt-4">
					<button
						type="submit"
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
					>
						Save Storage Settings
					</button>
				</div>
			</form>

			<form
				method="POST"
				action="?/testS3"
				class="mt-4"
				use:enhance={() => {
					testingS3 = true;
					s3TestResult = null;
					return async ({ result }) => {
						testingS3 = false;
						if (result.type === 'success' && result.data?.success) {
							s3TestResult = { success: true, message: result.data.success };
						} else if (result.type === 'failure' && result.data?.error) {
							s3TestResult = { success: false, message: result.data.error };
						} else {
							s3TestResult = { success: false, message: 'S3 test failed. Please check your settings.' };
						}
					};
				}}
			>
				<button
					type="submit"
					disabled={testingS3}
					class="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
				>
					{#if testingS3}
						<Loader2 class="h-4 w-4 animate-spin" />
					{:else}
						<TestTube2 class="h-4 w-4" />
					{/if}
					Test Connection
				</button>
			</form>
		</div>
	{/if}

	<!-- System Tab -->
	{#if activeTab === 'system'}
		<div class="space-y-6">
			<!-- Maintenance Mode -->
			<div class="glass-card p-6">
				<h2 class="mb-4 text-lg font-semibold text-slate-900">Maintenance Mode</h2>
				<form method="POST" action="?/updateSettings" class="space-y-4">
					<input type="hidden" name="category" value="system" />

					<div class="flex items-center gap-3 rounded-lg bg-amber-50 p-4">
						<input
							type="checkbox"
							id="maintenance_mode"
							name="setting_maintenance_mode"
							checked={getBoolSetting('system', 'maintenance_mode')}
							class="h-4 w-4 rounded border-amber-300 text-amber-600 focus:ring-amber-500"
						/>
						<div>
							<Label for="maintenance_mode" class="font-medium text-amber-800">Enable Maintenance Mode</Label>
							<p class="text-xs text-amber-700">When enabled, non-admin users will see the maintenance message</p>
						</div>
					</div>

					<div>
						<Label for="maintenance_message">Maintenance Message</Label>
						<textarea
							id="maintenance_message"
							name="setting_maintenance_message"
							rows="2"
							class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
						>{getSetting('system', 'maintenance_message', 'The portal is currently undergoing maintenance. Please check back soon.')}</textarea>
					</div>

					<button
						type="submit"
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
					>
						Save Maintenance Settings
					</button>
				</form>
			</div>

			<!-- Session & Security -->
			<div class="glass-card p-6">
				<h2 class="mb-4 text-lg font-semibold text-slate-900">Session & Security</h2>
				<form method="POST" action="?/updateSettings" class="space-y-4">
					<input type="hidden" name="category" value="system" />

					<div>
						<Label for="session_timeout">Session Timeout (hours)</Label>
						<Input
							type="number"
							id="session_timeout"
							name="setting_session_timeout_hours"
							value={getSetting('system', 'session_timeout_hours', '168')}
							min="1"
							max="720"
							class="mt-1 max-w-xs"
						/>
						<p class="mt-1 text-xs text-slate-500">Default is 168 hours (7 days). Max is 720 hours (30 days).</p>
					</div>

					<button
						type="submit"
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
					>
						Save Security Settings
					</button>
				</form>
			</div>

			<!-- File Upload Settings -->
			<div class="glass-card p-6">
				<h2 class="mb-4 text-lg font-semibold text-slate-900">File Uploads</h2>
				<form method="POST" action="?/updateSettings" class="space-y-4">
					<input type="hidden" name="category" value="system" />

					<div>
						<Label for="max_upload">Maximum Upload Size (MB)</Label>
						<Input
							type="number"
							id="max_upload"
							name="setting_max_upload_size_mb"
							value={getSetting('system', 'max_upload_size_mb', '50')}
							min="1"
							max="500"
							class="mt-1 max-w-xs"
						/>
					</div>

					<div>
						<Label>Allowed File Types</Label>
						<p class="mt-1 text-sm text-slate-600">
							PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, JPG, JPEG, PNG, WEBP
						</p>
						<p class="mt-1 text-xs text-slate-500">File type restrictions are enforced on upload</p>
					</div>

					<button
						type="submit"
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
					>
						Save Upload Settings
					</button>
				</form>
			</div>

			<!-- Public Access -->
			<div class="glass-card p-6">
				<h2 class="mb-4 text-lg font-semibold text-slate-900">Public Access</h2>
				<form method="POST" action="?/updateSettings" class="space-y-4">
					<input type="hidden" name="category" value="system" />

					<div class="space-y-3">
						<div class="flex items-center gap-3">
							<input
								type="checkbox"
								id="enable_public_events"
								name="setting_enable_public_events"
								checked={getBoolSetting('system', 'enable_public_events', true)}
								class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
							/>
							<div>
								<Label for="enable_public_events">Enable Public Events Page</Label>
								<p class="text-xs text-slate-500">Allow non-members to view events marked as public</p>
							</div>
						</div>

						<div class="flex items-center gap-3">
							<input
								type="checkbox"
								id="enable_public_rsvp"
								name="setting_enable_public_rsvp"
								checked={getBoolSetting('system', 'enable_public_rsvp', true)}
								class="h-4 w-4 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
							/>
							<div>
								<Label for="enable_public_rsvp">Enable Public RSVP</Label>
								<p class="text-xs text-slate-500">Allow non-members to RSVP to public events</p>
							</div>
						</div>
					</div>

					<button
						type="submit"
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700"
					>
						Save Public Access Settings
					</button>
				</form>
			</div>
		</div>
	{/if}
</div>

<!-- Add Status Modal -->
{#if showAddStatusModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center justify-between">
				<h3 class="text-lg font-semibold text-slate-900">Add Membership Status</h3>
				<button onclick={() => (showAddStatusModal = false)} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<form
				method="POST"
				action="?/createStatus"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						if (result.type === 'success') {
							showAddStatusModal = false;
							await invalidateAll();
						}
						await update();
						isSubmitting = false;
					};
				}}
				class="space-y-4"
			>
				<div>
					<Label for="status_name">Name (lowercase, no spaces)</Label>
					<Input type="text" id="status_name" name="name" required class="mt-1" />
				</div>
				<div>
					<Label for="status_display">Display Name</Label>
					<Input type="text" id="status_display" name="display_name" required class="mt-1" />
				</div>
				<div>
					<Label for="status_color">Color</Label>
					<Input type="color" id="status_color" name="color" value="#6b7280" class="mt-1 h-10" />
				</div>
				<div>
					<Label for="status_desc">Description (optional)</Label>
					<Input type="text" id="status_desc" name="description" class="mt-1" />
				</div>
				<div class="flex gap-3 pt-2">
					<button
						type="button"
						onclick={() => (showAddStatusModal = false)}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex-1 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{isSubmitting ? 'Adding...' : 'Add Status'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Add Membership Type Modal -->
{#if showAddTypeModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center justify-between">
				<h3 class="text-lg font-semibold text-slate-900">Add Membership Type</h3>
				<button onclick={() => (showAddTypeModal = false)} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<form
				method="POST"
				action="?/createType"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						if (result.type === 'success') {
							showAddTypeModal = false;
							await invalidateAll();
						}
						await update();
						isSubmitting = false;
					};
				}}
				class="space-y-4"
			>
				<div>
					<Label for="type_name">Name (lowercase, no spaces)</Label>
					<Input type="text" id="type_name" name="name" required class="mt-1" />
				</div>
				<div>
					<Label for="type_display">Display Name</Label>
					<Input type="text" id="type_display" name="display_name" required class="mt-1" />
				</div>
				<div>
					<Label for="type_dues">Annual Dues (€)</Label>
					<Input type="number" id="type_dues" name="annual_dues" step="0.01" required class="mt-1" />
				</div>
				<div>
					<Label for="type_desc">Description (optional)</Label>
					<Input type="text" id="type_desc" name="description" class="mt-1" />
				</div>
				<div class="flex gap-3 pt-2">
					<button
						type="button"
						onclick={() => (showAddTypeModal = false)}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex-1 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{isSubmitting ? 'Adding...' : 'Add Type'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Add Event Type Modal -->
{#if showAddEventTypeModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center justify-between">
				<h3 class="text-lg font-semibold text-slate-900">Add Event Type</h3>
				<button onclick={() => (showAddEventTypeModal = false)} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<form
				method="POST"
				action="?/createEventType"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						if (result.type === 'success') {
							showAddEventTypeModal = false;
							await invalidateAll();
						}
						await update();
						isSubmitting = false;
					};
				}}
				class="space-y-4"
			>
				<div>
					<Label for="etype_name">Name (lowercase, no spaces)</Label>
					<Input type="text" id="etype_name" name="name" required class="mt-1" />
				</div>
				<div>
					<Label for="etype_display">Display Name</Label>
					<Input type="text" id="etype_display" name="display_name" required class="mt-1" />
				</div>
				<div>
					<Label for="etype_color">Color</Label>
					<Input type="color" id="etype_color" name="color" value="#3b82f6" class="mt-1 h-10" />
				</div>
				<div class="flex gap-3 pt-2">
					<button
						type="button"
						onclick={() => (showAddEventTypeModal = false)}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex-1 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{isSubmitting ? 'Adding...' : 'Add Event Type'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Add Document Category Modal -->
{#if showAddCategoryModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center justify-between">
				<h3 class="text-lg font-semibold text-slate-900">Add Document Category</h3>
				<button onclick={() => (showAddCategoryModal = false)} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<form
				method="POST"
				action="?/createCategory"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						if (result.type === 'success') {
							showAddCategoryModal = false;
							await invalidateAll();
						}
						await update();
						isSubmitting = false;
					};
				}}
				class="space-y-4"
			>
				<div>
					<Label for="cat_name">Name (lowercase, no spaces)</Label>
					<Input type="text" id="cat_name" name="name" required class="mt-1" />
				</div>
				<div>
					<Label for="cat_display">Display Name</Label>
					<Input type="text" id="cat_display" name="display_name" required class="mt-1" />
				</div>
				<div>
					<Label for="cat_desc">Description (optional)</Label>
					<Input type="text" id="cat_desc" name="description" class="mt-1" />
				</div>
				<div class="flex gap-3 pt-2">
					<button
						type="button"
						onclick={() => (showAddCategoryModal = false)}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex-1 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{isSubmitting ? 'Adding...' : 'Add Category'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Create Mailbox Modal -->
{#if showCreateMailboxModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center justify-between">
				<div class="flex items-center gap-3">
					<div class="rounded-full bg-monaco-100 p-2">
						<Inbox class="h-5 w-5 text-monaco-600" />
					</div>
					<h3 class="text-lg font-semibold text-slate-900">Create Email Account</h3>
				</div>
				<button onclick={() => (showCreateMailboxModal = false)} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<form
				method="POST"
				action="?/createMailbox"
				use:enhance={() => {
					creatingMailbox = true;
					return async ({ result }) => {
						creatingMailbox = false;
						if (result.type === 'success') {
							showCreateMailboxModal = false;
							if (result.data?.generatedPassword) {
								generatedPassword = result.data.generatedPassword;
							}
							await loadMailboxes();
						}
					};
				}}
				class="space-y-4"
			>
				<div>
					<Label for="email_prefix">Email Address</Label>
					<div class="mt-1 flex">
						<Input
							type="text"
							id="email_prefix"
							name="email_prefix"
							placeholder="john.doe"
							required
							pattern="[a-zA-Z0-9._-]+"
							class="rounded-r-none"
						/>
						<span class="flex items-center rounded-r-lg border border-l-0 border-slate-200 bg-slate-50 px-3 text-sm text-slate-500">
							@{getSetting('poste', 'poste_domain', 'monacousa.org')}
						</span>
					</div>
					<p class="mt-1 text-xs text-slate-500">Letters, numbers, dots, dashes, and underscores only</p>
				</div>

				<div>
					<Label for="display_name">Display Name</Label>
					<Input
						type="text"
						id="display_name"
						name="display_name"
						placeholder="John Doe"
						required
						class="mt-1"
					/>
				</div>

				<div>
					<Label for="mailbox_password">Password (optional)</Label>
					<div class="relative mt-1">
						<Input
							type="password"
							id="mailbox_password"
							name="password"
							placeholder="Leave empty to generate random password"
							minlength="8"
						/>
						<Key class="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
					</div>
					<p class="mt-1 text-xs text-slate-500">If left empty, a secure password will be generated</p>
				</div>

				<div class="flex gap-3 pt-2">
					<button
						type="button"
						onclick={() => (showCreateMailboxModal = false)}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={creatingMailbox}
						class="flex-1 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{#if creatingMailbox}
							<span class="inline-flex items-center gap-2">
								<Loader2 class="h-4 w-4 animate-spin" />
								Creating...
							</span>
						{:else}
							Create Mailbox
						{/if}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
