<script lang="ts">
	import {
		User,
		Bell,
		Shield,
		Camera,
		Trash2,
		Mail,
		Calendar,
		CreditCard,
		Megaphone,
		Newspaper,
		Lock,
		Eye,
		EyeOff,
		Search,
		X,
		ChevronDown
	} from 'lucide-svelte';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { PhoneInput, CountrySelect } from '$lib/components/ui';
	import { enhance } from '$app/forms';
	import { page } from '$app/stores';
	import { invalidateAll } from '$app/navigation';
	import 'flag-icons/css/flag-icons.min.css';

	let { data, form } = $props();

	type Tab = 'profile' | 'notifications' | 'account';

	// Check URL for tab parameter (e.g., ?tab=security)
	function getInitialTab(): Tab {
		const urlTab = $page.url.searchParams.get('tab');
		if (urlTab === 'security' || urlTab === 'account') return 'account';
		if (urlTab === 'notifications') return 'notifications';
		return 'profile';
	}

	let activeTab = $state<Tab>(getInitialTab());
	let isSubmitting = $state(false);
	let showCurrentPassword = $state(false);
	let showPassword = $state(false);
	let showConfirmPassword = $state(false);

	// Get member and preferences from data
	const member = $derived(data.member);
	const notificationPrefs = $derived(data.notificationPrefs);

	// Avatar preview and form reference
	let avatarPreview = $state<string | null>(null);
	let avatarFormRef: HTMLFormElement;

	// Nationality state - initialize from member data
	let selectedNationalities = $state<string[]>([]);

	// Phone state
	let phoneValue = $state('');
	let phoneCountryCode = $state('US');

	// Address state
	let street = $state('');
	let city = $state('');
	let residenceCountry = $state('MC');

	// Parse address when member data loads
	$effect(() => {
		if (member?.phone) {
			phoneValue = member.phone;
		}
		if (member?.address) {
			// Try to parse existing address (format: "street, city, country")
			const parts = member.address.split(',').map((p: string) => p.trim());
			if (parts.length >= 3) {
				street = parts.slice(0, -2).join(', ');
				city = parts[parts.length - 2] || '';
				residenceCountry = parts[parts.length - 1] || 'MC';
			} else if (parts.length === 2) {
				street = parts[0] || '';
				city = parts[1] || '';
			} else {
				street = member.address;
			}
		}
	});

	// Computed full address for database
	const fullAddress = $derived(`${street}, ${city}, ${residenceCountry}`);

	// Sync nationality state when member data changes
	$effect(() => {
		if (member?.nationality) {
			selectedNationalities = [...member.nationality];
		}
	});

	const tabs: Array<{ id: Tab; label: string; icon: any }> = [
		{ id: 'profile', label: 'Profile', icon: User },
		{ id: 'notifications', label: 'Notifications', icon: Bell },
		{ id: 'account', label: 'Account & Security', icon: Shield }
	];

	// Complete list of countries (ISO 3166-1)
	const countries = [
		{ code: 'af', name: 'Afghanistan' },
		{ code: 'al', name: 'Albania' },
		{ code: 'dz', name: 'Algeria' },
		{ code: 'ad', name: 'Andorra' },
		{ code: 'ao', name: 'Angola' },
		{ code: 'ag', name: 'Antigua and Barbuda' },
		{ code: 'ar', name: 'Argentina' },
		{ code: 'am', name: 'Armenia' },
		{ code: 'au', name: 'Australia' },
		{ code: 'at', name: 'Austria' },
		{ code: 'az', name: 'Azerbaijan' },
		{ code: 'bs', name: 'Bahamas' },
		{ code: 'bh', name: 'Bahrain' },
		{ code: 'bd', name: 'Bangladesh' },
		{ code: 'bb', name: 'Barbados' },
		{ code: 'by', name: 'Belarus' },
		{ code: 'be', name: 'Belgium' },
		{ code: 'bz', name: 'Belize' },
		{ code: 'bj', name: 'Benin' },
		{ code: 'bt', name: 'Bhutan' },
		{ code: 'bo', name: 'Bolivia' },
		{ code: 'ba', name: 'Bosnia and Herzegovina' },
		{ code: 'bw', name: 'Botswana' },
		{ code: 'br', name: 'Brazil' },
		{ code: 'bn', name: 'Brunei' },
		{ code: 'bg', name: 'Bulgaria' },
		{ code: 'bf', name: 'Burkina Faso' },
		{ code: 'bi', name: 'Burundi' },
		{ code: 'cv', name: 'Cabo Verde' },
		{ code: 'kh', name: 'Cambodia' },
		{ code: 'cm', name: 'Cameroon' },
		{ code: 'ca', name: 'Canada' },
		{ code: 'cf', name: 'Central African Republic' },
		{ code: 'td', name: 'Chad' },
		{ code: 'cl', name: 'Chile' },
		{ code: 'cn', name: 'China' },
		{ code: 'co', name: 'Colombia' },
		{ code: 'km', name: 'Comoros' },
		{ code: 'cg', name: 'Congo' },
		{ code: 'cd', name: 'Congo (DRC)' },
		{ code: 'cr', name: 'Costa Rica' },
		{ code: 'ci', name: "Côte d'Ivoire" },
		{ code: 'hr', name: 'Croatia' },
		{ code: 'cu', name: 'Cuba' },
		{ code: 'cy', name: 'Cyprus' },
		{ code: 'cz', name: 'Czech Republic' },
		{ code: 'dk', name: 'Denmark' },
		{ code: 'dj', name: 'Djibouti' },
		{ code: 'dm', name: 'Dominica' },
		{ code: 'do', name: 'Dominican Republic' },
		{ code: 'ec', name: 'Ecuador' },
		{ code: 'eg', name: 'Egypt' },
		{ code: 'sv', name: 'El Salvador' },
		{ code: 'gq', name: 'Equatorial Guinea' },
		{ code: 'er', name: 'Eritrea' },
		{ code: 'ee', name: 'Estonia' },
		{ code: 'sz', name: 'Eswatini' },
		{ code: 'et', name: 'Ethiopia' },
		{ code: 'fj', name: 'Fiji' },
		{ code: 'fi', name: 'Finland' },
		{ code: 'fr', name: 'France' },
		{ code: 'ga', name: 'Gabon' },
		{ code: 'gm', name: 'Gambia' },
		{ code: 'ge', name: 'Georgia' },
		{ code: 'de', name: 'Germany' },
		{ code: 'gh', name: 'Ghana' },
		{ code: 'gr', name: 'Greece' },
		{ code: 'gd', name: 'Grenada' },
		{ code: 'gt', name: 'Guatemala' },
		{ code: 'gn', name: 'Guinea' },
		{ code: 'gw', name: 'Guinea-Bissau' },
		{ code: 'gy', name: 'Guyana' },
		{ code: 'ht', name: 'Haiti' },
		{ code: 'hn', name: 'Honduras' },
		{ code: 'hu', name: 'Hungary' },
		{ code: 'is', name: 'Iceland' },
		{ code: 'in', name: 'India' },
		{ code: 'id', name: 'Indonesia' },
		{ code: 'ir', name: 'Iran' },
		{ code: 'iq', name: 'Iraq' },
		{ code: 'ie', name: 'Ireland' },
		{ code: 'il', name: 'Israel' },
		{ code: 'it', name: 'Italy' },
		{ code: 'jm', name: 'Jamaica' },
		{ code: 'jp', name: 'Japan' },
		{ code: 'jo', name: 'Jordan' },
		{ code: 'kz', name: 'Kazakhstan' },
		{ code: 'ke', name: 'Kenya' },
		{ code: 'ki', name: 'Kiribati' },
		{ code: 'kp', name: 'North Korea' },
		{ code: 'kr', name: 'South Korea' },
		{ code: 'kw', name: 'Kuwait' },
		{ code: 'kg', name: 'Kyrgyzstan' },
		{ code: 'la', name: 'Laos' },
		{ code: 'lv', name: 'Latvia' },
		{ code: 'lb', name: 'Lebanon' },
		{ code: 'ls', name: 'Lesotho' },
		{ code: 'lr', name: 'Liberia' },
		{ code: 'ly', name: 'Libya' },
		{ code: 'li', name: 'Liechtenstein' },
		{ code: 'lt', name: 'Lithuania' },
		{ code: 'lu', name: 'Luxembourg' },
		{ code: 'mg', name: 'Madagascar' },
		{ code: 'mw', name: 'Malawi' },
		{ code: 'my', name: 'Malaysia' },
		{ code: 'mv', name: 'Maldives' },
		{ code: 'ml', name: 'Mali' },
		{ code: 'mt', name: 'Malta' },
		{ code: 'mh', name: 'Marshall Islands' },
		{ code: 'mr', name: 'Mauritania' },
		{ code: 'mu', name: 'Mauritius' },
		{ code: 'mx', name: 'Mexico' },
		{ code: 'fm', name: 'Micronesia' },
		{ code: 'md', name: 'Moldova' },
		{ code: 'mc', name: 'Monaco' },
		{ code: 'mn', name: 'Mongolia' },
		{ code: 'me', name: 'Montenegro' },
		{ code: 'ma', name: 'Morocco' },
		{ code: 'mz', name: 'Mozambique' },
		{ code: 'mm', name: 'Myanmar' },
		{ code: 'na', name: 'Namibia' },
		{ code: 'nr', name: 'Nauru' },
		{ code: 'np', name: 'Nepal' },
		{ code: 'nl', name: 'Netherlands' },
		{ code: 'nz', name: 'New Zealand' },
		{ code: 'ni', name: 'Nicaragua' },
		{ code: 'ne', name: 'Niger' },
		{ code: 'ng', name: 'Nigeria' },
		{ code: 'mk', name: 'North Macedonia' },
		{ code: 'no', name: 'Norway' },
		{ code: 'om', name: 'Oman' },
		{ code: 'pk', name: 'Pakistan' },
		{ code: 'pw', name: 'Palau' },
		{ code: 'ps', name: 'Palestine' },
		{ code: 'pa', name: 'Panama' },
		{ code: 'pg', name: 'Papua New Guinea' },
		{ code: 'py', name: 'Paraguay' },
		{ code: 'pe', name: 'Peru' },
		{ code: 'ph', name: 'Philippines' },
		{ code: 'pl', name: 'Poland' },
		{ code: 'pt', name: 'Portugal' },
		{ code: 'qa', name: 'Qatar' },
		{ code: 'ro', name: 'Romania' },
		{ code: 'ru', name: 'Russia' },
		{ code: 'rw', name: 'Rwanda' },
		{ code: 'kn', name: 'Saint Kitts and Nevis' },
		{ code: 'lc', name: 'Saint Lucia' },
		{ code: 'vc', name: 'Saint Vincent and the Grenadines' },
		{ code: 'ws', name: 'Samoa' },
		{ code: 'sm', name: 'San Marino' },
		{ code: 'st', name: 'São Tomé and Príncipe' },
		{ code: 'sa', name: 'Saudi Arabia' },
		{ code: 'sn', name: 'Senegal' },
		{ code: 'rs', name: 'Serbia' },
		{ code: 'sc', name: 'Seychelles' },
		{ code: 'sl', name: 'Sierra Leone' },
		{ code: 'sg', name: 'Singapore' },
		{ code: 'sk', name: 'Slovakia' },
		{ code: 'si', name: 'Slovenia' },
		{ code: 'sb', name: 'Solomon Islands' },
		{ code: 'so', name: 'Somalia' },
		{ code: 'za', name: 'South Africa' },
		{ code: 'ss', name: 'South Sudan' },
		{ code: 'es', name: 'Spain' },
		{ code: 'lk', name: 'Sri Lanka' },
		{ code: 'sd', name: 'Sudan' },
		{ code: 'sr', name: 'Suriname' },
		{ code: 'se', name: 'Sweden' },
		{ code: 'ch', name: 'Switzerland' },
		{ code: 'sy', name: 'Syria' },
		{ code: 'tw', name: 'Taiwan' },
		{ code: 'tj', name: 'Tajikistan' },
		{ code: 'tz', name: 'Tanzania' },
		{ code: 'th', name: 'Thailand' },
		{ code: 'tl', name: 'Timor-Leste' },
		{ code: 'tg', name: 'Togo' },
		{ code: 'to', name: 'Tonga' },
		{ code: 'tt', name: 'Trinidad and Tobago' },
		{ code: 'tn', name: 'Tunisia' },
		{ code: 'tr', name: 'Turkey' },
		{ code: 'tm', name: 'Turkmenistan' },
		{ code: 'tv', name: 'Tuvalu' },
		{ code: 'ug', name: 'Uganda' },
		{ code: 'ua', name: 'Ukraine' },
		{ code: 'ae', name: 'United Arab Emirates' },
		{ code: 'gb', name: 'United Kingdom' },
		{ code: 'us', name: 'United States' },
		{ code: 'uy', name: 'Uruguay' },
		{ code: 'uz', name: 'Uzbekistan' },
		{ code: 'vu', name: 'Vanuatu' },
		{ code: 'va', name: 'Vatican City' },
		{ code: 've', name: 'Venezuela' },
		{ code: 'vn', name: 'Vietnam' },
		{ code: 'ye', name: 'Yemen' },
		{ code: 'zm', name: 'Zambia' },
		{ code: 'zw', name: 'Zimbabwe' }
	].sort((a, b) => a.name.localeCompare(b.name));

	// Nationality dropdown state
	let nationalityDropdownOpen = $state(false);
	let nationalitySearch = $state('');
	let nationalityDropdownRef = $state<HTMLDivElement | null>(null);

	const filteredCountries = $derived(
		countries.filter((c) => c.name.toLowerCase().includes(nationalitySearch.toLowerCase()))
	);

	function toggleNationality(code: string) {
		if (selectedNationalities.includes(code)) {
			selectedNationalities = selectedNationalities.filter((n) => n !== code);
		} else {
			selectedNationalities = [...selectedNationalities, code];
		}
	}

	function removeNationality(code: string) {
		selectedNationalities = selectedNationalities.filter((n) => n !== code);
	}

	function getCountryName(code: string): string {
		const lowerCode = code.toLowerCase();
		return countries.find((c) => c.code === lowerCode)?.name || code;
	}

	function normalizeCode(code: string): string {
		return code.toLowerCase();
	}

	function handleNationalityClickOutside(event: MouseEvent) {
		if (nationalityDropdownRef && !nationalityDropdownRef.contains(event.target as Node)) {
			nationalityDropdownOpen = false;
		}
	}

	function handleFileSelect(event: Event) {
		const input = event.target as HTMLInputElement;
		const file = input.files?.[0];
		if (file) {
			const reader = new FileReader();
			reader.onload = (e) => {
				avatarPreview = e.target?.result as string;
				// Auto-submit the form after preview is set
				if (avatarFormRef) {
					avatarFormRef.requestSubmit();
				}
			};
			reader.readAsDataURL(file);
		}
	}

	function getInitials(firstName: string, lastName: string): string {
		return `${firstName?.charAt(0) || ''}${lastName?.charAt(0) || ''}`.toUpperCase();
	}
