"use client";

import { useEffect, useState } from "react";
import Script from "next/script";
import type { SnippetsData } from "@/types";

interface Props {
  snippets?: SnippetsData;
  pageSnippets?: SnippetsData;
  renderTop?: boolean;
  renderBottom?: boolean;
}

function insertMetaTag(name: string, content: string) {
  if (!name || typeof document === "undefined") return;
  const existing = document.head.querySelector(`meta[name="${name}"]`);
  if (existing) return;
  const m = document.createElement("meta");
  m.setAttribute("name", name);
  m.setAttribute("content", content);
  document.head.appendChild(m);
}

export default function SnippetsInjector({
  snippets,
  pageSnippets,
  renderTop = false,
  renderBottom = false,
}: Props) {
  const [scripts, setScripts] = useState<{ id: string; code?: string; src?: string }[]>([]);

  useEffect(() => {
    const allHead = [snippets?.head, pageSnippets?.head]
      .filter(Boolean)
      .join("\n");

    if (!allHead) return;

    // Handle Meta Tags
    const metaRegex = /<meta\s+name=["']([^"']+)["']\s+content=["']([^"']+)["']\s*\/?>>?/gi;
    let m: RegExpExecArray | null;
    while ((m = metaRegex.exec(allHead))) {
      insertMetaTag(m[1], m[2]);
    }

    // Extract Scripts (Inline and External)
    const scriptRegex = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
    let s: RegExpExecArray | null;
    const extractedScripts: { id: string; code?: string; src?: string }[] = [];
    let idx = 0;

    while ((s = scriptRegex.exec(allHead))) {
      const attributes = s[1];
      const content = s[2]?.trim();
      
      const srcMatch = /src=["']([^"']+)["']/i.exec(attributes);
      const src = srcMatch ? srcMatch[1] : undefined;

      if (src || content) {
        extractedScripts.push({
          id: `cms-deferred-script-${idx}`,
          src,
          code: content || undefined,
        });
        idx++;
      }
    }
    setScripts(extractedScripts);
  }, [snippets, pageSnippets]);

  useEffect(() => {
    if (typeof document === "undefined") return;

    const insertBodyHtml = (html: string, position: "top" | "bottom") => {
      if (!html) return;

      const existing = Array.from(
        document.body.querySelectorAll(`[data-cms-snippet="${position}"]`)
      );
      existing.forEach((node) => node.remove());

      const template = document.createElement("template");
      template.innerHTML = html;
      const nodes = Array.from(template.content.childNodes);
      nodes.forEach((node, index) => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          (node as HTMLElement).setAttribute("data-cms-snippet", position);
          (node as HTMLElement).setAttribute(
            "data-cms-snippet-idx",
            String(index)
          );
        }
        if (position === "top") {
          document.body.insertBefore(node, document.body.firstChild);
        } else {
          document.body.appendChild(node);
        }
      });
    };

    if (renderTop) {
      const topHtml = [snippets?.bodyTop, pageSnippets?.bodyTop]
        .filter(Boolean)
        .join("\n");
      if (topHtml) insertBodyHtml(topHtml, "top");
    }

    if (renderBottom) {
      const bottomHtml = [snippets?.bodyBottom, pageSnippets?.bodyBottom]
        .filter(Boolean)
        .join("\n");
      if (bottomHtml) insertBodyHtml(bottomHtml, "bottom");
    }
  }, [snippets, pageSnippets, renderTop, renderBottom]);

  return (
    <>
      {scripts.map((s) => (
        <Script
          key={s.id}
          id={s.id}
          src={s.src}
          strategy="lazyOnload"
          dangerouslySetInnerHTML={s.code ? { __html: s.code } : undefined}
        />
      ))}
    </>
  );
}


