<script lang="ts">
	import { navigationStore } from '$lib/navigation';
	import type { Arxlet } from '$lib/eve';
	import { onDestroy, onMount } from 'svelte';
	import ArxletHeader from '$lib/components/ArxletHeader.svelte';
	import LiquidGlass from '$lib/components/LiquidGlass.svelte';

	function universalBase64Encode(data: string) {
		return btoa(String.fromCharCode(...new TextEncoder().encode(data)));
	}

	function cleanup() {
		document.body
			.querySelectorAll('script[type="module"][data-arxlet]')
			.forEach((script) => script.remove());
	}

	const runArxlet = (module: string) => {
		cleanup();

		const newScript = document.createElement('script');
		newScript.type = 'module';
		newScript.dataset.arxlet = 'true';
		const stringifiedModule = JSON.stringify(
			'data:text/javascript;base64,' + universalBase64Encode(module)
		);
		const stringifiedPath = JSON.stringify(path || '');
		newScript.innerHTML = `
      import { render } from ${stringifiedModule};
      render(document.getElementById('arxlet-container'), ${stringifiedPath});
		`;
		document.body.appendChild(newScript);
	};

	const { id, path } = $props();

	let arxlet: Arxlet | null = $state();

	onMount(async () => {
		if (id === 'ZZ-store') return navigationStore.navigateTo('/store');
		const arxletData = await window.eve.getArxlet(id);
		if (!arxletData) navigationStore.navigateTo('/');
		arxlet = arxletData;
		if (!arxlet) return;
		runArxlet(arxlet.script);
	});

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

<svelte:head>
	<script type="importmap">
		{
			"imports": {
				"svelte": "https://esm.sh/svelte/src/index-client.js",
				"svelte/internal": "https://esm.sh/svelte/src/internal/index.js",
				"svelte/internal/flags/legacy": "https://esm.sh/svelte/src/internal/flags/legacy.js",
				"svelte/internal/client": "https://esm.sh/svelte/src/internal/client/index.js",
				"rxjs": "https://esm.sh/rxjs/dist/esm/index.js",
				"rxjs/operators": "https://esm.sh/rxjs/dist/esm/operators/index.js",
				"vue": "https://esm.sh/vue@3.5.21/dist/vue.esm-browser.prod.js",
				"@vueuse/rxjs": "https://esm.sh/@vueuse/rxjs"
			}
		}
	</script>
</svelte:head>

<ArxletHeader
	title={arxlet?.name ?? 'Loading...'}
	subtitle={arxlet?.description ?? 'No description'}
	icon={arxlet?.icon ?? 'mdi:loading'}
	iconColor={arxlet?.iconColor ?? '#000000'}
	iconForegroundColor={arxlet?.iconForegroundColor}
	iconStrokeColor={arxlet?.iconStrokeColor}
/>
<LiquidGlass>
	<div id="arxlet-container" />
</LiquidGlass>
