<template>
	<UModal v-model:open="isOpen">
		<!-- Trigger Slot -->
		<slot>
			<UButton
				:label="buttonProps.label"
				:color="buttonProps.color"
				:variant="buttonProps.variant"
				:size="buttonProps.size"
				:leading-icon="buttonProps.icon"
			/>
		</slot>

		<template #content>
			<div class="p-6">
				<!-- Header -->
				<header class="mb-6">
					<h3 class="text-xl font-semibold text-neutral-900 dark:text-white">
						{{ title }}
					</h3>
					<p class="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
						{{ description }}
					</p>
				</header>

				<!-- Cookie Categories -->
				<div class="space-y-4">
					<div
						v-for="category in categories"
						:key="category.id"
						class="p-4 rounded-xl border border-neutral-200 dark:border-neutral-700"
					>
						<div class="flex items-start justify-between gap-4">
							<div class="flex-1">
								<div class="flex items-center gap-2">
									<h4 class="font-medium text-neutral-900 dark:text-white">
										{{ category.name }}
									</h4>
									<UBadge
										v-if="category.required"
										label="Required"
										size="xs"
										variant="subtle"
									/>
								</div>
								<p class="mt-1 text-sm text-neutral-600 dark:text-neutral-400">
									{{ category.description }}
								</p>
							</div>
							<USwitch
								v-model="selections[category.id]"
								:disabled="category.required"
							/>
						</div>
					</div>
				</div>

				<!-- Actions -->
				<footer class="mt-6 flex flex-col sm:flex-row gap-3">
					<UButton
						label="Reject All"
						variant="ghost"
						color="neutral"
						class="flex-1"
						@click="rejectAll"
					/>
					<UButton
						label="Accept Selected"
						variant="outline"
						class="flex-1"
						@click="acceptSelected"
					/>
					<UButton
						label="Accept All"
						class="flex-1"
						@click="acceptAll"
					/>
				</footer>

				<!-- Policy Links -->
				<div class="mt-4 pt-4 border-t border-neutral-200 dark:border-neutral-700 text-center">
					<div class="flex justify-center gap-4 text-sm">
						<NuxtLink
							v-if="privacyLink"
							:to="privacyLink"
							class="text-primary-500 hover:underline"
						>
							Privacy Policy
						</NuxtLink>
						<NuxtLink
							v-if="cookieLink"
							:to="cookieLink"
							class="text-primary-500 hover:underline"
						>
							Cookie Policy
						</NuxtLink>
					</div>
				</div>
			</div>
		</template>
	</UModal>
</template>

<script setup>
const props = defineProps({
	/** v-model for modal visibility */
	modelValue: {
		type: Boolean,
		default: false,
	},
	/** Modal title */
	title: {
		type: String,
		default: 'Privacy Preferences',
	},
	/** Modal description */
	description: {
		type: String,
		default: 'We use cookies to enhance your browsing experience. You can choose which categories to allow.',
	},
	/** Cookie categories */
	categories: {
		type: Array,
		default: () => [
			{
				id: 'necessary',
				name: 'Necessary',
				description: 'Essential cookies required for the website to function properly.',
				required: true,
			},
			{
				id: 'analytics',
				name: 'Analytics',
				description: 'Cookies that help us understand how visitors interact with our website.',
				required: false,
			},
			{
				id: 'marketing',
				name: 'Marketing',
				description: 'Cookies used for advertising and promotional purposes.',
				required: false,
			},
			{
				id: 'preferences',
				name: 'Preferences',
				description: 'Cookies that remember your preferences and settings.',
				required: false,
			},
		],
	},
	/** Privacy policy link */
	privacyLink: {
		type: String,
		default: '/privacy',
	},
	/** Cookie policy link */
	cookieLink: {
		type: String,
		default: '/cookies',
	},
	/** Storage key for preferences */
	storageKey: {
		type: String,
		default: 'gdpr-preferences',
	},
	/** Button configuration object */
	button: {
		type: Object,
		default: () => ({}),
	},
});

const emit = defineEmits(['update:modelValue', 'accept', 'reject', 'save']);

// Support both v-model and self-managed state
const internalOpen = ref(false);
const isOpen = computed({
	get: () => props.modelValue !== undefined ? props.modelValue : internalOpen.value,
	set: (value) => {
		internalOpen.value = value;
		emit('update:modelValue', value);
	},
});

// Button props with defaults
const buttonProps = computed(() => ({
	label: props.button.label || 'Cookie Settings',
	color: props.button.color || 'neutral',
	variant: props.button.variant || 'outline',
	size: props.button.size || 'md',
	icon: props.button.icon || 'i-lucide-cookie',
}));

// Initialize selections
const selections = ref({});

onMounted(() => {
	// Load saved preferences
	const saved = localStorage.getItem(props.storageKey);
	if (saved) {
		selections.value = JSON.parse(saved);
	} else {
		// Default: required categories enabled
		props.categories.forEach((cat) => {
			selections.value[cat.id] = cat.required;
		});
	}
});

const savePreferences = (prefs) => {
	localStorage.setItem(props.storageKey, JSON.stringify(prefs));
	localStorage.setItem('cookie-consent', 'customized');
	emit('save', prefs);
	isOpen.value = false;
};

const acceptAll = () => {
	const prefs = {};
	props.categories.forEach((cat) => {
		prefs[cat.id] = true;
	});
	savePreferences(prefs);
	emit('accept');
};

const acceptSelected = () => {
	// Ensure required categories are always true
	const prefs = { ...selections.value };
	props.categories.forEach((cat) => {
		if (cat.required) {
			prefs[cat.id] = true;
		}
	});
	savePreferences(prefs);
};

const rejectAll = () => {
	const prefs = {};
	props.categories.forEach((cat) => {
		prefs[cat.id] = cat.required;
	});
	savePreferences(prefs);
	emit('reject');
};
</script>
