import { readAnalyticsConsent } from "./cookie-consent-storage";

export type MatomoRuntimeConfig = Readonly<{
  baseUrl: string;
  siteId: string;
}>;

type MatomoWindow = Window &
  typeof globalThis & {
    _paq?: unknown[][];
  };

let injectPromise: Promise<void> | null = null;

export const getMatomoRuntimeConfig = (): MatomoRuntimeConfig | null => {
  const rawUrl = import.meta.env.VITE_MATOMO_URL;
  const rawSite = import.meta.env.VITE_MATOMO_SITE_ID;
  const url = typeof rawUrl === "string" ? rawUrl.trim() : "";
  const siteId = typeof rawSite === "string" ? rawSite.trim() : "";
  if (!url || !siteId) return null;
  const baseUrl = url.endsWith("/") ? url : `${url}/`;
  return { baseUrl, siteId };
};

export const isMatomoConfigured = (): boolean => getMatomoRuntimeConfig() !== null;

export const injectMatomoTracker = (cfg: MatomoRuntimeConfig): Promise<void> => {
  if (injectPromise) return injectPromise;
  injectPromise = new Promise<void>((resolve, reject) => {
    const w = window as MatomoWindow;
    w._paq = w._paq ?? [];
    w._paq.push(["setTrackerUrl", `${cfg.baseUrl}matomo.php`]);
    w._paq.push(["setSiteId", cfg.siteId]);
    const g = document.createElement("script");
    g.async = true;
    g.src = `${cfg.baseUrl}matomo.js`;
    g.onload = () => {
      const mw = window as MatomoWindow;
      mw._paq?.push(["enableLinkTracking"]);
      resolve();
    };
    g.onerror = () => reject(new Error("Failed to load matomo.js"));
    const s = document.getElementsByTagName("script")[0];
    if (s?.parentNode) {
      s.parentNode.insertBefore(g, s);
    } else {
      document.head.appendChild(g);
    }
  });
  return injectPromise;
};

export const trackMatomoPageView = (): void => {
  if (readAnalyticsConsent() !== "analytics-accepted") return;
  const w = window as MatomoWindow;
  if (!w._paq) return;
  w._paq.push(["setCustomUrl", window.location.href]);
  w._paq.push(["setDocumentTitle", document.title]);
  w._paq.push(["trackPageView"]);
};
