<script lang="ts" ts>
	import type { Media } from '$lib/AniList/media';
	import MediaTitleDisplay from '$lib/List/MediaTitleDisplay.svelte';
	import type { SubsPleaseEpisode } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
	import HoverCover from '$lib/Media/Cover/HoverCover.svelte';
	import {
		onMouseEnter,
		type HoverCoverResponse,
		onMouseLeave,
		onMouseMove
	} from '$lib/Media/Cover/hoverCover';

	import { outboundLink } from '$lib/Media/links';
	import tooltip from '$lib/Tooltip/tooltip';
	import { abbreviate } from '$lib/Utility/string';
	import settings from '$stores/settings';

	export let media: Media | null;
	export let entry: SubsPleaseEpisode;
	export let cover = true;

	let hoverCoverState: HoverCoverResponse = {};
	const abbreviateTo = 40;

	const titleSelect = (media: Media | null) =>
		media ? media.title.english || media.title.romaji || media.title.native : null;
</script>

<a
	href={media
		? outboundLink(media, 'anime', $settings.displayOutboundLinksTo)
		: outboundLink(
				null,
				'anime',
				$settings.displayOutboundLinksTo,
				true,
				titleSelect(media) || entry.title
		  )}
	target="_blank"
	on:mouseenter={() => {
		const response = onMouseEnter(media, entry);

		hoverCoverState.hovering = response.hovering;
		hoverCoverState.item = response.item;
		hoverCoverState.media = response.media;
	}}
	on:mouseleave={() => {
		const response = onMouseLeave();

		hoverCoverState.hovering = response.hovering;
		hoverCoverState.item = response.item;
		hoverCoverState.media = response.media;
	}}
	on:mousemove={(e) => {
		const response = onMouseMove(e, 300);

		hoverCoverState.style = response.style;
	}}
>
	{#if media}
		<MediaTitleDisplay
			title={media.title}
			abbreviate
			{abbreviateTo}
			tooltip={media.title.english?.length > abbreviateTo ||
				media.title.romaji?.length > abbreviateTo ||
				media.title.native?.length > abbreviateTo}
		/>
	{:else}
		<span title={entry.title} use:tooltip>
			{abbreviate(entry.title, abbreviateTo)}
		</span>
	{/if}
</a>

{#if cover}
	<HoverCover options={hoverCoverState} width={300} />
{/if}
