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

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

	import Button from '$lib/components/ui/Button.svelte';
	import Input from '$lib/components/ui/Input.svelte';
	import { page } from '$app/stores';

	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 /><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
		>
			<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>
					<Input 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" />
				</div>
			</div>
			<Button class="w-full sm:w-44" variant="brand">Valider</Button>
		</form>
	{:else}
		<div class="flex items-center justify-between flex-col sm:flex-row gap-2">
			<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 type="button" onClick={() => router.push(getURL(`/dashboard/puzzles`))}>
				Retour aux puzzles
			</Button> -->
			<Button href="/dashboard/chapters/{chapterId}" class="w-full sm:w-44" variant="brand">Retour aux puzzles</Button>
		</div>
	{/if}
</div>
