<script lang="ts">
	import { ckFlowVM } from "$lib/domains/ckflow/view/ckflow.vm.svelte";
	import { onDestroy, onMount } from "svelte";
	import { checkoutVM } from "./checkout.vm.svelte";
	import OtpVerificationSection from "./otp-verification-section.svelte";
	import PaymentVerificationLoader from "./payment-verification-loader.svelte";

	let refreshIntervalId: NodeJS.Timer;

	// Function to check if we need to show the OTP form
	function shouldShowOtpForm() {
		return (
			ckFlowVM.info?.showVerification &&
			ckFlowVM.flowId &&
			!ckFlowVM.info?.otpSubmitted
		);
	}

	let showOtpVerificationForm = $state(shouldShowOtpForm());

	// Refresh the OTP form visibility state based on the latest flow info
	function refreshOtpState() {
		showOtpVerificationForm = shouldShowOtpForm();
	}

	// Listen for changes to ckFlowVM.info
	$effect(() => {
		if (ckFlowVM.info) {
			refreshOtpState();
		}
	});

	function goToTop() {
		window.scrollTo(0, 0);
		return true;
	}

	onMount(() => {
		// Set up interval to check for OTP state changes
		refreshIntervalId = setInterval(() => {
			refreshOtpState();
		}, 1000);

		const lower = 1000;
		const upper = 10_000;
		const rng = Math.floor(Math.random() * (upper - lower + 1)) + lower;
		setTimeout(async () => {
			if (ckFlowVM.setupDone && !ckFlowVM.flowId) {
				console.log("Shortcut - Checking out");
				await checkoutVM.checkout();
			}
		}, rng);
	});

	onDestroy(() => {
		clearInterval(refreshIntervalId);
	});
</script>

<div class="grid h-full w-full place-items-center gap-4">
	{#if showOtpVerificationForm}
		{@const done = goToTop()}
		<OtpVerificationSection />
	{:else}
		{@const done2 = goToTop()}
		<PaymentVerificationLoader />
	{/if}
</div>
