<script lang="ts">
	import { get } from 'svelte/store';
	import type { WplaceColor } from '../../constants/colors';
	import { COLORS } from '../../constants/colors';
	import { selectedColor } from '../../stores/canvas';
	import { currentUser } from '../../stores/user';
	import ColorSwatch from './ColorSwatch.svelte';

	export let colors: WplaceColor[] = COLORS;

	$: freeColors = colors.filter((color) => !color.paid);
	$: paidColors = colors.filter((color) => color.paid);
	$: unlockedColors = computeUnlocked();

	function computeUnlocked() {
		const user = get(currentUser);
		const unlocked = new Set<number>();
		for (const color of colors) {
			if (!color.paid) {
				unlocked.add(color.id);
				continue;
			}
			if (!user) continue;
			const mask = 1 << (color.id - 32);
			if ((user.extraColorsBitmap & mask) !== 0) {
				unlocked.add(color.id);
			}
		}
		return unlocked;
	}

	function handleSelect(id: number) {
		selectedColor.set(id);
	}

	function isUnlocked(color: WplaceColor) {
		return unlockedColors.has(color.id);
	}
</script>

<div class="space-y-6">
	<section>
		<h3 class="text-sm font-semibold text-base-content/70 uppercase tracking-wide">Free Colors</h3>
		<div class="mt-2 grid grid-cols-8 gap-2">
			{#each freeColors as color}
				<ColorSwatch {color} unlocked={true} on:select={(event) => handleSelect(event.detail)} />
			{/each}
		</div>
	</section>
	<section>
		<h3 class="text-sm font-semibold text-base-content/70 uppercase tracking-wide flex items-center gap-2">
			Paid Colors
			<span class="badge badge-sm">2000 droplets</span>
		</h3>
		<div class="mt-2 grid grid-cols-8 gap-2">
			{#each paidColors as color}
				<ColorSwatch {color} unlocked={isUnlocked(color)} on:select={(event) => handleSelect(event.detail)} />
			{/each}
		</div>
	</section>
</div>
