<script lang="ts">
  import { getBlockLayoutClasses } from "$lib/block-layout";
  import type { ImageBlockData } from "$lib/block-types";
  import RustyImage from "$lib/components/RustyImage.svelte";
  import { extractCmsImageField } from "$lib/rusty-image";

  let { block }: { block: ImageBlockData } = $props();

  const layoutClasses = $derived(getBlockLayoutClasses(block.layout));
  const imageSource = $derived(block.image ?? block.img);
  const imageField = $derived(extractCmsImageField(imageSource));
  const rawSrc = $derived(imageField?.url ?? null);
  const focal = $derived(imageField?.focal ?? null);
  $effect(() => {
    if (!rawSrc && block._slug) {
      console.warn("[ImageBlock] Bild nicht verfügbar:", block._slug, {
        hasImage: !!block.image,
        hasImg: !!block.img,
        imageType: typeof block.image,
        imgType: typeof block.img,
        imgSrc:
          block.img && typeof block.img === "object"
            ? (block.img as { src?: string }).src
            : undefined,
        imageSrc:
          block.image && typeof block.image === "object"
            ? (block.image as { src?: string }).src
            : undefined,
      });
    }
  });
  const title = $derived(
    typeof imageSource === "object" && imageSource
      ? "description" in imageSource && imageSource.description
        ? imageSource.description
        : "title" in imageSource
          ? (imageSource as { title?: string }).title
          : undefined
      : undefined,
  );
</script>

<div class={layoutClasses} data-block="Image" data-block-type="image" data-block-slug={block._slug}>
  {#if rawSrc}
    <figure class="max-w-[400px]">
      <RustyImage
        src={rawSrc}
        focal={focal}
        width={800}
        quality={85}
        fit="contain"
        alt={block.caption ?? title ?? ""}
        class="w-full rounded-xs"
        loading="lazy"
      />
      {#if block.caption}
        <figcaption class="mt-1 text-sm text-stein-600">{block.caption}</figcaption>
      {/if}
    </figure>
  {:else}
    <p class="text-sm text-stein-500">Bild nicht verfügbar.</p>
  {/if}
</div>
