import { Head } from "@inertiajs/react";
import { useEffect } from "react";

type SeoPayload = {
  title?: string;
  description?: string;
  code_start_head?: string;
  code_end_head?: string;
  code_start_body?: string;
  code_end_body?: string;
};

type SeoHeadProps = {
  seo?: SeoPayload | null;
};

export default function SeoHead({ seo }: SeoHeadProps) {
  useEffect(() => {
    const mountHtml = (target: HTMLElement, html?: string) => {
      if (!html?.trim()) {
        return null;
      }

      const wrapper = document.createElement("div");
      wrapper.innerHTML = html;
      const nodes = Array.from(wrapper.childNodes);
      nodes.forEach((node) => target.appendChild(node));

      return () => {
        nodes.forEach((node) => {
          if (node.parentNode === target) {
            target.removeChild(node);
          }
        });
      };
    };

    const cleanups = [
      mountHtml(document.head, seo?.code_start_head),
      mountHtml(document.head, seo?.code_end_head),
      mountHtml(document.body, seo?.code_start_body),
      mountHtml(document.body, seo?.code_end_body),
    ].filter(Boolean) as Array<() => void>;

    return () => {
      cleanups.forEach((cleanup) => cleanup());
    };
  }, [
    seo?.code_start_head,
    seo?.code_end_head,
    seo?.code_start_body,
    seo?.code_end_body,
  ]);

  return (
    <Head>
      {seo?.title ? <title>{seo.title}</title> : null}
      {seo?.description ? <meta name="description" content={seo.description} /> : null}
    </Head>
  );
}
