import { datadogRum } from "@datadog/browser-rum";
import { reactPlugin } from "@datadog/browser-rum-react";

// import { getCookieConsent } from "../hooks/useCookieConsent";

// Check if user has consented to analytics cookies before initializing
// const consent = getCookieConsent();
// const hasAnalyticsConsent = consent?.analytics ?? false;

datadogRum.init({
  applicationId: "8e268e1a-1be0-44c6-b12a-978530d497c7",
  clientToken: "pub1761af09ab04e215cc90d34da6ac576b",
  site: "datadoghq.com",
  service: "xtablo-ui",
  env: import.meta.env.MODE,

  // Specify a version number to identify the deployed version of your application in Datadog
  // version: '1.0.0',
  sessionSampleRate: 100,
  sessionReplaySampleRate: 80,
  defaultPrivacyLevel: "mask-user-input",
  plugins: [reactPlugin({ router: true })],
  trackViewsManually: true,
  trackUserInteractions: true,
  trackResources: true,
  // TODO: Uncomment when we have enough data
  // trackingConsent: hasAnalyticsConsent ? "granted" : "not-granted",
  trackingConsent: "granted",
  startSessionReplayRecordingManually: false,
});

// TODO: Uncomment when we have enough data

// Listen for storage changes to update tracking consent when cookie preferences change
// window.addEventListener("storage", (event) => {
//   if (event.key === "xtablo-cookie-consent") {
//     const newConsent = getCookieConsent();
//     const newHasAnalyticsConsent = newConsent?.analytics ?? false;

//     datadogRum.setTrackingConsent(newHasAnalyticsConsent ? "granted" : "not-granted");
//   }
// });

// Also listen for changes within the same tab (storage event doesn't fire for same-origin changes)
// const originalSetItem = localStorage.setItem;
// localStorage.setItem = function setItem(key, value) {
//   const result = originalSetItem.apply(this, [key, value]);
//   if (key === "xtablo-cookie-consent") {
//     const newConsent = getCookieConsent();
//     const newHasAnalyticsConsent = newConsent?.analytics ?? false;

//     datadogRum.setTrackingConsent(newHasAnalyticsConsent ? "granted" : "not-granted");
//   }

//   return result;
// };

export default datadogRum;
