<script lang="ts">
import * as m from '$lib/paraglide/messages.js';
import { relativeTimeDe } from '$lib/shared/relativeTime';
import type { components } from '$lib/generated/api';

type Geschichte = components['schemas']['Geschichte'];

interface Props {
	stories: Geschichte[];
}

const { stories }: Props = $props();

function stripHtml(html: string): string {
	return html.replace(/<[^>]*>/g, '');
}

function excerpt(body: string | undefined): string {
	if (!body) return '';
	const text = stripHtml(body);
	if (text.length <= 150) return text;
	return text.slice(0, 150) + '…';
}
</script>

{#if stories.length > 0}
	<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
		<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
			{m.dashboard_reader_recent_stories_heading()}
		</h2>
		<ul class="flex flex-col divide-y divide-line">
			{#each stories as story (story.id)}
				<li class="py-4 first:pt-0 last:pb-0">
					<a
						href="/geschichten/{story.id}"
						class="flex flex-col gap-1 rounded-sm transition-colors hover:text-brand-mint focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
					>
						<span class="text-ink-1 font-serif text-base italic">{story.title}</span>
						{#if story.body}
							<p class="line-clamp-2 font-sans text-xs text-ink-3">{excerpt(story.body)}</p>
						{/if}
						<span class="font-sans text-xs text-ink-3">
							{relativeTimeDe(new Date(story.publishedAt ?? story.updatedAt))}
						</span>
					</a>
				</li>
			{/each}
		</ul>
		<a
			href="/geschichten"
			class="mt-4 block font-sans text-sm text-brand-navy underline hover:text-brand-mint"
		>
			{m.dashboard_reader_all_stories()}
		</a>
	</div>
{/if}
