<script lang="ts">
  import Icon from "@iconify/svelte";
  import { getBlockLayoutClasses } from "../../lib/block-layout";
  import type { IframeBlockData } from "../../lib/block-types";
  import { t as tStatic, T } from "../../lib/translations";
  import type { Translations } from "../../lib/translations";

  let { block, translations = {} }: { block: IframeBlockData; translations?: Translations | null } = $props();

  function t(key: string) {
    return tStatic(translations ?? null, key);
  }

  /** Overlay blockiert Scroll/Klick über Map; nach Klick entfernen (client:load nötig). */
  let overlayActive = $state(true);

  /** Nimmt entweder eine reine URL oder Iframe-HTML und liefert die src-URL. */
  function getIframeSrc(raw: string | undefined): string {
    if (typeof raw !== "string" || !raw.trim()) return "";
    const s = raw.trim();
    if (s.startsWith("http") || s.startsWith("//")) return s;
    const match = s.match(/<iframe[^>]+src\s*=\s*["']([^"']+)["']/i);
    return match ? match[1].trim() : "";
  }

  const layoutClasses = $derived(getBlockLayoutClasses(block.layout));
  const src = $derived(getIframeSrc(block.iframe));

  function activateMap() {
    overlayActive = false;
  }
</script>

<div class={layoutClasses} data-block-type="iframe" data-block-slug={block._slug}>
  {#if src}
    <div class="relative aspect-video w-full overflow-hidden rounded-sm bg-zinc-100">
      <iframe
        title={block.content ?? "Embed"}
        src={src}
        class="h-full w-full border-0"
        loading="lazy"
        allowfullscreen
      ></iframe>
      {#if overlayActive}
        <div
          role="button"
          tabindex="0"
          class="absolute inset-0 z-10 cursor-pointer rounded-sm bg-black/50 flex items-center justify-center"
          aria-label={t(T.iframe_activate_aria)}
          onclick={activateMap}
          onkeydown={(e) => e.key === "Enter" && activateMap()}
        >
          <Icon
            icon="mdi:cursor-default-click"
            width="2rem"
            height="2rem"
            class="block text-white"
            aria-hidden="true"
          />
        </div>
      {/if}
    </div>
  {:else}
    <p class="text-sm text-zinc-500">{t(T.iframe_missing)}</p>
  {/if}
</div>
