<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 GeschichteSummary = components['schemas']['GeschichteSummary'];

interface Props {
	stories: GeschichteSummary[];
}

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="flex flex-col overflow-hidden rounded-sm border border-line bg-surface">
		<!-- Card-head -->
		<div class="flex items-center justify-between border-b border-line px-3 py-1.5">
			<h3 class="text-[11px] font-bold tracking-[.12em] text-ink-3 uppercase">
				{m.dashboard_reader_recent_stories_heading()}
			</h3>
			<a
				href="/geschichten"
				class="flex min-h-[44px] items-center text-[11px] font-semibold text-ink-2 no-underline focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
			>
				{m.dashboard_reader_all_stories()}
			</a>
		</div>

		<!-- Story list -->
		<ul class="flex flex-col">
			{#each stories as story (story.id)}
				<li>
					<a
						href="/geschichten/{story.id}"
						class="flex min-h-[44px] flex-col gap-1 border-b border-line/50 px-3 py-2 last:border-b-0 hover:bg-muted focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
					>
						<span class="font-serif text-base text-ink italic">{story.title}</span>
						{#if story.body}
							<p class="line-clamp-2 text-xs leading-relaxed text-ink-2">{excerpt(story.body)}</p>
						{/if}
						<span class="text-[11px] text-ink-3">
							{relativeTimeDe(new Date(story.publishedAt ?? story.updatedAt))}
						</span>
					</a>
				</li>
			{/each}
		</ul>
	</div>
{/if}
