<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";

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

  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}
</div>
