import _extends from "@babel/runtime/helpers/extends";
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 const LazyIntersectionObserverCard = props => {
  const [isIntersected, setIsIntersected] = useState(false);
  const [shouldSendRenderedUFOEvent] = useState(shouldSample());
  const {
    appearance,
    children,
    id,
    onError: onErrorCallback,
    ui,
    url
  } = props;
  const prefetch = usePrefetch(url);
  const ComponentObserver = appearance === 'inline' ? 'span' : 'div';
  const {
    onIntersecting: onSeenIntersecting,
    onStatusSettled
  } = useSmartLinkSeenEvent({
    appearance,
    children,
    id,
    ui,
    url
  });
  const onError = useCallback(data => {
    if (data !== null && data !== void 0 && data.status) {
      onStatusSettled(data.status);
    }
    onErrorCallback === null || onErrorCallback === void 0 ? void 0 : onErrorCallback(data);
  }, [onStatusSettled, onErrorCallback]);
  const onIntersection = useCallback(isIntersecting => {
    if (isIntersecting) {
      if (shouldSendRenderedUFOEvent) {
        startUfoExperience('smart-link-rendered', id);
      }
      onSeenIntersecting();
      setIsIntersected(true);
    } else {
      prefetch();
    }
  }, [id, onSeenIntersecting, prefetch, shouldSendRenderedUFOEvent]);
  const ref = useIntersectionObserver({
    onIntersection
  });
  const 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);
};