<script lang="ts">
	import { browser } from "$app/environment";
	import { fade } from "svelte/transition";
	import type { PageData } from "../../routes/$types.js"; // Approximate type; adjust if needed
	import Container from "./Container.svelte";

	let {
		data,
		isWon,
		blurChapter = false,
	}: { data: PageData; 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) => 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;
			(window as any).rybbit?.event("Copy Verse");
			setTimeout(() => {
				copied = false;
			}, 2000);
		});
	}
</script>

<Container class="w-full p-8 sm:p-12 bg-white/70 overflow-hidden">
	<blockquote
		class="text-xl sm:text-2xl font-triodion leading-relaxed text-gray-700 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! font-bold mt-8 bg-white/70 rounded-xl px-4 py-2"
			>
				{displayReference}
			</p>
		{/if}
	</div>
</Container>
