<script lang="ts">
  import { onMount } from "svelte";
  import { getBlockLayoutClasses } from "../../lib/block-layout";
  import type { OpnFormBlockData } from "../../lib/block-types";

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

  const layoutClasses = $derived(getBlockLayoutClasses(block.layout));
  const formId = $derived((block.formId ?? "").trim());
  const baseUrl = $derived(
    (typeof block.baseUrl === "string" && block.baseUrl.trim()
      ? block.baseUrl.trim()
      : "https://opnform.pm86.de"
    ).replace(/\/$/, ""),
  );
  const iframeSrc = $derived(formId ? `${baseUrl}/forms/${formId}` : "");
  const iframeTitle = $derived(block.iframeTitle?.trim() || "Kontaktformular");

  let iframeEl = $state<HTMLIFrameElement | null>(null);

  onMount(() => {
    if (!formId || !iframeEl) return;

    const el = iframeEl;
    // Höhe ausschließlich per DOM verwalten – nie über Sveltes style= Prop.
    el.style.height = "600px";
    el.style.transition = "height 0.25s ease";
    // Verhindert native Browser-Scrollbar im Iframe, egal ob Höhe stimmt oder nicht.
    el.setAttribute("scrolling", "no");

    const scriptUrl = `${baseUrl}/widgets/iframe.min.js`;

    function handleMessage(event: MessageEvent) {
      if (event.source !== el.contentWindow) return;
      const d = event.data;
      let h: number | undefined;
      if (typeof d === "number") {
        h = d;
      } else if (d && typeof d === "object") {
        h = d.height ?? d.frameHeight ?? d.iFrameHeight;
      } else if (typeof d === "string" && d.startsWith("[iFrameSizer]")) {
        const parts = d.split(":");
        h = parts.length >= 2 ? parseFloat(parts[1]) : undefined;
      }
      if (typeof h === "number" && h > 50) {
        el.style.height = `${Math.ceil(h)}px`;
      }
    }
    window.addEventListener("message", handleMessage);

    function runInit() {
      const w = window as Window & {
        initEmbed?: (id: string, opts: { autoResize?: boolean }) => void;
      };
      w.initEmbed?.(formId, { autoResize: true });
    }

    const existing = document.querySelector<HTMLScriptElement>(
      `script[data-opnform-embed-js="${baseUrl}"]`,
    );
    const w = window as Window & { initEmbed?: unknown };

    if (existing) {
      if (typeof w.initEmbed === "function") {
        queueMicrotask(runInit);
      } else {
        existing.addEventListener("load", runInit, { once: true });
      }
    } else {
      const s = document.createElement("script");
      s.type = "text/javascript";
      s.async = true;
      s.src = scriptUrl;
      s.dataset.opnformEmbedJs = baseUrl;
      s.onload = () => runInit();
      document.body.appendChild(s);
    }

    return () => {
      window.removeEventListener("message", handleMessage);
    };
  });
</script>

<div
  class="{layoutClasses} content-opnform w-[calc(100%+2rem)] max-w-none -mx-4 min-w-0 overflow-visible border border-stein-200 lg:rounded-lg px-0 py-3 md:w-[calc(100%+3rem)] md:-mx-6 md:px-4 md:py-4"
  data-block-type="opnform"
  data-block-slug={block._slug}
>
  {#if iframeSrc}
    <iframe
      bind:this={iframeEl}
      style="border: none; width: 100%;"
      id={formId}
      title={iframeTitle}
      src={iframeSrc}
    ></iframe>
  {:else}
    <p class="text-sm text-stein-500">OpnForm: formId fehlt.</p>
  {/if}
</div>
