import Script from "next/script";

import { marketingFeatureSlugs } from "@/lib/marketing/features";

const publicAnalyticsPaths = new Set([
  "/",
  "/impressum",
  "/datenschutz",
  "/login",
  "/register",
  ...marketingFeatureSlugs.map((slug) => `/features/${slug}`),
]);

export function UmamiAnalytics() {
  const scriptUrl = process.env.NEXT_PUBLIC_UMAMI_SCRIPT_URL;
  const websiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID;
  const domains = process.env.NEXT_PUBLIC_UMAMI_DOMAINS;

  if (!scriptUrl || !websiteId) {
    return null;
  }

  return (
    <>
      <Script id="umami-before-send" strategy="afterInteractive">
        {`
          window.kitaPlanerUmamiBeforeSend = function (_type, payload) {
            try {
              var url = new URL(payload && payload.url ? payload.url : window.location.href, window.location.origin);
              var path = url.pathname.length > 1 && url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
              var allowedPaths = ${JSON.stringify(Array.from(publicAnalyticsPaths))};
              return allowedPaths.indexOf(path) === -1 ? false : payload;
            } catch (_error) {
              return false;
            }
          };
        `}
      </Script>
      <Script
        src={scriptUrl}
        strategy="afterInteractive"
        data-website-id={websiteId}
        data-domains={domains}
        data-exclude-search="true"
        data-exclude-hash="true"
        data-do-not-track="true"
        data-before-send="kitaPlanerUmamiBeforeSend"
      />
    </>
  );
}