</script>

<svelte:window onclick={handleNationalityClickOutside} />

<svelte:head>
	<title>Settings | Monaco USA</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">Manage your profile, notifications, and account security</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}
				{@const Icon = tab.icon}
				<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'}"
				>
					<Icon class="h-4 w-4" />
					{tab.label}
				</button>
			{/each}
		</nav>
	</div>

	<!-- Profile Tab -->
	{#if activeTab === 'profile'}
		<div class="grid gap-6 lg:grid-cols-3">
			<!-- Avatar Section -->
			<div class="glass-card p-6">
				<h2 class="mb-4 text-lg font-semibold text-slate-900">Profile Picture</h2>
				<div class="flex flex-col items-center gap-4">
					<div class="relative">
						{#if avatarPreview || member?.avatar_url}
							<img
								src={avatarPreview || member?.avatar_url}
								alt="Profile"
								class="h-32 w-32 rounded-full object-cover ring-4 ring-white shadow-lg"
							/>
						{:else}
							<div
								class="flex h-32 w-32 items-center justify-center rounded-full bg-gradient-to-br from-monaco-500 to-monaco-700 text-3xl font-bold text-white ring-4 ring-white shadow-lg"
							>
								{getInitials(member?.first_name || '', member?.last_name || '')}
							</div>
						{/if}
					</div>

					<div class="flex gap-2">
						<form
							bind:this={avatarFormRef}
							method="POST"
							action="?/uploadAvatar"
							enctype="multipart/form-data"
							use:enhance={() => {
								isSubmitting = true;
								return async ({ update }) => {
									await invalidateAll();
									await update();
									isSubmitting = false;
									avatarPreview = null;
								};
							}}
						>
							<input
								type="file"
								id="avatar-input"
								name="avatar"
								accept="image/*"
								class="sr-only"
								onchange={handleFileSelect}
							/>
							{#if avatarPreview}
								<button
									type="submit"
									disabled={isSubmitting}
									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 disabled:opacity-50"
								>
									{isSubmitting ? 'Uploading...' : 'Save Photo'}
								</button>
							{:else}
								<label
									for="avatar-input"
									class="flex cursor-pointer 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"
								>
									<Camera class="h-4 w-4" />
									Change
								</label>
							{/if}
						</form>

						{#if member?.avatar_url}
							<form
								method="POST"
								action="?/removeAvatar"
								use:enhance={() => {
									isSubmitting = true;
									return async ({ update }) => {
										await invalidateAll();
										await update();
										isSubmitting = false;
									};
								}}
							>
								<button
									type="submit"
									disabled={isSubmitting}
									class="flex items-center gap-1.5 rounded-lg border border-slate-200 px-3 py-1.5 text-sm font-medium text-slate-600 hover:bg-slate-50 disabled:opacity-50"
								>
									<Trash2 class="h-4 w-4" />
									Remove
								</button>
							</form>
						{/if}
					</div>
					<p class="text-center text-xs text-slate-500">
						JPG, PNG, WebP or GIF. Max 5MB.
					</p>
				</div>
			</div>

			<!-- Personal Details -->
			<div class="glass-card p-6 lg:col-span-2">
				<h2 class="mb-4 text-lg font-semibold text-slate-900">Personal Information</h2>
				<form
					method="POST"
					action="?/updateProfile"
					use:enhance={() => {
						isSubmitting = true;
						return async ({ update }) => {
							await invalidateAll();
							await update();
							isSubmitting = false;
						};
					}}
					class="space-y-4"
				>
					<div class="grid gap-4 sm:grid-cols-2">
						<div>
							<Label for="first_name">First Name</Label>
							<Input
								type="text"
								id="first_name"
								name="first_name"
								value={member?.first_name || ''}
								required
								class="mt-1"
							/>
						</div>
						<div>
							<Label for="last_name">Last Name</Label>
							<Input
								type="text"
								id="last_name"
								name="last_name"
								value={member?.last_name || ''}
								required
								class="mt-1"
							/>
						</div>
					</div>

					<!-- Nationality - placed early so dropdown has room to expand -->
					<div>
						<Label>Nationality</Label>
						<p class="mb-2 text-xs text-slate-500">Select all nationalities/citizenships that apply</p>
						<input type="hidden" name="nationality" value={selectedNationalities.join(',')} />

						<!-- Selected nationalities -->
						{#if selectedNationalities.length > 0}
							<div class="mb-2 flex flex-wrap gap-2">
								{#each selectedNationalities as code}
									{@const lowerCode = code.toLowerCase()}
									<span class="flex items-center gap-1.5 rounded-full bg-monaco-100 px-3 py-1 text-sm text-monaco-700">
										<span class={`fi fi-${lowerCode} fis`} style="width: 1.33em; height: 1em;"></span>
										{getCountryName(code)}
										<button
											type="button"
											onclick={() => removeNationality(code)}
											class="ml-1 rounded-full p-0.5 hover:bg-monaco-200"
										>
											<X class="h-3 w-3" />
										</button>
									</span>
								{/each}
							</div>
						{/if}

						<!-- Dropdown -->
						<div class="relative" bind:this={nationalityDropdownRef}>
							<button
								type="button"
								onclick={() => (nationalityDropdownOpen = !nationalityDropdownOpen)}
								class="flex w-full items-center justify-between rounded-lg border border-slate-200 px-3 py-2 text-left text-sm transition-colors hover:border-slate-300 focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
							>
								<span class="text-slate-500">
									{selectedNationalities.length === 0
										? 'Select nationalities...'
										: `${selectedNationalities.length} selected`}
								</span>
								<ChevronDown class="h-4 w-4 text-slate-400 transition-transform {nationalityDropdownOpen ? 'rotate-180' : ''}" />
							</button>

							{#if nationalityDropdownOpen}
								<div class="absolute z-50 mt-1 max-h-64 w-full overflow-hidden rounded-lg border border-slate-200 bg-white shadow-lg">
									<!-- Search -->
									<div class="border-b border-slate-100 p-2">
										<div class="relative">
											<Search class="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
											<input
												type="text"
												bind:value={nationalitySearch}
												placeholder="Search countries..."
												class="w-full rounded-md border border-slate-200 py-1.5 pl-8 pr-3 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
											/>
										</div>
									</div>

									<!-- Country list -->
									<div class="max-h-48 overflow-y-auto">
										{#each filteredCountries as country}
											<button
												type="button"
												onclick={() => toggleNationality(country.code)}
												class="flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors hover:bg-slate-50 {selectedNationalities.includes(country.code) ? 'bg-monaco-50 text-monaco-700' : 'text-slate-700'}"
											>
												<span class={`fi fi-${country.code} fis`} style="width: 1.33em; height: 1em;"></span>
												<span class="flex-1">{country.name}</span>
												{#if selectedNationalities.includes(country.code)}
													<span class="text-monaco-600">✓</span>
												{/if}
											</button>
										{/each}
										{#if filteredCountries.length === 0}
											<p class="px-3 py-2 text-sm text-slate-500">No countries found</p>
										{/if}
									</div>
								</div>
							{/if}
						</div>
					</div>

					<div>
						<Label>Phone Number</Label>
						<PhoneInput
							bind:value={phoneValue}
							bind:countryCode={phoneCountryCode}
							placeholder="Phone number"
							name="phone"
							class="mt-1"
						/>
					</div>

					<div>
						<Label for="street">Street Address</Label>
						<Input
							type="text"
							id="street"
							name="street"
							bind:value={street}
							placeholder="123 Avenue Princesse Grace"
							class="mt-1"
						/>
					</div>

					<div class="grid gap-4 sm:grid-cols-2">
						<div>
							<Label for="city">City</Label>
							<Input
								type="text"
								id="city"
								name="city"
								bind:value={city}
								placeholder="Monaco"
								class="mt-1"
							/>
						</div>
						<div>
							<Label>Country of Residence</Label>
							<CountrySelect
								bind:value={residenceCountry}
								placeholder="Select country..."
								name="residence_country"
								class="mt-1"
							/>
						</div>
					</div>

					<!-- Hidden full address for database -->
					<input type="hidden" name="address" value={fullAddress} />

					<div class="pt-2">
						<button
							type="submit"
							disabled={isSubmitting}
							class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
						>
							{isSubmitting ? 'Saving...' : 'Save Changes'}
						</button>
					</div>
				</form>
			</div>
		</div>
	{/if}

	<!-- Notifications Tab -->
	{#if activeTab === 'notifications'}
		<form
			method="POST"
			action="?/updateNotifications"
			use:enhance={() => {
				isSubmitting = true;
				return async ({ update }) => {
					await invalidateAll();
					await update();
					isSubmitting = false;
				};
			}}
			class="space-y-6"
		>
			<!-- Event Notifications -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center gap-3">
					<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100">
						<Calendar class="h-5 w-5 text-blue-600" />
					</div>
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Event Notifications</h2>
						<p class="text-sm text-slate-500">Control emails about events and RSVPs</p>
					</div>
				</div>

				<div class="space-y-3">
					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">RSVP Confirmations</p>
							<p class="text-sm text-slate-500">Receive confirmation when you RSVP to an event</p>
						</div>
						<input
							type="checkbox"
							name="email_event_rsvp_confirmation"
							checked={notificationPrefs?.email_event_rsvp_confirmation}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Event Reminders</p>
							<p class="text-sm text-slate-500">Get reminded before events you're attending</p>
						</div>
						<input
							type="checkbox"
							name="email_event_reminder"
							checked={notificationPrefs?.email_event_reminder}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Event Updates</p>
							<p class="text-sm text-slate-500">Be notified of changes to events you're attending</p>
						</div>
						<input
							type="checkbox"
							name="email_event_updates"
							checked={notificationPrefs?.email_event_updates}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Waitlist Promotions</p>
							<p class="text-sm text-slate-500">Get notified when you're promoted from a waitlist</p>
						</div>
						<input
							type="checkbox"
							name="email_waitlist_promotion"
							checked={notificationPrefs?.email_waitlist_promotion}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>
				</div>
			</div>

			<!-- Membership Notifications -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center gap-3">
					<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-green-100">
						<CreditCard class="h-5 w-5 text-green-600" />
					</div>
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Membership & Payments</h2>
						<p class="text-sm text-slate-500">Notifications about your membership and dues</p>
					</div>
				</div>

				<div class="space-y-3">
					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Dues Reminders</p>
							<p class="text-sm text-slate-500">Receive reminders when membership dues are due</p>
						</div>
						<input
							type="checkbox"
							name="email_dues_reminder"
							checked={notificationPrefs?.email_dues_reminder}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Payment Confirmations</p>
							<p class="text-sm text-slate-500">Receive confirmation when payments are recorded</p>
						</div>
						<input
							type="checkbox"
							name="email_payment_confirmation"
							checked={notificationPrefs?.email_payment_confirmation}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Membership Updates</p>
							<p class="text-sm text-slate-500">Important updates about your membership status</p>
						</div>
						<input
							type="checkbox"
							name="email_membership_updates"
							checked={notificationPrefs?.email_membership_updates}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>
				</div>
			</div>

			<!-- General Notifications -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center gap-3">
					<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-100">
						<Megaphone class="h-5 w-5 text-purple-600" />
					</div>
					<div>
						<h2 class="text-lg font-semibold text-slate-900">News & Updates</h2>
						<p class="text-sm text-slate-500">Stay informed about Monaco USA activities</p>
					</div>
				</div>

				<div class="space-y-3">
					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Announcements</p>
							<p class="text-sm text-slate-500">Important announcements from Monaco USA</p>
						</div>
						<input
							type="checkbox"
							name="email_announcements"
							checked={notificationPrefs?.email_announcements}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div class="flex-1">
							<p class="font-medium text-slate-900">Newsletter</p>
							<p class="text-sm text-slate-500">Receive the Monaco USA newsletter</p>
						</div>
						<input
							type="checkbox"
							name="email_newsletter"
							checked={notificationPrefs?.email_newsletter}
							class="h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500"
						/>
					</label>
				</div>
			</div>

			<div class="flex justify-end">
				<button
					type="submit"
					disabled={isSubmitting}
					class="rounded-lg bg-monaco-600 px-6 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
				>
					{isSubmitting ? 'Saving...' : 'Save Notification Preferences'}
				</button>
			</div>
		</form>

		<!-- Directory Privacy -->
		<form
			method="POST"
			action="?/updateDirectoryPrivacy"
			use:enhance={() => {
				isSubmitting = true;
				return async ({ update }) => {
					await invalidateAll();
					await update();
					isSubmitting = false;
				};
			}}
			class="mt-6"
		>
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center gap-3">
					<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-slate-100">
						<Eye class="h-5 w-5 text-slate-600" />
					</div>
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Directory Privacy</h2>
						<p class="text-sm text-slate-500">Control what other members can see in the directory</p>
					</div>
				</div>

				<div class="space-y-3">
					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Email Address</p>
							<p class="text-sm text-slate-500">Show your email in the member directory</p>
						</div>
						<input
							type="checkbox"
							name="show_email"
							checked={data.directoryPrivacy?.show_email !== false}
							class="h-4 w-4 rounded border-slate-300 text-monaco-600"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Phone Number</p>
							<p class="text-sm text-slate-500">Show your phone number in the member directory</p>
						</div>
						<input
							type="checkbox"
							name="show_phone"
							checked={data.directoryPrivacy?.show_phone !== false}
							class="h-4 w-4 rounded border-slate-300 text-monaco-600"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Address</p>
							<p class="text-sm text-slate-500">Show your address in the member directory</p>
						</div>
						<input
							type="checkbox"
							name="show_address"
							checked={data.directoryPrivacy?.show_address === true}
							class="h-4 w-4 rounded border-slate-300 text-monaco-600"
						/>
					</label>

					<label class="flex items-center justify-between rounded-lg border border-slate-200 p-4">
						<div>
							<p class="font-medium text-slate-900">Nationality</p>
							<p class="text-sm text-slate-500">Show your nationality flags in the member directory</p>
						</div>
						<input
							type="checkbox"
							name="show_nationality"
							checked={data.directoryPrivacy?.show_nationality !== false}
							class="h-4 w-4 rounded border-slate-300 text-monaco-600"
						/>
					</label>
				</div>

				<p class="mt-3 text-xs text-slate-400">
					Board members and admins can always see all fields regardless of these settings.
				</p>

				<div class="mt-4 flex justify-end">
					<button
						type="submit"
						disabled={isSubmitting}
						class="rounded-lg bg-monaco-600 px-6 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{isSubmitting ? 'Saving...' : 'Save Privacy Settings'}
					</button>
				</div>
			</div>
		</form>
	{/if}

	<!-- Account Tab -->
	{#if activeTab === 'account'}
		<div class="space-y-6">
			<!-- Monaco USA Email (for board/admin only) -->
			{#if data.hasMonacoEmailAccount && data.monacoEmail}
				<div class="glass-card border-2 border-monaco-200 p-6">
					<div class="mb-4 flex items-center gap-3">
						<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-monaco-100">
							<Mail class="h-5 w-5 text-monaco-600" />
						</div>
						<div>
							<h2 class="text-lg font-semibold text-slate-900">Monaco USA Email</h2>
							<p class="text-sm text-slate-500">Manage your @monacousa.org email account</p>
						</div>
					</div>

					<div class="mb-4 rounded-lg bg-monaco-50 p-4">
						<div class="flex items-center gap-2">
							<Mail class="h-4 w-4 text-monaco-600" />
							<span class="font-medium text-monaco-800">{data.monacoEmail}</span>
						</div>
						<p class="mt-1 text-xs text-monaco-600">
							Access your email at <a href="https://mail.monacousa.org" target="_blank" class="underline">mail.monacousa.org</a>
						</p>
					</div>

					<form
						method="POST"
						action="?/updateMonacoEmailPassword"
						use:enhance={() => {
							isSubmitting = true;
							return async ({ update }) => {
								await invalidateAll();
								await update();
								isSubmitting = false;
							};
						}}
						class="space-y-4"
					>
						<input type="hidden" name="monaco_email" value={data.monacoEmail} />

						<div>
							<Label for="monaco_new_password">New Email Password</Label>
							<div class="relative mt-1">
								<Input
									type={showPassword ? 'text' : 'password'}
									id="monaco_new_password"
									name="monaco_new_password"
									placeholder="Enter new email password"
									required
									minlength={8}
									class="pr-10"
								/>
								<button
									type="button"
									onclick={() => (showPassword = !showPassword)}
									class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
								>
									{#if showPassword}
										<EyeOff class="h-4 w-4" />
									{:else}
										<Eye class="h-4 w-4" />
									{/if}
								</button>
							</div>
						</div>

						<div>
							<Label for="monaco_confirm_password">Confirm New Password</Label>
							<div class="relative mt-1">
								<Input
									type={showConfirmPassword ? 'text' : 'password'}
									id="monaco_confirm_password"
									name="monaco_confirm_password"
									placeholder="Confirm new password"
									required
									minlength={8}
									class="pr-10"
								/>
								<button
									type="button"
									onclick={() => (showConfirmPassword = !showConfirmPassword)}
									class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
								>
									{#if showConfirmPassword}
										<EyeOff class="h-4 w-4" />
									{:else}
										<Eye class="h-4 w-4" />
									{/if}
								</button>
							</div>
							<p class="mt-1 text-xs text-slate-500">
								Password must be at least 8 characters long.
							</p>
						</div>

						<button
							type="submit"
							disabled={isSubmitting}
							class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
						>
							{isSubmitting ? 'Updating...' : 'Update Email Password'}
						</button>
					</form>
				</div>
			{/if}

			<!-- Email Address -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center gap-3">
					<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100">
						<Mail class="h-5 w-5 text-blue-600" />
					</div>
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Email Address</h2>
						<p class="text-sm text-slate-500">Update your email address</p>
					</div>
				</div>

				<form
					method="POST"
					action="?/updateEmail"
					use:enhance={() => {
						isSubmitting = true;
						return async ({ update }) => {
							await invalidateAll();
							await update();
							isSubmitting = false;
						};
					}}
					class="space-y-4"
				>
					<div>
						<Label for="current_email">Current Email</Label>
						<Input
							type="email"
							id="current_email"
							value={member?.email || ''}
							disabled
							class="mt-1 bg-slate-50"
						/>
					</div>

					<div>
						<Label for="email">New Email Address</Label>
						<Input
							type="email"
							id="email"
							name="email"
							placeholder="Enter new email address"
							class="mt-1"
						/>
						<p class="mt-1 text-xs text-slate-500">
							A verification link will be sent to your new email address.
						</p>
					</div>

					<button
						type="submit"
						disabled={isSubmitting}
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{isSubmitting ? 'Updating...' : 'Update Email'}
					</button>
				</form>
			</div>

			<!-- Password -->
			<div class="glass-card p-6">
				<div class="mb-4 flex items-center gap-3">
					<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-100">
						<Lock class="h-5 w-5 text-amber-600" />
					</div>
					<div>
						<h2 class="text-lg font-semibold text-slate-900">Password</h2>
						<p class="text-sm text-slate-500">Change your account password</p>
					</div>
				</div>

				<form
					method="POST"
					action="?/updatePassword"
					use:enhance={() => {
						isSubmitting = true;
						return async ({ update }) => {
							await invalidateAll();
							await update();
							isSubmitting = false;
						};
					}}
					class="space-y-4"
				>
					<div>
						<Label for="current_password">Current Password</Label>
						<div class="relative mt-1">
							<Input
								type={showCurrentPassword ? 'text' : 'password'}
								id="current_password"
								name="current_password"
								placeholder="Enter your current password"
								required
								class="pr-10"
							/>
							<button
								type="button"
								onclick={() => (showCurrentPassword = !showCurrentPassword)}
								class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
							>
								{#if showCurrentPassword}
									<EyeOff class="h-4 w-4" />
								{:else}
									<Eye class="h-4 w-4" />
								{/if}
							</button>
						</div>
					</div>

					<div>
						<Label for="new_password">New Password</Label>
						<div class="relative mt-1">
							<Input
								type={showPassword ? 'text' : 'password'}
								id="new_password"
								name="new_password"
								placeholder="Enter new password"
								required
								minlength={8}
								class="pr-10"
							/>
							<button
								type="button"
								onclick={() => (showPassword = !showPassword)}
								class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
							>
								{#if showPassword}
									<EyeOff class="h-4 w-4" />
								{:else}
									<Eye class="h-4 w-4" />
								{/if}
							</button>
						</div>
					</div>

					<div>
						<Label for="confirm_password">Confirm New Password</Label>
						<div class="relative mt-1">
							<Input
								type={showConfirmPassword ? 'text' : 'password'}
								id="confirm_password"
								name="confirm_password"
								placeholder="Confirm new password"
								required
								minlength={8}
								class="pr-10"
							/>
							<button
								type="button"
								onclick={() => (showConfirmPassword = !showConfirmPassword)}
								class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
							>
								{#if showConfirmPassword}
									<EyeOff class="h-4 w-4" />
								{:else}
									<Eye class="h-4 w-4" />
								{/if}
							</button>
						</div>
						<p class="mt-1 text-xs text-slate-500">
							Password must be at least 8 characters long.
						</p>
					</div>

					<button
						type="submit"
						disabled={isSubmitting}
						class="rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{isSubmitting ? 'Updating...' : 'Change Password'}
					</button>
				</form>
			</div>

			<!-- Member Info (Read Only) -->
			<div class="glass-card p-6">
				<h2 class="mb-4 text-lg font-semibold text-slate-900">Membership Information</h2>
				<div class="grid gap-4 sm:grid-cols-2">
					<div>
						<p class="text-sm text-slate-500">Member ID</p>
						<p class="font-medium text-slate-900">{member?.member_id || 'N/A'}</p>
					</div>
					<div>
						<p class="text-sm text-slate-500">Membership Type</p>
						<p class="font-medium text-slate-900">{member?.membership_type?.display_name || 'N/A'}</p>
					</div>
					<div>
						<p class="text-sm text-slate-500">Member Since</p>
						<p class="font-medium text-slate-900">
							{member?.member_since
								? new Date(member.member_since).toLocaleDateString('en-US', {
										year: 'numeric',
										month: 'long',
										day: 'numeric'
									})
								: 'N/A'}
						</p>
					</div>
					<div>
						<p class="text-sm text-slate-500">Status</p>
						<p class="font-medium text-slate-900">{member?.membership_status?.display_name || 'N/A'}</p>
					</div>
				</div>
			</div>
		</div>
	{/if}
</div>
