services/analytics/analytics.jsjavascript
import { AnalyticsSDK } from "./AnalyticsSDK";

/*
  Project wrapper around the vendored AnalyticsSDK (see AnalyticsSDK.js,
  mirrored from ~/Development/js/messe-tracking/analytics.js). Replaces the
  old Matomo-based services/tracking/tracking.jsx.

  Unlike the raw SDK (which throws if 'exponatId'/'apiKey' are missing), this
  wrapper degrades gracefully to a no-op with a console warning - matching the
  previous Matomo integration's behavior when VITE_MATOMO_SITE_ID was empty.
  This matters because the SDK is instantiated once at module-load time, so a
  hard throw here would crash the app on every `npm run dev`/CI run until the
  AWS backend (exponatId/apiKey/endpoint) is provisioned.
*/

const exponatId = import.meta.env.VITE_ANALYTICS_EXPONAT_ID;
const apiKey = import.meta.env.VITE_ANALYTICS_API_KEY;
const endpoint = import.meta.env.VITE_ANALYTICS_ENDPOINT;

const noop = () => {};
const disabledAnalytics = {
  trackEvent: noop,
  trackPageView: noop,
  trackHotspot: noop,
  trackSlideOrStory: noop,
};

let analytics = disabledAnalytics;

if (!exponatId || !apiKey) {
  // eslint-disable-next-line no-console
  console.warn(
    "[Analytics] Tracking deactivated: missing 'VITE_ANALYTICS_EXPONAT_ID' or 'VITE_ANALYTICS_API_KEY'."
  );
} else {
  const instance = new AnalyticsSDK({ exponatId, apiKey, endpoint });

  // bind so call sites can destructure (`const { trackEvent } = useAnalytics()`)
  // without losing `this` inside the SDK's prototype methods
  analytics = {
    trackEvent: instance.trackEvent.bind(instance),
    trackPageView: instance.trackPageView.bind(instance),
    trackHotspot: instance.trackHotspot.bind(instance),
    trackSlideOrStory: instance.trackSlideOrStory.bind(instance),
  };

  if (import.meta.env.DEV) {
    // the raw instance, not the bound subset above - matches the SDK's own
    // documented dev-console usage (e.g. `window.analytics.flush()`)
    window.analytics = instance;
  }
}

/**
 * Returns the analytics singleton's tracking functions. Not a real React
 * hook (no state/context involved) - kept as a hook-shaped function so
 * existing call sites read the same as the old `useTracking()`.
 */
export const useAnalytics = () => analytics;

export { analytics };