<script lang="ts">
	import { browser } from "$app/environment";
	import { fade } from "svelte/transition";
	import Container from "./Container.svelte";

	interface VerseDisplayData {
		dailyVerse: {
			date: string;
			reference: string;
			verseText: string;
		};
	}

	let {
		data,
		isWon,
		blurChapter = false,
	}: { data: VerseDisplayData; isWon: boolean; blurChapter?: boolean } = $props();
	let dailyVerse = $derived(data.dailyVerse);
	let displayReference = $derived(
		blurChapter
			? dailyVerse.reference
					.replace(/^Psalms /, "Psalm ")
					.replace(/\s(\d+):/, " ?:")
			: dailyVerse.reference.replace(/^Psalms /, "Psalm "),
	);
	let displayVerseText = $derived(
		dailyVerse.verseText
			.replace(/^([a-z])/, (c: string) => c.toUpperCase())
			.replace(/[,:;-—]$/, "..."),
	);

	let showReference = $state(false);
	let copied = $state(false);

	// Delay showing reference until GuessesTable animation completes
	$effect(() => {
		if (!isWon) {
			showReference = false;
			return;
		}

		// Check if user already won today (page reload case)
		const winTrackedKey = `bibdle-win-tracked-${dailyVerse.date}`;
		const alreadyWonToday =
			browser && localStorage.getItem(winTrackedKey) === "true";

		if (alreadyWonToday) {
			// User already won and is refreshing - show immediately
			showReference = true;
		} else {
			// User just won this session - delay for animation
			const animationDelay = 1800;
			const timeoutId = setTimeout(() => {
				showReference = true;
			}, animationDelay);

			return () => clearTimeout(timeoutId);
		}
	});

	function copyVerse() {
		navigator.clipboard.writeText(displayVerseText).then(() => {
			copied = true;
			setTimeout(() => {
				copied = false;
			}, 2000);
		});
	}
</script>

<Container
	class="w-full p-8 sm:p-12 bg-white/70 dark:bg-black/30 overflow-hidden"
>
	<blockquote
		class="text-xl sm:text-2xl font-triodion leading-relaxed text-gray-700 dark:text-gray-200 text-center"
	>
		{displayVerseText}
	</blockquote>
	<div
		class="transition-all duration-500 ease-in-out overflow-hidden"
		style="max-height: {showReference ? '200px' : '0px'};"
	>
		{#if showReference}
			<p
				transition:fade={{ duration: 400 }}
				class="text-center text-lg! big-text text-green-600! dark:text-green-400! font-bold mt-8 bg-white/70 dark:bg-black/50 rounded-xl px-4 py-2"
			>
				{displayReference}
			</p>
		{/if}
	</div>
</Container>
