import _extends from "@babel/runtime/helpers/extends";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useCallback, useState } from 'react';
import { usePrefetch } from '../../../state';
import { startUfoExperience } from '../../../state/analytics/ufoExperiences';
import useIntersectionObserver from '../../../state/hooks/use-intersection-observer';
import { useSmartLinkSeenEvent } from '../../../state/hooks/use-smart-link-seen-event';
import { shouldSample } from '../../../utils/shouldSample';
import CardLoaderWrapper from '../card-loader-wrapper';
import { CardWithUrlContent } from '../component';
import { LoadingCardLink } from './LoadingCardLink';
export var LazyIntersectionObserverCard = function LazyIntersectionObserverCard(props) {
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isIntersected = _useState2[0],
    setIsIntersected = _useState2[1];
  var _useState3 = useState(shouldSample()),
    _useState4 = _slicedToArray(_useState3, 1),
    shouldSendRenderedUFOEvent = _useState4[0];
  var appearance = props.appearance,
    children = props.children,
    id = props.id,
    onErrorCallback = props.onError,
    ui = props.ui,
    url = props.url;
  var prefetch = usePrefetch(url);
  var ComponentObserver = appearance === 'inline' ? 'span' : 'div';
  var _useSmartLinkSeenEven = useSmartLinkSeenEvent({
      appearance: appearance,
      children: children,
      id: id,
      ui: ui,
      url: url
    }),
    onSeenIntersecting = _useSmartLinkSeenEven.onIntersecting,
    onStatusSettled = _useSmartLinkSeenEven.onStatusSettled;
  var onError = useCallback(function (data) {
    if (data !== null && data !== void 0 && data.status) {
      onStatusSettled(data.status);
    }
    onErrorCallback === null || onErrorCallback === void 0 || onErrorCallback(data);
  }, [onStatusSettled, onErrorCallback]);
  var onIntersection = useCallback(function (isIntersecting) {
    if (isIntersecting) {
      if (shouldSendRenderedUFOEvent) {
        startUfoExperience('smart-link-rendered', id);
      }
      onSeenIntersecting();
      setIsIntersected(true);
    } else {
      prefetch();
    }
  }, [id, onSeenIntersecting, prefetch, shouldSendRenderedUFOEvent]);
  var ref = useIntersectionObserver({
    onIntersection: onIntersection
  });
  var content = isIntersected ? /*#__PURE__*/React.createElement(CardWithUrlContent, _extends({}, props, {
    onError: onError
  })) : /*#__PURE__*/React.createElement(ComponentObserver, {
    ref: ref
  }, /*#__PURE__*/React.createElement(LoadingCardLink, props));
  return /*#__PURE__*/React.createElement(CardLoaderWrapper, {
    appearance: appearance
  }, content);
};