---
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,
  getPostImageUrl,
  buildPostSearchIndex,
  selectUpcomingEvents,
} from '../../../lib/blog-utils';
import { t, T } from '../../../lib/translations';

export const prerender = true;

export async function getStaticPaths() {
  const perPage = getPostsPerPage();
  let posts: Awaited<ReturnType<typeof getPosts>> = [];
  try {
    posts = await getPosts();
    posts = filterHiddenPosts(sortPostsByDate(posts));
  } catch {
    return [];
  }
  const totalPages = getTotalPages(posts.length, perPage);
  return Array.from({ length: totalPages - 1 }, (_, i) => ({
    params: { page: String(i + 2) },
  }));
}

const { page: pageParam } = Astro.params as { page: string };
const currentPage = Math.max(1, parseInt(pageParam, 10) || 1);
const perPage = getPostsPerPage();

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 { 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 filtered = filterPostsByTag(posts, null);
const totalPages = getTotalPages(filtered.length, perPage);
const pageNum = Math.min(currentPage, totalPages);
const pagePosts = paginate(filtered, pageNum, perPage);

const upcomingEvents = selectUpcomingEvents(filtered);
const searchIndex = buildPostSearchIndex(filtered);

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

<Layout
  title={`${t(translations, T.posts_title)} – Seite ${pageNum}`}
  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={pageNum}
        totalPages={totalPages}
        totalPosts={filtered.length}
        basePath="/posts"
        translations={translations}
        upcomingEvents={upcomingEvents}
        searchIndex={searchIndex}
        client:load
      />
    )}
  </div>
</Layout>
