"use client";

import { useSyncExternalStore } from "react";
import Script from "next/script";
import { usePathname } from "next/navigation";
import { getConsentCookie } from "@/lib/cookie-consent";
import { LINKEDIN_PARTNER_ID, LINKEDIN_INSIGHT_SRC } from "@/lib/linkedin-insight";
import { isMarketingPath } from "@/lib/marketing-pages";

// Subscribe to marketing-consent changes (dispatched by the cookie banner).
function subscribe(callback: () => void) {
  window.addEventListener("cookie-consent-changed", callback);
  return () => window.removeEventListener("cookie-consent-changed", callback);
}
const getMarketingConsent = () => getConsentCookie()?.marketing ?? false;
const getServerMarketingConsent = () => false;

/**
 * Loads the LinkedIn Insight Tag only when ALL of these hold:
 *  - a partner ID is configured,
 *  - the user consented to marketing cookies, and
 *  - the current page is a marketing/funnel page (never a clinical page).
 * This enforces the HIPAA rule: no pixel on any screening/results/report page.
 */
export default function LinkedInInsightGate() {
  const pathname = usePathname();
  const marketingAllowed = useSyncExternalStore(
    subscribe,
    getMarketingConsent,
    getServerMarketingConsent
  );

  if (!LINKEDIN_PARTNER_ID || !marketingAllowed || !isMarketingPath(pathname)) {
    return null;
  }

  return (
    <>
      <Script id="linkedin-insight-init" strategy="afterInteractive">
        {`
          _linkedin_partner_id = "${LINKEDIN_PARTNER_ID}";
          window._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];
          window._linkedin_data_partner_ids.push(_linkedin_partner_id);
          window.lintrk = window.lintrk || function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};
        `}
      </Script>
      <Script
        id="linkedin-insight-loader"
        strategy="afterInteractive"
        src={LINKEDIN_INSIGHT_SRC}
      />
    </>
  );
}
