import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import React, { lazy, Suspense, useCallback, useEffect, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { di } from 'react-magnetic-di';
// eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
import uuid from 'uuid';
import { useAnalyticsEvents } from '../../common/analytics/generated/use-analytics-events';
import { failUfoExperience, startUfoExperience } from '../../state/analytics';
import { importWithRetry } from '../../utils';
import { useSmartLinkAnalyticsContext } from '../../utils/analytics/SmartLinkAnalyticsContext';
import { isFlexibleUiCard } from '../../utils/flexible';
import { clearMarks, clearMeasures } from '../../utils/performance';
import { LoadingCardLink } from './component-lazy/LoadingCardLink';
export var LazyCardWithUrlContent = /*#__PURE__*/lazy(function () {
  return importWithRetry(function () {
    return import( /* webpackChunkName: "@atlaskit-internal_smartcard-urlcardcontent" */'./component-lazy/index');
  });
});
export function CardWithURLRenderer(props) {
  // eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
  var _useState = useState(function () {
      return props.id ? props.id : uuid();
    }),
    _useState2 = _slicedToArray(_useState, 1),
    id = _useState2[0];
  var _useAnalyticsEvents = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  useEffect(function () {
    // ComponentWillUnmount
    return function () {
      clearMarks(id);
      clearMeasures(id);
    };
  }, [id]);
  var url = props.url,
    appearance = props.appearance,
    isSelected = props.isSelected,
    isHovered = props.isHovered,
    frameStyle = props.frameStyle,
    onClick = props.onClick,
    container = props.container,
    onResolve = props.onResolve,
    onError = props.onError,
    testId = props.testId,
    actionOptions = props.actionOptions,
    inheritDimensions = props.inheritDimensions,
    platform = props.platform,
    embedIframeRef = props.embedIframeRef,
    embedIframeUrlType = props.embedIframeUrlType,
    inlinePreloaderStyle = props.inlinePreloaderStyle,
    children = props.children,
    ui = props.ui,
    showHoverPreview = props.showHoverPreview,
    hoverPreviewOptions = props.hoverPreviewOptions,
    placeholder = props.placeholder,
    fallbackComponent = props.fallbackComponent,
    removeTextHighlightingFromTitle = props.removeTextHighlightingFromTitle,
    resolvingPlaceholder = props.resolvingPlaceholder,
    truncateInline = props.truncateInline,
    CompetitorPrompt = props.CompetitorPrompt,
    disablePreviewPanel = props.disablePreviewPanel;
  var isFlexibleUi = isFlexibleUiCard(children, ui);
  var analyticsContext = useSmartLinkAnalyticsContext({
    display: isFlexibleUi ? 'flexible' : appearance,
    id: id,
    url: url !== null && url !== void 0 ? url : ''
  });
  var errorHandler = useCallback(function (error, info) {
    var componentStack = info.componentStack;
    var errorInfo = {
      componentStack: componentStack
    };
    // NB: APIErrors are thrown in response to Object Resolver Service. We do not
    // fire an event for these, as they do not cover failed UI render events.
    // The rest of the errors caught here are unexpected, and correlate
    // to the reliability of the smart-card front-end components.
    // Likewise, chunk loading errors are not caused by a failure of smart-card rendering.
    if (error.name === 'ChunkLoadError') {
      fireEvent('operational.smartLink.chunkLoadFailed', _objectSpread(_objectSpread({}, analyticsContext === null || analyticsContext === void 0 ? void 0 : analyticsContext.attributes), {}, {
        display: appearance,
        error: error,
        errorInfo: errorInfo,
        definitionId: null
      }));
    } else if (error.name !== 'APIError') {
      startUfoExperience('smart-link-rendered', id || 'NULL');
      failUfoExperience('smart-link-rendered', id || 'NULL');
      failUfoExperience('smart-link-authenticated', id || 'NULL');
      fireEvent('ui.smartLink.renderFailed', _objectSpread(_objectSpread({}, analyticsContext === null || analyticsContext === void 0 ? void 0 : analyticsContext.attributes), {}, {
        display: isFlexibleUi ? 'flexible' : appearance,
        id: id !== null && id !== void 0 ? id : null,
        error: error,
        errorInfo: errorInfo
      }));
    }
    onError && onError({
      status: 'errored',
      url: url !== null && url !== void 0 ? url : '',
      err: error
    });
  }, [analyticsContext === null || analyticsContext === void 0 ? void 0 : analyticsContext.attributes, appearance, fireEvent, id, isFlexibleUi, onError, url]);
  if (!url) {
    throw new Error('@atlaskit/smart-card: url property is missing.');
  }
  var defaultFallBackComponent = function defaultFallBackComponent() {
    return null;
  };
  var FallbackComponent = fallbackComponent !== null && fallbackComponent !== void 0 ? fallbackComponent : defaultFallBackComponent;
  var ErrorFallback = function ErrorFallback() {
    return /*#__PURE__*/React.createElement(FallbackComponent, null);
  };
  var cardWithUrlProps = {
    id: id,
    url: url,
    appearance: appearance,
    onClick: onClick,
    isSelected: isSelected,
    isHovered: isHovered,
    frameStyle: frameStyle,
    container: container,
    onResolve: onResolve,
    onError: onError,
    testId: testId,
    actionOptions: actionOptions,
    inheritDimensions: inheritDimensions,
    platform: platform,
    embedIframeRef: embedIframeRef,
    embedIframeUrlType: embedIframeUrlType,
    inlinePreloaderStyle: inlinePreloaderStyle,
    ui: ui,
    showHoverPreview: showHoverPreview,
    hoverPreviewOptions: hoverPreviewOptions,
    placeholder: placeholder,
    removeTextHighlightingFromTitle: removeTextHighlightingFromTitle,
    resolvingPlaceholder: resolvingPlaceholder,
    truncateInline: truncateInline,
    CompetitorPrompt: CompetitorPrompt,
    disablePreviewPanel: disablePreviewPanel
  };
  return /*#__PURE__*/React.createElement(ErrorBoundary, {
    FallbackComponent: ErrorFallback,
    onError: errorHandler
  }, /*#__PURE__*/React.createElement(Suspense, {
    fallback: /*#__PURE__*/React.createElement(LoadingCardLink, cardWithUrlProps)
  }, /*#__PURE__*/React.createElement(LazyCardWithUrlContent, cardWithUrlProps, children)));
}