<template>
	<div class="faq-container">
		<!-- Accordion Layout -->
		<div
			v-if="layout === 'accordion'"
			class="border border-neutral-200 dark:border-neutral-800 rounded-xl overflow-hidden"
		>
			<div
				v-for="(item, index) in items"
				:key="index"
				class="faq-item border-b border-neutral-200 dark:border-neutral-800 last:border-b-0"
			>
				<!-- Question -->
				<button
					:aria-expanded="openIndexes.includes(index)"
					class="faq-question w-full flex items-center justify-between p-5 text-left hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors duration-200"
					@click="toggleItem(index)"
				>
					<span class="font-medium text-neutral-900 dark:text-white pr-4">
						{{ item.question }}
					</span>
					<UIcon
						name="i-lucide-chevron-down"
						class="w-5 h-5 text-neutral-500 dark:text-neutral-400 flex-shrink-0 transition-transform duration-300"
						:class="{ 'rotate-180': openIndexes.includes(index) }"
					/>
				</button>

				<!-- Answer -->
				<div
					ref="answerRefs"
					class="faq-answer overflow-hidden transition-all duration-300 ease-in-out"
					:style="{
						maxHeight: openIndexes.includes(index)
							? answerHeights[index] + 'px'
							: '0',
						opacity: openIndexes.includes(index) ? 1 : 0,
					}"
				>
					<div
						class="p-5 pt-0 text-neutral-600 dark:text-neutral-400 prose prose-neutral dark:prose-invert max-w-none"
					>
						{{ item.answer }}
					</div>
				</div>
			</div>
		</div>

		<!-- Two-Column Layout -->
		<div
			v-else-if="layout === 'two-column'"
			class="grid md:grid-cols-2 gap-x-12 gap-y-8"
		>
			<!-- Questions Column -->
			<div class="questions-column space-y-4">
				<div
					v-for="(item, index) in items"
					:key="index"
					class="font-medium text-neutral-900 dark:text-white"
				>
					{{ item.question }}
				</div>
			</div>

			<!-- Answers Column -->
			<div class="answers-column space-y-4">
				<div
					v-for="(item, index) in items"
					:key="index"
					class="text-neutral-600 dark:text-neutral-400"
				>
					{{ item.answer }}
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
const props = defineProps({
	/** Array of FAQ items [{ question, answer, open? }] */
	items: {
		type: Array,
		default: () => [
			{
				question: "What is this?",
				answer: "This is a frequently asked question.",
			},
		],
	},
	/** Layout type: 'accordion' or 'two-column' */
	layout: {
		type: String,
		default: "accordion",
		validator: (value) => ["accordion", "two-column"].includes(value),
	},
	/** Whether the first item should start open */
	openFirst: {
		type: Boolean,
		default: false,
	},
	/** Whether multiple items can be open at once */
	allowMultiple: {
		type: Boolean,
		default: false,
	},
});

// Track which items are open
const openIndexes = ref([]);

// Track answer heights for smooth transitions
const answerHeights = ref({});

// Initialize open state based on props
onMounted(() => {
	// Set initial open indexes
	const initialOpen = [];
	props.items.forEach((item, index) => {
		if (item.open || (props.openFirst && index === 0)) {
			initialOpen.push(index);
		}
	});
	openIndexes.value = initialOpen;

	// Calculate initial heights after DOM update
	nextTick(() => {
		calculateHeights();
	});
});

// Recalculate heights on window resize
onMounted(() => {
	if (typeof window !== "undefined") {
		window.addEventListener("resize", calculateHeights);
	}
});

onUnmounted(() => {
	if (typeof window !== "undefined") {
		window.removeEventListener("resize", calculateHeights);
	}
});

// Watch for items changes to recalculate heights
watch(
	() => props.items,
	() => {
		nextTick(() => {
			calculateHeights();
		});
	},
	{ deep: true }
);

function calculateHeights() {
	// Need to access DOM elements - we'll estimate based on content
	// This is a simplified approach - in production, you might measure actual heights
	props.items.forEach((item, index) => {
		// Estimate height based on answer length (rough approximation)
		const answerLength = item.answer?.length || 0;
		// Average characters per line ~50, line height ~1.6, padding ~20px
		const lines = Math.ceil(answerLength / 50);
		const estimatedHeight = lines * 28 + 40; // ~28px per line + padding
		answerHeights.value[index] = Math.max(estimatedHeight, 100);
	});
}

function toggleItem(index) {
	const isOpen = openIndexes.value.includes(index);

	if (isOpen) {
		// Close the item
		openIndexes.value = openIndexes.value.filter((i) => i !== index);
	} else {
		// Open the item
		if (props.allowMultiple) {
			// Allow multiple - just add to open indexes
			openIndexes.value = [...openIndexes.value, index];
		} else {
			// Only one at a time - close others and open this one
			openIndexes.value = [index];
		}
	}

	// Recalculate heights after toggle
	nextTick(() => {
		calculateHeights();
	});
}
</script>
