"use client";

import Script from "next/script";
import { usePathname } from "next/navigation";
import { useEffect, useRef } from "react";

/*
 * HubSpot tracking code (CTA QA BUG-28, dev step 7): page views and visit history on each contact's timeline, and
 * HubSpot's own Original Traffic Source. Loaded only when NEXT_PUBLIC_HUBSPOT_PORTAL_ID is set (24315290), so it
 * goes live when the HubSpot admin has turned off non-HubSpot form collection (otherwise each form would also be
 * collected as a second submission) and excluded the office IPs.
 * HubSpot records the first page load itself; each later in-app navigation is sent with setPath + trackPageView.
 * After a form is sent, monetize.js / the React forms call window.mzHubspotIdentify(email) to tie the visit history
 * to that contact.
 * HubSpot's chat widget is off for now, on every browser: this setting stops the tracking code from opening it, and
 * the #hubspot-messages-iframe-container rule in monetize.css hides it if it opens anyway. Tracking is unaffected.
 */
type Hsq = unknown[][];

if (typeof window !== "undefined") {
  (window as unknown as { hsConversationsSettings?: object }).hsConversationsSettings = { loadImmediately: false };
}

export default function HubSpotTracking({ portalId }: { portalId?: string }) {
  const pathname = usePathname();
  const first = useRef(true);

  useEffect(() => {
    if (!portalId) return;
    if (first.current) {
      first.current = false;
      return;
    }
    const w = window as unknown as { _hsq?: Hsq };
    const q = (w._hsq = w._hsq || []);
    q.push(["setPath", pathname + window.location.search]);
    q.push(["trackPageView"]);
  }, [pathname, portalId]);

  if (!portalId || !/^\d+$/.test(portalId)) return null;
  return <Script id="hs-script-loader" src={`https://js.hs-scripts.com/${portalId}.js`} strategy="afterInteractive" />;
}
