import React, { useEffect } from "react";
import { useSelector } from "react-redux";
import { useMatomo } from "@jonkoops/matomo-tracker-react";
import { LS_MATOMO_USER_SESSION_TIMER, LS_MATOMO_TOPIC_VISITED, MATOMO_TOPIC_CHANGE_ACTION, MATOMO_TOPIC_CHANGE_TIMER } from "../../utils/constants";
function MatomoTracker() {
  const {
    trackPageView,
    trackEvent,
    pushInstruction
  } = useMatomo();
  const disableCookies = useSelector(state => state.app.disableCookies);
  const consentGiven = useSelector(state => state.app.consentGiven);
  const activeTopicKey = useSelector(state => {
    var _state$app$activeTopi;
    return (_state$app$activeTopi = state.app.activeTopic) === null || _state$app$activeTopi === void 0 ? void 0 : _state$app$activeTopi.key;
  });

  // Start tracking page view when the consent has been given
  useEffect(() => {
    var _localStorage, _localStorage2;
    if (!trackPageView || !pushInstruction || !consentGiven) {
      return;
    }
    pushInstruction("setConsentGiven");
    if (disableCookies) {
      // it's important that this instruction happens after the setConsentGiven instruction.
      pushInstruction("disableCookies");
    }
    trackPageView();

    // Start the clock to avoid duplicate 'User topic change' event tracking.
    (_localStorage = localStorage) === null || _localStorage === void 0 || _localStorage.setItem(LS_MATOMO_USER_SESSION_TIMER, Date.now());
    (_localStorage2 = localStorage) === null || _localStorage2 === void 0 || _localStorage2.setItem(LS_MATOMO_TOPIC_VISITED, "");
  }, [disableCookies, consentGiven, trackPageView, pushInstruction]);

  // Track topic change event within 30 min.
  useEffect(() => {
    var _localStorage3, _localStorage4;
    if (!activeTopicKey || !consentGiven || !trackEvent || !localStorage) {
      return;
    }
    const startDate = ((_localStorage3 = localStorage) === null || _localStorage3 === void 0 ? void 0 : _localStorage3.getItem(LS_MATOMO_USER_SESSION_TIMER)) || 0;
    const topicVisited = ((_localStorage4 = localStorage) === null || _localStorage4 === void 0 ? void 0 : _localStorage4.getItem(LS_MATOMO_TOPIC_VISITED)) || "";

    // A matomo user session is 30 min by default.
    if (Date.now() - startDate > MATOMO_TOPIC_CHANGE_TIMER || topicVisited.indexOf("".concat(activeTopicKey, ",")) === -1) {
      var _localStorage5;
      // within 30 min
      // Track the topic change
      trackEvent({
        category: activeTopicKey,
        action: MATOMO_TOPIC_CHANGE_ACTION
      });
      (_localStorage5 = localStorage) === null || _localStorage5 === void 0 || _localStorage5.setItem(LS_MATOMO_TOPIC_VISITED, "".concat(topicVisited + activeTopicKey, ","));
    }
  }, [activeTopicKey, trackEvent, consentGiven]);
  return null;
}
export default /*#__PURE__*/React.memo(MatomoTracker);
//# sourceMappingURL=MatomoTracker.js.map