<script lang="ts">
	import { formatZoned } from '$lib/utils/date';

	import { Button } from '$lib/components/ui/button';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';

	import * as m from '$lib/paraglide/messages';

	import { SIGNUP_URL, getSupporterPrice } from './config';
	import { clearLicense, isSupporter, storedLicenseKey, supporterState, verifyKey } from './store';

	interface Props {
		open?: boolean;
	}

	let { open = $bindable(false) }: Props = $props();

	const price = getSupporterPrice();

	// Prefill with the stored key so an existing subscriber sees their key.
	let keyInput = $state('');
	let submitting = $state(false);
	let localError = $state<string | null>(null);

	$effect(() => {
		if (open) {
			keyInput = $storedLicenseKey;
			localError = null;
		}
	});

	async function submit(e: SubmitEvent) {
		e.preventDefault();
		if (submitting) return;
		submitting = true;
		localError = null;
		const result = await verifyKey(keyInput);
		submitting = false;
		if (result.valid) {
			// close shortly so the success state is visible for a beat
			setTimeout(() => (open = false), 700);
		} else {
			localError = result.error ?? m.supporter_key_invalid();
		}
	}

	function removeKey() {
		clearLicense();
		keyInput = '';
	}

	let expiresLabel = $derived.by(() => {
		const exp = $supporterState.expires;
		if ($supporterState.status !== 'valid') return null;
		if (!exp) return m.supporter_lifetime();
		return m.supporter_active_until({ date: formatZoned(new Date(exp), 'UTC', 'd LLL yyyy') });
	});
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-md">
		<Dialog.Header>
			<Dialog.Title>{m.supporter_dialog_title()}</Dialog.Title>
			<Dialog.Description>
				{m.supporter_dialog_desc()}
			</Dialog.Description>
		</Dialog.Header>

		{#if $isSupporter && $supporterState.status === 'valid'}
			<div
				class="flex items-start gap-3 rounded-lg border border-emerald-300/60 bg-emerald-50 px-3.5 py-3 text-sm text-emerald-800 dark:border-emerald-800/50 dark:bg-emerald-950/30 dark:text-emerald-200"
			>
				<svg
					class="mt-0.5 h-5 w-5 shrink-0"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
					stroke-width="2"
				>
					<path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4" />
					<circle cx="12" cy="12" r="9" />
				</svg>
				<div>
					<p class="font-semibold">{m.supporter_extras_active()}</p>
					{#if expiresLabel}<p class="text-xs opacity-80">{expiresLabel}</p>{/if}
				</div>
			</div>
		{/if}

		<form onsubmit={submit} class="grid gap-3">
			<div class="grid gap-1.5">
				<Label for="license-key">{m.supporter_access_key()}</Label>
				<Input
					id="license-key"
					bind:value={keyInput}
					placeholder="DRZ-XXXX-XXXX-XXXX"
					autocomplete="off"
					spellcheck={false}
					class="font-mono tracking-wide"
				/>
			</div>

			{#if localError}
				<p class="text-sm text-destructive">{localError}</p>
			{:else if $supporterState.status === 'error'}
				<p class="text-sm text-destructive">
					{m.supporter_server_unreachable()}
				</p>
			{/if}

			<Button type="submit" disabled={submitting || !keyInput.trim()}>
				{#if submitting}{m.supporter_verifying()}{:else}{m.supporter_unlock_button()}{/if}
			</Button>
		</form>

		<Dialog.Footer class="flex-col items-stretch gap-2 sm:flex-col sm:items-stretch">
			{#if $isSupporter}
				<button
					type="button"
					class="cursor-pointer text-center text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
					onclick={removeKey}
				>
					{m.supporter_remove_key()}
				</button>
			{:else}
				<p class="text-center text-xs text-muted-foreground">
					{m.supporter_no_key_yet()}
					<a
						href={SIGNUP_URL}
						target="_blank"
						rel="noopener"
						class="font-semibold text-primary underline-offset-2 hover:underline"
					>
						{m.supporter_support_from({ price })}
					</a>
				</p>
			{/if}
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
