import { useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";

type Settings = {
  gtm_id: string | null;
  meta_pixel_id: string | null;
  ga4_id: string | null;
  google_ads_id: string | null;
  tiktok_pixel_id: string | null;
  custom_head_html: string | null;
};

// Avoid double-injection across navigations.
const injected = new Set<string>();

function injectScript(id: string, src: string | null, inline?: string) {
  if (typeof document === "undefined") return;
  if (injected.has(id) || document.getElementById(id)) {
    injected.add(id);
    return;
  }
  const s = document.createElement("script");
  s.id = id;
  s.async = true;
  if (src) s.src = src;
  if (inline) s.innerHTML = inline;
  document.head.appendChild(s);
  injected.add(id);
}

export function SiteScripts() {
  useEffect(() => {
    let cancelled = false;
    (async () => {
      const { data } = await supabase
        .from("site_settings")
        .select("gtm_id,meta_pixel_id,ga4_id,google_ads_id,tiktok_pixel_id,custom_head_html")
        .eq("id", true)
        .maybeSingle();
      if (cancelled || !data) return;
      const s = data as Settings;

      // Google Tag Manager
      if (s.gtm_id) {
        injectScript(
          "gtm-script",
          null,
          `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','${s.gtm_id}');`,
        );
      }

      // GA4
      if (s.ga4_id) {
        injectScript("ga4-loader", `https://www.googletagmanager.com/gtag/js?id=${s.ga4_id}`);
        injectScript(
          "ga4-init",
          null,
          `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config','${s.ga4_id}');`,
        );
      }

      // Google Ads
      if (s.google_ads_id) {
        injectScript(
          "gads-loader",
          `https://www.googletagmanager.com/gtag/js?id=${s.google_ads_id}`,
        );
        injectScript(
          "gads-init",
          null,
          `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config','${s.google_ads_id}');`,
        );
      }

      // Meta Pixel
      if (s.meta_pixel_id) {
        injectScript(
          "meta-pixel",
          null,
          `!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init','${s.meta_pixel_id}');fbq('track','PageView');`,
        );
      }

      // TikTok Pixel
      if (s.tiktok_pixel_id) {
        injectScript(
          "tiktok-pixel",
          null,
          `!function (w, d, t) {w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e};ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};ttq.load('${s.tiktok_pixel_id}');ttq.page();}(window, document, 'ttq');`,
        );
      }

      // Custom head HTML (scripts, meta tags, etc.) set via admin panel
      if (s.custom_head_html && !injected.has("custom-head-html") && !document.getElementById("custom-head-html-marker")) {
        const wrapper = document.createElement("div");
        wrapper.innerHTML = s.custom_head_html;
        const marker = document.createElement("meta");
        marker.id = "custom-head-html-marker";
        document.head.appendChild(marker);
        Array.from(wrapper.childNodes).forEach((node) => {
          if (node.nodeType === 1 && (node as Element).tagName === "SCRIPT") {
            const src = node as HTMLScriptElement;
            const s2 = document.createElement("script");
            for (const attr of Array.from(src.attributes)) s2.setAttribute(attr.name, attr.value);
            s2.text = src.text;
            document.head.appendChild(s2);
          } else {
            document.head.appendChild(node.cloneNode(true));
          }
        });
        injected.add("custom-head-html");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  return null;
}
