<script lang="ts">
	import type { PageData } from './$types';

	import { enhance } from '$app/forms';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';

	import { marked, type MarkedOptions } from 'marked';

	import { cn } from '$lib';
	import { addToast } from '$lib/components/Toaster.svelte';
	import Button from '$lib/components/ui/Button.svelte';
	import Input from '$lib/components/ui/Input.svelte';

	export let data: PageData;

	$: puzzle = data.puzzle;
	$: chapterId = $page.params.chapterId;

	const renderer = new marked.Renderer();

	renderer.link = (href, title, text) => {
		const html = marked.Renderer.prototype.link.call(renderer, href, title, text);
		return html.replace(
			/^<a /,
			'<a target="_blank" rel="nofollow" class="text-brand hover:text-brand/90" '
		);
	};

	renderer.br = () => {
		return '<br />';
	};

	renderer.codespan = (code) => {
		return `<code class="cursor-default select-none text-transparent transition-colors delay-150 hover:text-highlight-secondary">${code}</code>`;
	};

	const options: MarkedOptions = {
		breaks: true,
		renderer,
		gfm: true
	};
</script>

<div class="flex h-full w-full flex-col justify-between gap-4">
	<h1 class="text-2xl font-bold sm:text-3xl md:text-4xl">
		{puzzle.name}
		<span class="text-xl text-highlight-secondary">({puzzle.scoreMax} points)</span>
	</h1>
	<div class="h-screen w-full overflow-y-auto break-all font-fira text-xs sm:text-base">
		{@html marked(puzzle.content, options)}
	</div>
	{#if !puzzle.score}
		<form
			class="flex w-full flex-col items-end justify-between gap-2 sm:flex-row"
			method="POST"
			enctype="multipart/form-data"
			use:enhance={async ({ formData, cancel }) => {
				if (formData.get('answer') === '') {
					addToast({
						data: {
							title: 'Réponse vide',
							description: 'Vous devez entrer une réponse'
						},
						closeDelay: 5000
					});
					return cancel();
				}

				const res = await fetch(data.url, {
					method: 'POST',
					body: formData,
					headers: {
						Authorization: `Bearer ${data.session}`
					}
				});

				if (res.ok || res.status === 403 || res.status === 406 || res.status === 423) {
					const data = res.ok || res.status === 406 ? await res.json() : null;

					if (data && data.score) {
						addToast({
							data: {
								title: 'Bravo !',
								description: `Vous avez trouvé la bonne réponse en ${data.tries} tentative${
									data.tries > 1 ? 's' : ''
								} !`
							}
						});
					} else if (data && data.tries)
						addToast({
							data: {
								title: 'Mauvaise réponse',
								description: `Vous avez effectué ${data.tries} tentative${
									data.tries > 1 ? 's' : ''
								} !`
							}
						});
					else if (res.ok && data?.success)
						addToast({
							data: {
								title: 'Bravo !',
								description: `Vous avez trouvé la bonne réponse !`
							}
						});
					else if (res.status === 423)
						addToast({
							data: {
								title: 'Puzzle désactivé',
								description: `Ce puzzle est désactivé pour le moment.`
							}
						});
				}

				return async ({ result }) => {
					if (result.type === 'redirect') {
						goto(result.location, {
							invalidateAll: true
						});
					}
				};
			}}
		>
			<div class="flex w-full flex-col gap-2 sm:flex-row sm:gap-4">
				<div class="flex flex-col gap-y-2">
					<label for="answer">Réponse</label>
					<textarea
						class={cn(
							'flex h-10 w-full rounded-md border border-primary-600 bg-highlight-primary px-3 py-2 text-sm ring-offset-highlight-primary file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted focus:bg-primary-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50'
						)}
						name="answer"
						placeholder="CAPTAIN, LOOK !"
					/>
				</div>
				<div class="flex flex-col gap-y-2">
					<label for="code_file">Fichier</label>
					<Input name="code_file" type="file" accept=".py,.js,.ts,.java,.rs,.c" />
				</div>
			</div>
			<Button class="w-full sm:w-44" variant="brand">Valider</Button>
		</form>
	{:else}
		<div class="flex flex-col items-center justify-between gap-2 sm:flex-row">
			<div class="flex items-center gap-2">
				<p>
					Tentative{puzzle.tries && puzzle.tries > 1 ? 's' : ''} :{' '}
					<span class="text-brand-accent">{puzzle.tries}</span>
				</p>
				<p>
					Score : <span class="text-brand-accent">{puzzle.score}</span>
				</p>
			</div>
			<Button href="/dashboard/chapters/{chapterId}" class="w-full sm:w-44" variant="brand">
				Retour aux puzzles
			</Button>
		</div>
	{/if}
</div>
