"use client";

import { usePathname } from "next/navigation";
import { useEffect } from "react";

const PORTAL = process.env.NEXT_PUBLIC_HUBSPOT_PORTAL_ID?.trim() || "";

/** HubSpot page-view tracking. Off until NEXT_PUBLIC_HUBSPOT_PORTAL_ID is set. */
export default function HubSpotTracking() {
  const pathname = usePathname();

  useEffect(() => {
    if (!PORTAL) return;
    const w = window as Window & { _hsq?: unknown[] };
    w._hsq = w._hsq || [];
    if (document.getElementById("hs-script-loader")) return;
    const script = document.createElement("script");
    script.id = "hs-script-loader";
    script.async = true;
    script.src = `https://js-na2.hs-scripts.com/${PORTAL}.js`;
    document.body.appendChild(script);
  }, []);

  useEffect(() => {
    if (!PORTAL) return;
    const w = window as Window & { _hsq?: unknown[] };
    w._hsq = w._hsq || [];
    w._hsq.push(["setPath", pathname]);
    w._hsq.push(["trackPageView"]);
  }, [pathname]);

  return null;
}
