import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { usePrefetch } from '../../../state';
import { startUfoExperience } from '../../../state/analytics/ufoExperiences';
import { shouldSample } from '../../../utils/shouldSample';
import { CardWithUrlContent } from '../component';
import { LoadingCardLink } from './LoadingCardLink';

// This property enables the intersection observer to be run once the
// HTML element being observed is within `X` px of the target container it is
// being compared to. Since the default container is the `document`, we set this
// up to check once a Smart Link is within `X` px from the bottom of the viewport.
var ROOT_MARGIN_VERTICAL = '360px';
export function LazyIntersectionObserverCard(props) {
  var ref = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isIntersecting = _useState2[0],
    setIsIntersecting = _useState2[1];
  var _useState3 = useState(shouldSample()),
    _useState4 = _slicedToArray(_useState3, 1),
    shouldSendRenderedUFOEvent = _useState4[0];
  var appearance = props.appearance,
    url = props.url,
    id = props.id;
  var prefetch = usePrefetch(url);
  var Component = appearance === 'inline' ? 'span' : 'div';
  var ComponentObserver = Component;
  var onIntersection = useCallback(function (entries, observer) {
    var isVisible = entries.some(function (entry) {
      return entry.isIntersecting;
    });
    if (isVisible) {
      if (shouldSendRenderedUFOEvent) {
        startUfoExperience('smart-link-rendered', id);
      }
      setIsIntersecting(true);
      observer.disconnect();
    } else {
      prefetch();
    }
  }, [id, prefetch, shouldSendRenderedUFOEvent]);
  useEffect(function () {
    if (!ref.current) {
      return;
    }
    var intersectionObserver = new IntersectionObserver(onIntersection, {
      rootMargin: "".concat(ROOT_MARGIN_VERTICAL, " 0px ").concat(ROOT_MARGIN_VERTICAL, " 0px")
    });
    intersectionObserver.observe(ref.current);
    return function () {
      return intersectionObserver.disconnect();
    };
  }, [ref, onIntersection]);
  var content = isIntersecting ? /*#__PURE__*/React.createElement(CardWithUrlContent, props) : /*#__PURE__*/React.createElement(ComponentObserver, {
    ref: ref
  }, /*#__PURE__*/React.createElement(LoadingCardLink, props));

  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
  return /*#__PURE__*/React.createElement(Component, {
    className: "loader-wrapper"
  }, content);
}