"use client";

import { useEffect, useRef } from "react";

function mountHtml(host: HTMLElement, html: string) {
  const template = document.createElement("template");
  template.innerHTML = html;
  const added: Node[] = [];
  for (const node of Array.from(template.content.childNodes)) {
    if (node instanceof HTMLScriptElement) {
      const script = document.createElement("script");
      for (const attr of Array.from(node.attributes)) {
        script.setAttribute(attr.name, attr.value);
      }
      script.text = node.text;
      host.appendChild(script);
      added.push(script);
    } else {
      const clone = node.cloneNode(true);
      host.appendChild(clone);
      added.push(clone);
    }
  }
  return () => {
    for (const node of added) node.parentNode?.removeChild(node);
  };
}

export function CodeSlot({ html, head = false }: { html: string; head?: boolean }) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!html.trim()) return;
    if (head) return mountHtml(document.head, html);
    const el = ref.current;
    if (!el) return;
    return mountHtml(el, html);
  }, [html, head]);

  if (head) return null;
  if (!html.trim()) return null;
  return <div ref={ref} className="cf-code-slot" />;
}
