<script lang="ts">
import FileThumb from '@/components/textarea/FileThumb.svelte'
import { testIds } from '@/constants'
import { files } from '@/modules/fileUpload'

export let file: File

const MATH_ERROR_TOLERANCE = 2

$: storeFile = $files && files.find(file.name)

$: width = storeFile?.preview?.dimensions?.width || 0
$: height = storeFile?.preview?.dimensions?.height || 0
$: horizontal = storeFile?.preview?.orientation?.horizontal || false
$: vertical = storeFile?.preview?.orientation?.vertical || false

$: horizontalScale = width / (height / 100) + MATH_ERROR_TOLERANCE
$: horizontalShift = (100 - horizontalScale) / 2
$: verticalScale = height / (width / 100) + MATH_ERROR_TOLERANCE
$: verticalShift = (100 - verticalScale) / 2
</script>

{#if storeFile && storeFile.previewState === 'ready'}
	{#if storeFile.preview?.data}
		<div class="w-full h-full rounded-xl overflow-hidden" data-testid={testIds.textareaPreviewImage}>
			<img
				src={storeFile.preview.data}
				alt={file.name}
				style:width={horizontal ? `${horizontalScale}%` : undefined}
				style:margin-left={horizontal ? `${horizontalShift}%` : undefined}
				style:height={vertical ? `${verticalScale}%` : undefined}
				style:margin-top={vertical ? `${verticalShift}%` : undefined}
				class="m-auto max-w-none"
			/>
		</div>
	{:else}
		<FileThumb {file} />
	{/if}
{/if}
