<script lang="ts">
	import type { MediaTitle } from '$lib/Data/AniList/media';
	import LinkedTooltip from '$lib/Tooltip/LinkedTooltip.svelte';
	import { abbreviate as abbreviated } from '$lib/Utility/string';
	import settings from '$stores/settings';
	import LZString from 'lz-string';
	import * as wanakana from 'wanakana';

	export let title: MediaTitle;
	export let abbreviate = false;
	export let abbreviateTo = 20;
	export let tooltip = false;

	const compressToBase64 = (string: string) => LZString.compressToBase64(string);
</script>

<span id={`title-display-${compressToBase64(title.native)}`}>
	{#if $settings.displayTitleFormat === 'native'}
		{#if $settings.displayFurigana}
			{@const kana = abbreviate
				? abbreviated(wanakana.toKana(title.native), abbreviateTo)
				: wanakana.toKana(title.native)}
			{@const native = abbreviate ? abbreviated(title.native, abbreviateTo) : title.native}

			<LinkedTooltip
				content={title.english || title.romaji || title.native}
				disable={tooltip}
				pin={`title-display-${compressToBase64(title.native)}`}
				relative
				ignoreAnchorStyling
			>
				{#if kana === native}
					{native}
				{:else}
					<ruby>
						{native}
						<rt>
							{kana}
						</rt>
					</ruby>
				{/if}
			</LinkedTooltip>
		{:else}
			<LinkedTooltip
				content={title.english || title.romaji || title.native}
				disable={tooltip}
				pin={`title-display-${compressToBase64(title.native)}`}
				relative
				ignoreAnchorStyling
			>
				{abbreviate ? abbreviated(title.native, abbreviateTo) : title.native}
			</LinkedTooltip>
		{/if}
	{:else if $settings.displayTitleFormat === 'romaji'}
		<LinkedTooltip
			content={title.english || title.romaji || title.native}
			disable={tooltip}
			pin={`title-display-${compressToBase64(title.native)}`}
			relative
			ignoreAnchorStyling
		>
			{abbreviate ? abbreviated(title.romaji, abbreviateTo) : title.romaji}
		</LinkedTooltip>
	{:else}
		<LinkedTooltip
			content={title.romaji || title.native}
			disable={tooltip}
			pin={`title-display-${compressToBase64(title.native)}`}
			relative
			ignoreAnchorStyling
		>
			{abbreviate
				? abbreviated(title.english || title.romaji || title.native, abbreviateTo)
				: title.english || title.romaji || title.native}
		</LinkedTooltip>
	{/if}
</span>
