<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { authClient } from '$lib/auth-client';
	{{#if (eq api "orpc")}}
	import { orpc } from '$lib/orpc';
	import { createQuery } from '@tanstack/svelte-query';
	{{/if}}
	{{#if (eq payments "polar")}}
	let customerState: any = null;
	{{/if}}

	const sessionQuery = authClient.useSession();

	{{#if (eq api "orpc")}}
	const privateDataQuery = createQuery(orpc.privateData.queryOptions());
    {{/if}}

	onMount(() => {
		const { data: session, isPending } = $sessionQuery;
		if (!session && !isPending) {
			goto('/login');
		}
		{{#if (eq payments "polar")}}
		if (session) {
			authClient.customer.state().then(({ data }) => {
				customerState = data;
			});
		}
		{{/if}}
	});
</script>

{#if $sessionQuery.isPending}
	<div>Loading...</div>
{:else if !$sessionQuery.data}
{:else}
	<div>
		<h1>Dashboard</h1>
		<p>Welcome {$sessionQuery.data.user.name}</p>
		{{#if (eq api "orpc")}}
		<p>API: {$privateDataQuery.data?.message}</p>
		{{/if}}
		{{#if (eq payments "polar")}}
		<p>Plan: {customerState?.activeSubscriptions?.length > 0 ? "Pro" : "Free"}</p>
		{#if customerState?.activeSubscriptions?.length > 0}
			<button onclick={async () => await authClient.customer.portal()}>
				Manage Subscription
			</button>
		{:else}
			<button onclick={async () => await authClient.checkout({ slug: "pro" })}>
				Upgrade to Pro
			</button>
		{/if}
		{{/if}}
	</div>
{/if}
