<script context="module" lang="ts">
	export type DisplayFn = (
		msg: string,
		options?: {
			type?: 'error' | 'success';
			timeToShow?: number;
		}
	) => void;
</script>

<script lang="ts">
	let message = $state<string | undefined>(undefined);
	let type = $state<'error' | 'success'>('error');

	let timeout: number | undefined = undefined;

	export function clear() {
		if (timeout) clearTimeout(timeout);
		message = undefined;
	}

	export function display(
		msg: string,
		options?: {
			type?: 'error' | 'success';
			timeToShow?: number;
		}
	) {
		if (timeout) clearTimeout(timeout);

		if (!msg) {
			message = undefined;
			return;
		}

		let { type: l_type, timeToShow } = options ?? { type: 'error', timeToShow: undefined };

		if (l_type) {
			type = l_type;
		}

		message = msg;

		if (timeToShow) {
			timeout = setTimeout(() => {
				message = undefined;
				timeout = undefined;
			}, timeToShow);
		}
	}
</script>

{#if message}
	<div class="form-msg {type}">
		{message}
	</div>
{/if}
