<script lang="ts">
	import * as d3 from 'd3-color';
	import { createEventDispatcher } from 'svelte';
	import type { ColorsPrompt } from '$lib/types';
	import ColorPalette from '$lib/ColorPalette.svelte';

	const dispatch = createEventDispatcher();

	export let promptData: ColorsPrompt;

	let seletecdImage = 0;

	$: prompt = promptData?.prompt;
	$: colors = promptData?.images[seletecdImage]?.colors.map((e) => d3.rgb(e)) || [];
	$: imageSrc = promptData?.images[seletecdImage]?.imgURL;
	let isCopying = false;

	async function copyStringToClipboard(text: string) {
		// usingo Clipboard API
		if (isCopying) return;
		isCopying = true;
		// await navigator.permissions.query({ name: 'clipboard-write' });
		await navigator.clipboard.write([
			new ClipboardItem({ 'text/plain': new Blob([text], { type: 'text/plain' }) })
		]);
		setTimeout(() => {
			isCopying = false;
		}, 1000);
	}
</script>

<div class="grid grid-cols-6 gap-3">
	<blockquote
		class="row-start-1 mx-auto col-span-6 italic font-semibold max-w-prose text-base text-center line-clamp-3 my-3"
		title={prompt}
	>
		<p>{prompt}</p>
	</blockquote>
	<div class="row-start-3 md:row-start-2 col-span-6 md:col-span-4 flex items-center justify-center">
		{#if colors}
			<ColorPalette {colors} />
		{/if}
	</div>
	<div class="row-start-2 col-span-6 md:col-span-2 flex justify-center md:justify-end pb-3">
		<div class="relative">
			<img
				loading="lazy"
				class="relative max-w-[100px] w-full aspect-square"
				src={imageSrc}
				alt={prompt}
			/>
			<div class="absolute flex justify-around w-full">
				{#each promptData.images as image, i}
					<button
						class="{seletecdImage === i
							? 'bg-black dark:bg-white'
							: 'bg-white dark:bg-black'}   dark:bg-slate-300 rounded-full h-3 w-3 m-1 border border-black dark:border-white"
						on:click={() => (seletecdImage = i)}
						on:mousemove={() => (seletecdImage = i)}
					/>
				{/each}
			</div>
		</div>
	</div>
	<div
		class="row-start-4 col-span-6 md:col-span-2 md:col-start-5 flex justify-center md:justify-end"
	>
		<div class="flex justify-center items-center">
			<button
				class="button"
				title="Send this prompt to input so you can remix it"
				on:click={() => dispatch('remix', { prompt })}
			>
				Remix
			</button>
			<button
				class="button"
				title="Copy all colors to clipboard"
				disabled={isCopying}
				on:click={() => copyStringToClipboard(colors.map((color) => color.formatHex()).join(', '))}
			>
				{isCopying ? 'Copied' : 'Copy'}
			</button>
		</div>
	</div>
</div>

<style lang="postcss" scoped>
	.button {
		@apply min-w-[9ch] bg-black text-white border-2 dark:border-white border-black rounded-2xl ml-2 px-2 py-2 shadow-sm text-xs font-bold focus:outline-none focus:border-gray-400;
	}
</style>
