<script lang="ts">
  import { marked } from "marked";
  import PostCard from "../PostCard.svelte";
  import { getBlockLayoutClasses } from "../../lib/block-layout";
  import type { PostOverviewBlockData } from "../../lib/block-types";
  import type { PostEntry } from "../../lib/cms";
  import { postHref } from "../../lib/blog-utils";
  import { t as tStatic, T } from "../../lib/translations";
  import type { Translations } from "../../lib/translations";

  let {
    block,
    class: className = "",
    translations = {},
  }: {
    block: PostOverviewBlockData;
    class?: string;
    translations?: Translations | null;
  } = $props();

  const t = (key: Parameters<typeof tStatic>[1]) => tStatic(translations ?? null, key);

  marked.setOptions({ gfm: true });
  const textHtml = $derived(
    block.text && typeof block.text === "string"
      ? (marked.parse(block.text) as string)
      : "",
  );
  const layoutClasses = $derived(getBlockLayoutClasses(block.layout));
  const posts = $derived((block.postsResolved ?? []) as (PostEntry & { _resolvedImageUrl?: string })[]);
  const design = $derived(block.design ?? "cards");
  const tagBase = "/posts/tag";
</script>

<div
  class="post-overview mb-4 {layoutClasses} {className}"
  data-block-type="post_overview"
  data-block-slug={block._slug}
>
  {#if block.headline}
    <h3 class="mb-2">{block.headline}</h3>
  {/if}
  {#if textHtml}
    <div class="mb-2 markdown max-w-none prose prose-zinc">{@html textHtml}</div>
  {/if}

  {#if design === "list" && posts.length > 0}
    <div class="flex flex-col gap-4">
      {#each posts as post}
        <PostCard post={post} href={postHref(post)} tagBase={tagBase} />
      {/each}
    </div>
  {:else if design === "cards" && posts.length > 0}
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {#each posts as post}
        <PostCard post={post} href={postHref(post)} tagBase={tagBase} />
      {/each}
    </div>
  {/if}

  {#if posts.length > 0}
    <div class="mt-3 text-xs px-2">
      <a href="/posts/" class="inline-flex items-center gap-1 text-zinc-700 hover:text-zinc-900 hover:underline !no-underline">
        {t(T.post_overview_all)}
        <span aria-hidden="true">→</span>
      </a>
    </div>
  {/if}
</div>
