<script lang="ts" module>
	import { env } from '$env/dynamic/public';

	const { PUBLIC_BASEPATH } = env;

	const trim = (str: string, char: string, trimStart?: boolean, trimEnd?: boolean) => {
		let start = 0,
			end = str.length;

		if (trimStart || trimStart === undefined) {
			while (start < end && str[start] === char) start++;
		}

		if (trimEnd || trimEnd === undefined) {
			while (end > start && str[end - 1] === char) end--;
		}

		return str.substring(start, end);
	};
</script>

<script lang="ts">
	import type { Snippet } from 'svelte';
	import type { MouseEventHandler } from 'svelte/elements';

	let {
		href,
		disabled = false,
		tab = 'current',
		children,
		onclick
	}: {
		href: string;
		disabled?: boolean;
		tab?: 'current' | 'new';
		children: Snippet;
		onclick?: MouseEventHandler<HTMLAnchorElement>;
	} = $props();

	if (PUBLIC_BASEPATH && !href.startsWith('http://') && !href.startsWith('https://')) {
		let prefix = trim(PUBLIC_BASEPATH, '/');
		href = `/${prefix}/${trim(href, '/', true, false)}`;
	}
</script>

<a
	class={[
		'text-accent hover:text-primary inline-flex items-center gap-1.5 transition-colors',
		disabled && 'pointer-events-none cursor-not-allowed opacity-50'
	]}
	{href}
	target={tab === 'new' ? '_blank' : undefined}
	rel={tab === 'new' ? 'noopener noreferrer' : undefined}
	{onclick}
>
	{@render children()}
</a>
