<script lang="ts">
	import { createEventDispatcher, onMount } from 'svelte';
	import { currentUser, currentCharges } from '$lib/stores/user';
	import { selectedColor } from '$lib/stores/canvas';
	import { COLORS } from '$lib/constants/colors';

	export let disabled = false;
	export let painting = false;

	const dispatch = createEventDispatcher();

	let chargeCanvas: HTMLCanvasElement;

	$: selectedColorData = COLORS.find((c) => c.id === $selectedColor);
	$: chargePercentage = $currentUser ? ($currentCharges / $currentUser.maxCharges) * 100 : 0;

	// Draw charge bar whenever charges change
	$: if (chargeCanvas && $currentUser) {
		drawChargeBar(chargeCanvas, $currentCharges, $currentUser.maxCharges);
	}

	function drawChargeBar(canvas: HTMLCanvasElement, charges: number, maxCharges: number) {
		const ctx = canvas.getContext('2d');
		if (!ctx) return;

		const width = 112;
		const height = 20;
		const barHeight = 12;
		const barY = (height - barHeight) / 2;
		const filledWidth = (charges / maxCharges) * width;

		// Clear canvas
		ctx.clearRect(0, 0, width, height);

		// Draw background (empty bar)
		ctx.fillStyle = '#444';
		ctx.fillRect(0, barY, width, barHeight);

		// Draw filled portion
		ctx.fillStyle = '#4ade80'; // Green color
		ctx.fillRect(0, barY, filledWidth, barHeight);

		// Draw border
		ctx.strokeStyle = '#fff';
		ctx.lineWidth = 2;
		ctx.strokeRect(1, barY + 1, width - 2, barHeight - 2);
	}

	function handleClick() {
		if (!disabled) {
			dispatch('click');
		}
	}

	function openPalette() {
		dispatch('openPalette');
	}
</script>

<button
	class="btn btn-primary btn-lg sm:btn-xl relative z-30"
	on:click={handleClick}
	{disabled}
>
	<svg
		xmlns="http://www.w3.org/2000/svg"
		viewBox="0 -960 960 960"
		fill="currentColor"
		class="size-6"
	>
		<path
			d="M240-120q-45 0-89-22t-71-58q26 0 53-20.5t27-59.5q0-50 35-85t85-35q50 0 85 35t35 85q0 66-47 113t-113 47Zm230-240L360-470l358-358q11-11 27.5-11.5T774-828l54 54q12 12 12 28t-12 28L470-360Z"
		/>
	</svg>

	<div class="flex items-center gap-2">
		Paint
		{#if $currentUser}
			<span class="font-semibold">{Math.floor($currentCharges)}/{$currentUser.maxCharges}</span>
		{/if}
	</div>

	<!-- Color preview - click to open palette -->
	{#if selectedColorData}
		<button
			type="button"
			class="absolute -right-2 -top-2 size-8 rounded-full border-2 border-white shadow-md"
			style="background: {selectedColorData.hex}"
			on:click|stopPropagation={openPalette}
			title="Change color"
		>
		</button>
	{/if}
</button>
