"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IframeDwellTracker = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
/**
 * @jsxRuntime classic
 * @jsx jsx
 */

/**
 * A kind of cheap logarithmic backoff. Fire analytics after the user has
 * dwelled for 5 seconds, then 10 seconds, and so on.
 */
var INTERVALS_TO_LOG = [5, 10, 15, 20, 25, 30, 45, 60, 90, 120, 180];
var IframeDwellTracker = exports.IframeDwellTracker = function IframeDwellTracker(_ref) {
  var isIframeLoaded = _ref.isIframeLoaded,
    isMouseOver = _ref.isMouseOver,
    iframePercentVisible = _ref.iframePercentVisible,
    onIframeDwell = _ref.onIframeDwell;
  var _useState = (0, _react.useState)({
      time: 0,
      percentVisible: 0
    }),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    dwell = _useState2[0],
    setDwell = _useState2[1];
  var dwellTimeoutId = (0, _react.useRef)();

  // fire analytics when the dwell timer reaches 5 seconds
  (0, _react.useEffect)(function () {
    if (dwell.time > 0 && INTERVALS_TO_LOG.includes(dwell.time)) {
      onIframeDwell && onIframeDwell(dwell.time, dwell.percentVisible);
    }
  }, [dwell, onIframeDwell]);

  // start and stop tracking dwell time
  (0, _react.useEffect)(function () {
    var incrementDwellTime = function incrementDwellTime() {
      // callback is called on dwell state changes, so change percentVisible and time together
      setDwell(function (_ref2) {
        var time = _ref2.time;
        return {
          time: time + 1,
          // snapshot of percent visible, rounded down to nearest 5%
          percentVisible: Math.floor((iframePercentVisible || 0) * 20) * 5
        };
      });
    };

    // Require: iframe loaded, mouse over, and >75% visible.
    // Note: isWindowFocused is intentionally not required - it's unreliable and
    // prevents tracking. The mouse over check is sufficient to indicate user engagement.
    var shouldTrack = isIframeLoaded && isMouseOver && iframePercentVisible > 0.75;
    if (shouldTrack) {
      if (dwellTimeoutId.current) {
        clearInterval(dwellTimeoutId.current);
      }
      dwellTimeoutId.current = setInterval(incrementDwellTime, 1000);
    } else {
      if (dwellTimeoutId.current) {
        clearInterval(dwellTimeoutId.current);
        dwellTimeoutId.current = undefined;
      }
    }
    return function () {
      if (dwellTimeoutId.current) {
        clearInterval(dwellTimeoutId.current);
      }
    };
  }, [setDwell, isMouseOver, isIframeLoaded, iframePercentVisible]);
  return null;
};