<script lang="ts">
	import { baseUrl } from '$lib/env';
	import { onMount, onDestroy } from 'svelte';

	let isLoaded = $state(false);
	let scalarApiReference;

	function initializeScalar() {
		// @ts-expect-error - Scalar is loaded dynamically
		if (window.Scalar) {
			// @ts-expect-error - Scalar is loaded dynamically
			scalarApiReference = window.Scalar.createApiReference('#app', {
				url: '/swagger.json',
				hideDarkModeToggle: true,
				hideClientButton: true,
				baseServerURL: baseUrl
			});
			isLoaded = true;
		} else {
			setTimeout(initializeScalar, 100); // Check again in 100ms
		}
	}

	function loadScalarScript() {
		const script = document.createElement('script');
		script.src = 'https://cdn.jsdelivr.net/npm/@scalar/api-reference';
		script.onload = () => {
			initializeScalar();
		};
		script.onerror = (error) => {
			console.error('Failed to load Scalar API Reference:', error);
		};
		document.head.appendChild(script);
	}

	let darkMode = $state(false);
	let handler: (e: MediaQueryListEvent) => void;
	let mediaQuery: MediaQueryList;
	onMount(() => {
		loadScalarScript();
		darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

		mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
		handler = (e: MediaQueryListEvent) => {
			darkMode = e.matches;
		};
		mediaQuery.addEventListener('change', handler);

		return () => {
			isLoaded = false;
		};
	});

	onDestroy(() => {
		if (mediaQuery) {
			mediaQuery.removeEventListener('change', handler);
		}
		if (isLoaded) {
			document.querySelectorAll('style[data-scalar]').forEach((el) => el.remove());

			scalarApiReference.destroy();
		}
	});
</script>

<div class="relative">
	<div id="app" class="w-full" class:dark-mode={darkMode}></div>
</div>
