"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CardWithURLRenderer = CardWithURLRenderer;
exports.LazyCardWithUrlContent = void 0;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _reactErrorBoundary = require("react-error-boundary");
var _reactMagneticDi = require("react-magnetic-di");
var _uuid = _interopRequireDefault(require("uuid"));
var _useAnalyticsEvents2 = require("../../common/analytics/generated/use-analytics-events");
var _analytics = require("../../state/analytics");
var _utils = require("../../utils");
var _SmartLinkAnalyticsContext = require("../../utils/analytics/SmartLinkAnalyticsContext");
var _flexible = require("../../utils/flexible");
var _performance = require("../../utils/performance");
var _LoadingCardLink = require("./component-lazy/LoadingCardLink");
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) { (0, _defineProperty2.default)(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; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != (0, _typeof2.default)(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); } // eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
var LazyCardWithUrlContent = exports.LazyCardWithUrlContent = /*#__PURE__*/(0, _react.lazy)(function () {
  return (0, _utils.importWithRetry)(function () {
    return Promise.resolve().then(function () {
      return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_smartcard-urlcardcontent" */'./component-lazy/index'));
    });
  });
});
function CardWithURLRenderer(props) {
  // eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
  var _useState = (0, _react.useState)(function () {
      return props.id ? props.id : (0, _uuid.default)();
    }),
    _useState2 = (0, _slicedToArray2.default)(_useState, 1),
    id = _useState2[0];
  var _useAnalyticsEvents = (0, _useAnalyticsEvents2.useAnalyticsEvents)(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  (0, _react.useEffect)(function () {
    // ComponentWillUnmount
    return function () {
      (0, _performance.clearMarks)(id);
      (0, _performance.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 = (0, _flexible.isFlexibleUiCard)(children, ui);
  var analyticsContext = (0, _SmartLinkAnalyticsContext.useSmartLinkAnalyticsContext)({
    display: isFlexibleUi ? 'flexible' : appearance,
    id: id,
    url: url !== null && url !== void 0 ? url : ''
  });
  var errorHandler = (0, _react.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') {
      (0, _analytics.startUfoExperience)('smart-link-rendered', id || 'NULL');
      (0, _analytics.failUfoExperience)('smart-link-rendered', id || 'NULL');
      (0, _analytics.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.default.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.default.createElement(_reactErrorBoundary.ErrorBoundary, {
    FallbackComponent: ErrorFallback,
    onError: errorHandler
  }, /*#__PURE__*/_react.default.createElement(_react.Suspense, {
    fallback: /*#__PURE__*/_react.default.createElement(_LoadingCardLink.LoadingCardLink, cardWithUrlProps)
  }, /*#__PURE__*/_react.default.createElement(LazyCardWithUrlContent, cardWithUrlProps, children)));
}