<svelte:options
	customElement={{
		tag: 'eve-relative-time',
		shadow: 'none'
	}}
/>

<script lang="ts">
	import type { NostrEvent } from '$lib/eve';
	import { onMount } from 'svelte';

	let props: { time?: Date | number | string; event?: NostrEvent } = $props();

	let time = $derived(
		props.time
			? typeof props.time === 'number' || typeof props.time === 'string'
				? new Date(Number(props.time) * 1000)
				: props.time
			: props.event
				? new Date(props.event.created_at * 1000)
				: new Date()
	);

	const relativeTime = $derived.by(() => {
		const sec = Math.floor(Date.now() / 1000) - time.getTime() / 1000;
		const past = sec >= 0;
		const n = Math.abs(sec);

		const fmt = (value: number, text: string) => {
			const label = text + (value === 1 ? '' : 's');
			return past ? `${value.toFixed(0)} ${label} ago` : `in ${value.toFixed(0)} ${label}`;
		};

		if (n < 5) return past ? 'just now' : 'soon';

		if (n < 90) return fmt(n, 'second');
		if (n < 3600) return fmt(Math.round(n / 60), 'minute');

		if (n < 86400) {
			const h = Math.round(n / 1800) / 2;
			return fmt(h, 'hour');
		}

		if (n < 604800) {
			const d = Math.round(n / 21600) / 4;
			return fmt(d, 'day');
		}

		return time.toLocaleDateString(undefined, { dateStyle: 'medium' });
	});

	onMount(() => {
		const interval = setInterval(() => {
			time = new Date(time);
		}, 1000);

		return () => clearInterval(interval);
	});
</script>

<time
	class="tooltip text-xs text-base-content/50"
	datetime={time.toISOString()}
	data-tip={time.toISOString()}
>
	{relativeTime}
</time>
