---
import Layout from '../../layouts/Layout.astro';
import BlogOverview from '../../components/BlogOverview.svelte';
import {
  getPosts,
  getTags,
} from '../../lib/cms';
import {
  sortPostsByDate,
  filterHiddenPosts,
  filterPostsByTag,
  getTotalPages,
  paginate,
  getPostsPerPage,
  getTagsMap,
  resolvePostTagsInPost,
  getPostImageUrl,
} from '../../lib/blog-utils';
import { t, T } from '../../lib/translations';

export const prerender = true;

let posts: Awaited<ReturnType<typeof getPosts>> = [];
let tags: Awaited<ReturnType<typeof getTags>> = [];
let cmsError: string | null = null;

try {
  [posts, tags] = await Promise.all([getPosts({ resolve: ['postImage'] }), getTags()]);
  posts = filterHiddenPosts(sortPostsByDate(posts));
  const tagsMap = await getTagsMap();
  for (const p of posts) resolvePostTagsInPost(p, tagsMap);
  // Resolve post card images
  const { ensureTransformedImage } = await import('../../lib/rusty-image');
  for (const post of posts) {
    const raw = getPostImageUrl(post.postImage);
    if (raw) {
      try {
        const url = await ensureTransformedImage(raw, { width: 400, height: 267, fit: 'cover', format: 'webp' });
        (post as typeof post & { _resolvedImageUrl?: string })._resolvedImageUrl = url;
      } catch { /* image optional */ }
    }
  }
} catch (e) {
  cmsError = e instanceof Error ? e.message : String(e);
}

const perPage = getPostsPerPage();
const filtered = filterPostsByTag(posts, null);
const totalPages = getTotalPages(filtered.length, perPage);
const pagePosts = paginate(filtered, 1, perPage);

type PostWithEvent = (typeof posts)[number] & {
  isEvent?: boolean;
  eventDate?: string;
  _resolvedImageUrl?: string;
};
const nowMs = Date.now();
const upcomingEvents = (posts as PostWithEvent[])
  .filter((p) => p.isEvent && p.eventDate && new Date(p.eventDate).getTime() >= nowMs)
  .sort((a, b) => new Date(a.eventDate ?? 0).getTime() - new Date(b.eventDate ?? 0).getTime())
  .slice(0, 4);

// Lightweight index for client-side search over the full archive.
const searchIndex = posts.map((p) => ({
  slug: p.slug ?? p._slug ?? "",
  headline: p.headline ?? "",
  excerpt: p.excerpt ?? "",
  subheadline: p.subheadline ?? "",
  tags: (p.postTag ?? []).map((t) => (typeof t === "string" ? t : (t as { name?: string; _slug?: string }).name ?? (t as { _slug?: string })._slug ?? "")).filter(Boolean),
  image: (p as PostWithEvent)._resolvedImageUrl ?? null,
  created: p.created ?? null,
  isEvent: Boolean((p as PostWithEvent).isEvent),
  eventDate: (p as PostWithEvent).eventDate ?? null,
}));

const translations = Astro.locals.translations ?? {};
---

<Layout
  title={`${t(translations, T.posts_title)} – Aktuelles`}
  description="Übersicht aller Beiträge und Meldungen."
  breadcrumbItems={[
    { href: "/", translationKey: T.nav_start },
    { translationKey: T.nav_posts },
  ]}
>
  <div class="mb-6 pt-10 pageTitle">
    <h1>{t(translations, T.posts_title)}</h1>
    <h2>{t(translations, T.posts_subtitle)}</h2>
  </div>
  <div class="content mt-8">
    {cmsError ? (
      <div class="rounded-sm border border-amber-200 bg-amber-50 p-4 text-amber-800">
        <strong>{t(translations, T.posts_cms_error)}</strong> {cmsError}
      </div>
    ) : (
      <BlogOverview
        posts={pagePosts}
        tags={tags}
        activeTag={null}
        currentPage={1}
        totalPages={totalPages}
        totalPosts={filtered.length}
        basePath="/posts"
        translations={translations}
        upcomingEvents={upcomingEvents}
        searchIndex={searchIndex}
        client:load
      />
    )}
  </div>
</Layout>
