import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useAnalyticsEvents } from '../../../common/analytics/generated/use-analytics-events';
import { useSmartLinkAnalyticsUtils } from '../../../utils/analytics/SmartLinkAnalyticsContext';
import { isFlexibleUiCard } from '../../../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.
 */
export 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 = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var _useSmartLinkAnalytic = useSmartLinkAnalyticsUtils(),
    getByUrl = _useSmartLinkAnalytic.getByUrl;
  var getAnalyticsProps = useCallback(function () {
    var isFlexibleUi = isFlexibleUiCard(children, ui);
    var display = isFlexibleUi ? 'flexible' : appearance;
    return {
      display: display,
      id: id
    };
  }, [appearance, children, id, ui]);
  var statusRef = useRef();
  var analyticsPropsRef = useRef(null);
  var hasIntersectedRef = useRef(false);
  var hasFiredSeenRef = useRef(false);
  useEffect(function () {
    analyticsPropsRef.current = getAnalyticsProps();
  }, [getAnalyticsProps]);
  var maybeFireSeenEvent = 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 = useCallback(function () {
    if (hasIntersectedRef.current) {
      return;
    }
    hasIntersectedRef.current = true;
    maybeFireSeenEvent();
  }, [maybeFireSeenEvent]);
  var onStatusSettled = useCallback(function (status) {
    statusRef.current = status;
    maybeFireSeenEvent();
  }, [maybeFireSeenEvent]);
  return useMemo(function () {
    return {
      onIntersecting: onIntersecting,
      onStatusSettled: onStatusSettled
    };
  }, [onIntersecting, onStatusSettled]);
}