"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSmartLinkSeenEvent = useSmartLinkSeenEvent;
var _react = require("react");
var _useAnalyticsEvents2 = require("../../../common/analytics/generated/use-analytics-events");
var _SmartLinkAnalyticsContext = require("../../../utils/analytics/SmartLinkAnalyticsContext");
var _flexible = require("../../../utils/flexible");
/**
 * Fires `ui.smartLink.seen` once when a smart link with status `unauthorized`
 * enters the viewport. Uses refs internally so it never causes re-renders,
 * which is important for SSR.
 */
function useSmartLinkSeenEvent(_ref) {
  var appearance = _ref.appearance,
    children = _ref.children,
    id = _ref.id,
    ui = _ref.ui,
    _ref$url = _ref.url,
    url = _ref$url === void 0 ? '' : _ref$url;
  var _useAnalyticsEvents = (0, _useAnalyticsEvents2.useAnalyticsEvents)(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var _useSmartLinkAnalytic = (0, _SmartLinkAnalyticsContext.useSmartLinkAnalyticsUtils)(),
    getByUrl = _useSmartLinkAnalytic.getByUrl;
  var getAnalyticsProps = (0, _react.useCallback)(function () {
    var isFlexibleUi = (0, _flexible.isFlexibleUiCard)(children, ui);
    var display = isFlexibleUi ? 'flexible' : appearance;
    return {
      display: display,
      id: id
    };
  }, [appearance, children, id, ui]);
  var statusRef = (0, _react.useRef)();
  var analyticsPropsRef = (0, _react.useRef)(null);
  var hasIntersectedRef = (0, _react.useRef)(false);
  var hasFiredSeenRef = (0, _react.useRef)(false);
  (0, _react.useEffect)(function () {
    analyticsPropsRef.current = getAnalyticsProps();
  }, [getAnalyticsProps]);
  var maybeFireSeenEvent = (0, _react.useCallback)(function () {
    if (!hasFiredSeenRef.current && hasIntersectedRef.current && statusRef.current === 'unauthorized') {
      var payload = getByUrl(url, analyticsPropsRef.current);
      fireEvent('ui.smartLink.seen', payload === null || payload === void 0 ? void 0 : payload.attributes);
      hasFiredSeenRef.current = true;
    }
  }, [fireEvent, getByUrl, url]);
  var onIntersecting = (0, _react.useCallback)(function () {
    if (hasIntersectedRef.current) {
      return;
    }
    hasIntersectedRef.current = true;
    maybeFireSeenEvent();
  }, [maybeFireSeenEvent]);
  var onStatusSettled = (0, _react.useCallback)(function (status) {
    statusRef.current = status;
    maybeFireSeenEvent();
  }, [maybeFireSeenEvent]);
  return (0, _react.useMemo)(function () {
    return {
      onIntersecting: onIntersecting,
      onStatusSettled: onStatusSettled
    };
  }, [onIntersecting, onStatusSettled]);
}