"use client";

import { useEffect, useRef, useState } from "react";
import { Maximize2 } from "lucide-react";
import { getKotschClassicTool } from "@/tools/kotsch-imports";
import type { Tool } from "@/tools/registry";

/**
 * Rendert die vollständig nach Toolaro kopierten Kotsch-Tools.
 * Die Tool-Logik liegt als eigenständige HTML-Datei unter /public/embed/<slug>.html
 * und läuft komplett auf Toolaro – kein Verweis und kein Laden von kotsch.tech.
 *
 * Same-Origin-Iframe → saubere CSS-/JS-Isolation, das Original-Tool funktioniert 1:1.
 */
export function KotschClassicTool({ tool }: { tool: Tool }) {
  const imported = getKotschClassicTool(tool.slug);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [height, setHeight] = useState(820);

  const src = `/embed/${tool.slug}.html`;

  // Iframe-Höhe automatisch an Tool-Inhalt anpassen
  useEffect(() => {
    const iframe = iframeRef.current;
    if (!iframe) return;

    function resize() {
      try {
        const doc = iframe?.contentDocument;
        if (doc?.body) {
          const h = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
          if (h > 200) setHeight(h + 24);
        }
      } catch {
        /* same-origin – sollte nicht werfen */
      }
    }

    iframe.addEventListener("load", () => {
      resize();
      // Mehrfach nachmessen, falls das Tool asynchron rendert
      const t1 = setTimeout(resize, 400);
      const t2 = setTimeout(resize, 1200);
      return () => {
        clearTimeout(t1);
        clearTimeout(t2);
      };
    });
    const interval = setInterval(resize, 2000);
    return () => clearInterval(interval);
  }, [src]);

  if (!imported) return null;

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-end">
        <a
          href={src}
          target="_blank"
          rel="noreferrer"
          className="inline-flex items-center gap-1.5 text-sm font-medium text-ink-secondary transition-colors hover:text-brand-700"
        >
          <Maximize2 className="h-3.5 w-3.5" />
          In neuem Tab öffnen
        </a>
      </div>

      <div className="overflow-hidden rounded-lg border border-ink-primary/[0.08] bg-surface-raised shadow-rest">
        <iframe
          ref={iframeRef}
          title={imported.name}
          src={src}
          className="w-full"
          style={{ height, minHeight: 600 }}
          loading="lazy"
        />
      </div>
    </div>
  );
}
