<script lang="ts">
	export let src: string;
	export let alt = '';
	export let loading: 'eager' | 'lazy' | undefined = undefined;
	const u = new URL(src);
	const filename = u.pathname.split('/').pop() || '9a8sda';
	const int = (parseInt(filename?.slice(0, 8), 16) % 7) + 1;
	const frame = `/frames/frame_0${int}`;

	let handlingError = false;
	function handleError() {
		if (handlingError) return;
		handlingError = true;
		console.log('error', { src });
		const oldSrc = src;
		src = '';
		setTimeout(() => {
			src = oldSrc;
			handlingError = false;
		}, 1000);
	}
</script>

<div class="frame" style="--frame: url(/frames/frame_0{int}.png)">
	<picture class="painting-frame">
		<!-- Load AVIF format -->
		<source srcset="{frame}.avif" type="image/avif" />

		<!-- If AVIF is not supported, load WebP format -->
		<source srcset="{frame}.webp" type="image/webp" />

		<!-- If neither AVIF nor WebP are supported, load PNG format -->
		<img src="{frame}.png" alt="Painting Frame" />
	</picture>

	<img src="/hang.png" class="hang" alt="painting hanging cord" />
	<picture class="person">
		<source srcset={src.replace('.png', '.avif')} type="image/avif" />
		<source srcset={src.replace('.png', '.webp')} type="image/webp" />
		<source srcset={src.replace('.png', '.jpg')} type="image/jpeg" />
		<img {src} {alt} on:error={() => handleError()} {loading} />
	</picture>
</div>

<style>
	.painting-frame > * {
		position: absolute;
		width: 100%;
		height: 100%;
		object-fit: contain;
		filter: drop-shadow(0px 0px 10px black) brightness(0.6) contrast(1.1);
	}
	.hang {
		position: absolute;
		top: 0px;
		margin: 0px;
		top: -16%;
		width: 50%;
		left: 25%;
		z-index: -1;
	}
	.frame {
		position: relative;
		width: fit-content;
		height: fit-content;
	}
	.frame:before {
		content: '';
		position: absolute;
		height: 100%;
		width: 100%;
		/* background: var(--frame); */
		background-position: center center;
		background-size: contain;
		background-repeat: no-repeat;
		filter: drop-shadow(0px 0px 20px black);
	}
	.person img {
		z-index: -1;
		max-width: 70%;
		max-height: 70%;
		margin-left: 15%;
		margin-top: 12%;
	}
</style>
