import Script from "next/script";

export function Analytics() {
  const websiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID;
  const scriptUrl = process.env.NEXT_PUBLIC_UMAMI_SCRIPT_URL;

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

  let hostUrl: string | undefined;
  try {
    hostUrl = new URL(scriptUrl).origin;
  } catch {
    hostUrl = undefined;
  }

  return (
    <Script
      async
      data-host-url={hostUrl}
      data-website-id={websiteId}
      defer
      src={scriptUrl}
      strategy="afterInteractive"
    />
  );
}
