<script lang="ts">
	import { thumbnail } from '$lib/Utility/image.js';
	import type { Badge } from '$lib/Database/userBadges';
	import { cdn } from '$lib/Utility/image';
	import { databaseTimeToDate } from '$lib/Utility/time';
	import locale from '$stores/locale';
	import { onMount } from 'svelte';
	import { cubicOut } from 'svelte/easing';
	import { tweened } from 'svelte/motion';

	export let selectedBadge: Badge | undefined;

	let badgeReference: HTMLImageElement;
	const mouse = tweened(
		{ x: 0, y: 0 },
		{
			duration: 300 * 1.75,
			easing: cubicOut
		}
	);

	const handleMouseMove = (event: MouseEvent) => {
		const boundingRectangle = badgeReference.getBoundingClientRect();
		const factor = 1.25;
		const limit = 300 * 1.75;

		if ($mouse.x === 0 && $mouse.y === 0) $mouse = { x: event.clientX, y: event.clientY };

		$mouse.x +=
			(-(event.clientX - boundingRectangle.left - boundingRectangle.width / 2) - $mouse.x) * factor;
		$mouse.y +=
			(-(event.clientY - boundingRectangle.top - boundingRectangle.height / 2) - $mouse.y) * factor;
		$mouse.x = Math.max(Math.min($mouse.x, limit), -limit);
		$mouse.y = Math.max(Math.min($mouse.y, limit), -limit);
	};

	const handleMouseLeave = () => {
		$mouse = { x: 0, y: 0 };
	};

	$: {
		if (selectedBadge && selectedBadge.image) {
			const image = new Image();

			image.src = cdn(selectedBadge.image) || '';
			image.onload = () => {
				badgeReference.src = image.src;
			};
		}
	}

	onMount(() => {
		const handleClickOutside = (event: any) => {
			if (event.target.classList.contains('popup')) selectedBadge = undefined;
		};

		document.addEventListener('click', handleClickOutside);

		return () => {
			document.removeEventListener('click', handleClickOutside);
		};
	});

	const classifySource = (source: string) => {
		let name = source;
		const sourceLower = source.toLowerCase();

		if (sourceLower.includes('pixiv.net')) {
			name = 'Pixiv';
		} else if (sourceLower.includes('twitter.com') || sourceLower.includes('x.com')) {
			name = 'X (Twitter)';
		} else if (sourceLower.includes('zerochan.net')) {
			name = 'Zerochan';
		} else if (sourceLower.includes('imgur.com')) {
			name = 'Imgur';
		}

		return `<a href="${source}" target="_blank">${name}</a>`;
	};

	const classifyDesigner = (designer: string) => {
		let name = designer;
		let userLink = designer;
		const designerLower = designer.toLowerCase();
		const anilistUser = designer.match(/https?:\/\/anilist\.co\/user\/([^/]+)\/?/);

		if (anilistUser) {
			name = anilistUser[1];
		} else if (designerLower.startsWith('@')) {
			name = designer.replace('@', '');
			userLink = `https://anilist.co/user/${name}/`;
		} else if (!designerLower.startsWith('http')) {
			userLink = `https://anilist.co/user/${name}/`;
		}

		return `<a href="${userLink}" target="_blank">@${name}</a>`;
	};
</script>

{#if selectedBadge}
	<div class="badge-preview">
		{#if selectedBadge.image}
			<div
				on:mousemove={handleMouseMove}
				on:mouseleave={handleMouseLeave}
				role="img"
				class="badge-container"
			>
				<img
					src={cdn(thumbnail(selectedBadge.image))}
					bind:this={badgeReference}
					style="transform: perspective(1000px) rotateX({$mouse.y / 10}deg) rotateY({-$mouse.x /
						10}deg);"
					alt={selectedBadge.description}
				/>
			</div>

			<p />
		{/if}

		{#if selectedBadge.time}
			{$locale().dateFormatter(databaseTimeToDate(selectedBadge.time))}

			{#if (selectedBadge.designer || selectedBadge.source || selectedBadge.post) && !selectedBadge.description}
				<p />
			{:else if selectedBadge.description}
				<br />
			{/if}
		{/if}

		{#if selectedBadge.description}
			{selectedBadge.description}

			<p />
		{/if}

		{#if selectedBadge.designer}
			<b>Designer:</b>

			<!-- {#if selectedBadge.designer.startsWith('http')}
				<a href={selectedBadge.designer} target="_blank">
					{selectedBadge.designer}
				</a>
			{:else if selectedBadge.designer.startsWith('@')}
				<a href="https://anilist.co/user/{selectedBadge.designer.replace('@', '')}" target="_blank">
					{selectedBadge.designer}
				</a>
			{:else}
				{selectedBadge.designer}
			{/if} -->
			{@html classifyDesigner(selectedBadge.designer)}

			<br />
		{/if}

		{#if selectedBadge.post && selectedBadge.post !== '#'}
			<b>{selectedBadge.post.includes('forum') ? 'Forum' : 'Activity'}:</b>

			<a href={selectedBadge.post} target="_blank">
				{selectedBadge.post}
			</a>

			<br />
		{/if}

		{#if selectedBadge.source}
			<b>Source:</b>

			{#if selectedBadge.source.startsWith('http')}
				<!-- <a href={selectedBadge.source} target="_blank">
					{selectedBadge.source}
				</a> -->
				{@html classifySource(selectedBadge.source)}
			{:else}
				{selectedBadge.source}
			{/if}

			<br />
		{/if}

		{#if selectedBadge.category}
			<b>Category:</b>

			<a href={`?category=${selectedBadge.category}`} on:click={() => (selectedBadge = undefined)}>
				{selectedBadge.category}
			</a>

			<br />
		{/if}

		<b>SauceNAO:</b>
		<a href={`https://saucenao.com/search.php?url=${selectedBadge.image}`} target="_blank">
			Search
		</a>
	</div>
{/if}

<style>
	.badge-preview img {
		border-radius: 8px;
		max-width: 25vh;
		width: 100%;
	}

	.badge-container {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
