<script lang="ts">
	import locale from '$stores/locale';
	import type { Badge } from './Database/userBadges';
	import Tooltip from './Tooltip/LinkedTooltip.svelte';
	import { databaseTimeToDate } from './Utility/time';

	export let source: string | null | undefined;
	export let alternative: string | null | undefined;
	export let fallback: string | null | undefined;
	export let maxReplaceCount = 1;
	export let replaceDelay = 1000;
	export let error = 'https://i2.kym-cdn.com/photos/images/newsfeed/000/290/992/0aa.jpg';
	export let hideOnError = false;
	export let badge: Badge;
	export let style = '';
	export let selectedBadge: Badge | null = null;

	let replaceCount = 0;
	let badgeReference: HTMLImageElement;
	let mouseX = 0;
	let mouseY = 0;

	const delayedReplace = (event: Event, image: string | undefined | null) => {
		if (replaceCount >= maxReplaceCount) return;

		setTimeout(() => {
			(event.target as HTMLImageElement).src = image || '';

			replaceCount += 1;
		}, replaceDelay);
	};

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

		mouseX +=
			(-(event.clientX - boundingRectangle.left - boundingRectangle.width / 2) - mouseX) * factor;
		mouseY +=
			(-(event.clientY - boundingRectangle.top - boundingRectangle.height / 2) - mouseY) * factor;
	};

	const handleMouseLeave = () => {
		mouseX = 0;
		mouseY = 0;
	};
</script>

{#if replaceCount < maxReplaceCount}
	<Tooltip
		content={`${badge.time ? $locale().dateFormatter(databaseTimeToDate(badge.time)) : ''}${
			badge.description ? `\n${badge.description}` : ''
		}${badge.designer ? `\nDesigner: ${badge.designer}` : ''}${
			badge.source ? `\nSource: ${badge.source}` : ''
		}`}
		id={`badge-${badge.id}`}
		pin={`badge-${badge.id}`}
		pinPosition="top"
	>
		<a
			href={'#'}
			target="_blank"
			class="badge-container badge"
			on:click={(e) => {
				e.preventDefault();

				selectedBadge = badge;
			}}
		>
			<img
				src={source}
				alt={alternative}
				loading="lazy"
				class="badge"
				bind:this={badgeReference}
				on:mousemove={handleMouseMove}
				on:mouseleave={handleMouseLeave}
				style="transform: perspective(1000px) rotateX({mouseY / 10}deg) rotateY({-mouseX /
					10}deg); ${style}"
				on:error={(e) => delayedReplace(e, fallback)}
			/>
		</a>
	</Tooltip>
{:else if !hideOnError}
	<img src={error} alt="Not found" loading="lazy" class="badge" />
{/if}

<style lang="scss">
	$transition: transform 0.325s ease;

	.badge {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		transition: $transition;
		box-sizing: border-box;
		border-radius: 8px;
	}

	.badge:hover {
		transform: scale(1.075);
		position: relative;
		z-index: 2;
		transition: $transition;
	}
</style>
