<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 root from '$lib/Utility/root';
	import ParallaxImage from '$lib/Image/ParallaxImage.svelte';

	export let selectedBadge: Badge | undefined;
	export let onNext: () => void = () => {};
	export let onPrevious: () => void = () => {};
	export let hasNext: boolean;
	export let hasPrevious: boolean;

	let source = cdn(thumbnail(selectedBadge?.image || '')) || '';
	let badgeReference: HTMLImageElement;

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

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

	$: {
		if (selectedBadge)
			fetch(root(`/api/badges?incrementClickCount=${selectedBadge.id}`), {
				method: 'PUT'
			});
	}

	onMount(() => {
		badgeReference = document.querySelector('.badge-container-image') as HTMLImageElement;

		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';
		} else if (sourceLower.includes('lofter.com')) {
			name = 'Lofter';
		}

		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>`;
	};

	const onClick = (event: MouseEvent) => {
		event.preventDefault();

		if (
			event.clientX <
			badgeReference.getBoundingClientRect().left + badgeReference.getBoundingClientRect().width / 2
		) {
			onPrevious();
		} else {
			onNext();
		}
	};
</script>

{#if selectedBadge}
	<div class="badge-preview">
		<div class="badge-preview-badge">
			{#if selectedBadge.image}
				<div role="img" class="badge-container">
					<a href={'#'} on:click={onClick} class="badge-container-image">
						<ParallaxImage
							{source}
							alternativeText="selectedBadge.description"
							limit={100}
							duration={1500}
						/>
					</a>
				</div>

				<p />
			{/if}
		</div>

		<div class="badge-preview-information">
			{#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 class="badge-preview-seek">
				{#if hasPrevious}
					<button on:click={onPrevious}>Previous</button>
				{/if}

				{#if hasNext}
					<button on:click={onNext} style="float: right;">Next</button>
				{/if}
			</div>
		</div>
	</div>
{/if}

<style>
	:global(.badge-preview img) {
		border-radius: 8px;
		max-height: 50vh;
		height: auto;
		width: 100%;
	}

	.badge-container {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.badge-preview {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		gap: 1rem;
	}

	@media (max-width: 768px) {
		.badge-preview {
			flex-direction: column;
		}
	}

	.badge-preview-seek {
		padding-top: 2rem;
	}
</style>
