"use client";

import { normalizeHeadType } from "@/src/server_api/utils/helpers";
import Script from "next/script";
import React from "react";
import { createPortal } from "react-dom";

interface HeadScript {
  code: string;
  type?: string;
  name?: string;
  rel?: string;
}

interface Props {
  scripts: Record<string, HeadScript>;
}

export const DynamicHeadScripts: React.FC<Props> = ({ scripts }) => {
  const [mounted, setMounted] = React.useState(false);

  React.useEffect(() => {
    setMounted(true);
  }, []);

  if (!scripts || !mounted) return null;

  return createPortal(
    <>
      {Object.entries(scripts).map(([key, script]) => {
        if (!script?.code) return null;

        const normalized = normalizeHeadType(script.type);

        if (normalized === "meta") {
          return <meta key={key} name={key} content={script.code} />;
        }

        if (normalized === "link") {
          return <link key={key} rel={script.rel || "preconnect"} href={script.code} />;
        }

        if (normalized === "jsonld") {
          return <script key={key} type="application/ld+json" dangerouslySetInnerHTML={{ __html: script.code }} />;
        }

        if (normalized === "module") {
          return <script key={key} type="module" dangerouslySetInnerHTML={{ __html: script.code }} />;
        }

        if (normalized === "src") {
          return <Script key={key} src={script.code} strategy="afterInteractive" />;
        }

        return <script key={key} dangerouslySetInnerHTML={{ __html: script.code }} />;
      })}
    </>,
    document.head
  );
};
