<script lang="ts">
	import { onDestroy } from 'svelte';
	import type { Snippet } from 'svelte';
	import { theme } from '$lib/stores/theme.svelte.js';

	interface BoardTheme {
		themeHue?: number | null;
		themeSaturation?: number | null;
		backgroundType?: string | null;
	}

	interface Props {
		board: BoardTheme;
		children: Snippet;
	}

	let { board, children }: Props = $props();

	let containerEl: HTMLDivElement | undefined = $state(undefined);

	function restoreGlobalTheme() {
		if (typeof document === 'undefined') return;
		const html = document.documentElement;
		html.style.removeProperty('--board-primary-h');
		html.style.removeProperty('--board-primary-s');
		// Re-apply the global theme store values
		html.style.setProperty('--primary-h', String(theme.primaryHue));
		html.style.setProperty('--primary-s', `${theme.primarySaturation}%`);
	}

	// Apply board-level theme overrides via CSS custom properties
	$effect(() => {
		if (typeof document === 'undefined') return;
		const html = document.documentElement;

		if (board.themeHue != null) {
			html.style.setProperty('--board-primary-h', String(board.themeHue));
			html.style.setProperty('--primary-h', String(board.themeHue));
		}
		if (board.themeSaturation != null) {
			html.style.setProperty('--board-primary-s', `${board.themeSaturation}%`);
			html.style.setProperty('--primary-s', `${board.themeSaturation}%`);
		}

		return () => {
			restoreGlobalTheme();
		};
	});

	onDestroy(() => {
		restoreGlobalTheme();
	});
</script>

<div bind:this={containerEl} class="board-theme-scope">
	{@render children()}
</div>

<style>
	.board-theme-scope {
		transition: --primary-h 0.3s ease, --primary-s 0.3s ease;
	}
</style>
