"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.hoverCardClassName = exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _analyticsNext = require("@atlaskit/analytics-next");
var _linkProvider = require("@atlaskit/link-provider");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _platformFeatureFlagsReact = require("@atlaskit/platform-feature-flags-react");
var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals");
var _useAnalyticsEvents2 = require("../../../common/analytics/generated/use-analytics-events");
var _constants = require("../../../constants");
var _helpers = require("../../../state/helpers");
var _useRovoConfig2 = _interopRequireDefault(require("../../../state/hooks/use-rovo-config"));
var _useSmartLinkCrossProductUrlWrapper = require("../../../state/hooks/use-smart-link-cross-product-url-wrapper");
var _store = require("../../../state/store");
var _utils = require("../../../utils");
var _aiSummary = require("../../../utils/ai-summary");
var _click = require("../../../utils/analytics/click");
var _clickHelpers = require("../../../utils/click-helpers");
var _styled = require("../styled");
var _utils2 = require("../utils");
var _ContentContainer = _interopRequireDefault(require("./ContentContainer"));
var _forbidden = _interopRequireDefault(require("./views/forbidden"));
var _resolved = _interopRequireDefault(require("./views/resolved"));
var _resolving = _interopRequireDefault(require("./views/resolving"));
var _unauthorised = _interopRequireDefault(require("./views/unauthorised"));
var _RovoUnauthorisedView = _interopRequireDefault(require("./views/unauthorised/RovoUnauthorisedView"));
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" != _typeof(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); }
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; }
var hoverCardClassName = exports.hoverCardClassName = 'smart-links-hover-preview';
var useIsResolvedView = function useIsResolvedView(_ref) {
  var _hoverPreviewOptions$;
  var cardState = _ref.cardState,
    hoverPreviewOptions = _ref.hoverPreviewOptions;
  return !(hoverPreviewOptions !== null && hoverPreviewOptions !== void 0 && (_hoverPreviewOptions$ = hoverPreviewOptions.render) !== null && _hoverPreviewOptions$ !== void 0 && _hoverPreviewOptions$.call(hoverPreviewOptions)) && cardState.status === 'resolved';
};
var useServices = function useServices(_ref2) {
  var url = _ref2.url;
  var linkState = (0, _store.useSmartCardState)(url);
  var services = (0, _helpers.getServices)(linkState.details);
  return services;
};
var useIsUnauthorisedView = function useIsUnauthorisedView(_ref3) {
  var _hoverPreviewOptions$2;
  var cardState = _ref3.cardState,
    url = _ref3.url,
    hoverPreviewOptions = _ref3.hoverPreviewOptions;
  var services = useServices({
    url: url
  });
  return !(hoverPreviewOptions !== null && hoverPreviewOptions !== void 0 && (_hoverPreviewOptions$2 = hoverPreviewOptions.render) !== null && _hoverPreviewOptions$2 !== void 0 && _hoverPreviewOptions$2.call(hoverPreviewOptions)) && cardState.status === 'unauthorized' && Boolean(services === null || services === void 0 ? void 0 : services.length);
};
var useIsShowPreauthBetterHovercard = function useIsShowPreauthBetterHovercard(props) {
  var _useRovoConfig = (0, _useRovoConfig2.default)(),
    rovoConfig = _useRovoConfig.rovoOptions;
  return Boolean(useIsUnauthorisedView(props) && (rovoConfig === null || rovoConfig === void 0 ? void 0 : rovoConfig.isRovoEnabled) && (0, _expValEquals.expValEquals)('platform_sl_3p_preauth_better_hovercard', 'isEnabled', true));
};
var HoverCardContent = function HoverCardContent(_ref4) {
  var _linkState$status, _cardState$details;
  var _ref4$id = _ref4.id,
    id = _ref4$id === void 0 ? '' : _ref4$id,
    cardState = _ref4.cardState,
    onActionClick = _ref4.onActionClick,
    onResolve = _ref4.onResolve,
    renderers = _ref4.renderers,
    url = _ref4.url,
    onMouseEnter = _ref4.onMouseEnter,
    onMouseLeave = _ref4.onMouseLeave,
    onDismiss = _ref4.onDismiss,
    actionOptions = _ref4.actionOptions,
    hoverPreviewOptions = _ref4.hoverPreviewOptions;
  var _useAnalyticsEventsNe = (0, _analyticsNext.useAnalyticsEvents)(),
    createAnalyticsEvent = _useAnalyticsEventsNe.createAnalyticsEvent;
  var _useAnalyticsEvents = (0, _useAnalyticsEvents2.useAnalyticsEvents)(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var extensionKey = (0, _react.useMemo)(function () {
    return (0, _helpers.getExtensionKey)(cardState.details);
  }, [cardState.details]);
  var linkState = (0, _store.useSmartCardState)(url);
  var linkStatus = (_linkState$status = linkState.status) !== null && _linkState$status !== void 0 ? _linkState$status : 'pending';
  var definitionId = (0, _react.useMemo)(function () {
    return (0, _helpers.getDefinitionId)(cardState.details);
  }, [cardState.details]);
  var _useSmartLinkContext = (0, _linkProvider.useSmartLinkContext)(),
    isAdminHubAIEnabled = _useSmartLinkContext.isAdminHubAIEnabled,
    product = _useSmartLinkContext.product;
  var isAISummaryEnabled = (0, _aiSummary.getIsAISummaryEnabled)(isAdminHubAIEnabled, cardState.details);
  var services = (0, _helpers.getServices)(linkState.details);
  var appendCrossProductAnalyticsParams = (0, _useSmartLinkCrossProductUrlWrapper.useSmartLinkCrossProductUrlWrapperGated)({
    details: linkState.details
  });
  var statusRef = (0, _react.useRef)(linkStatus);
  var fireEventRef = (0, _react.useRef)(fireEvent);
  var definitionIdRef = (0, _react.useRef)(definitionId);
  (0, _react.useEffect)(function () {
    /**
     * Must access object value via ref because its not stable
     * and it can trigger useEffect to re-run below
     */
    if (statusRef.current !== linkStatus) {
      statusRef.current = linkStatus;
    }
    if (fireEventRef.current !== fireEvent) {
      fireEventRef.current = fireEvent;
    }
    if (definitionIdRef.current !== definitionId) {
      definitionIdRef.current = definitionId;
    }
  }, [linkStatus, fireEvent, definitionId]);
  (0, _react.useEffect)(function () {
    var _definitionIdRef$curr;
    var previewDisplay = 'card';
    var previewInvokeMethod = 'mouse_hover';
    var cardOpenTime = Date.now();
    var fireEventCurrent = fireEventRef.current;
    fireEventCurrent('ui.hoverCard.viewed', {
      previewDisplay: previewDisplay,
      previewInvokeMethod: previewInvokeMethod,
      definitionId: (_definitionIdRef$curr = definitionIdRef.current) !== null && _definitionIdRef$curr !== void 0 ? _definitionIdRef$curr : null
    });
    return function () {
      var _definitionIdRef$curr2;
      var hoverTime = Date.now() - cardOpenTime;
      fireEventCurrent('ui.hoverCard.dismissed', {
        previewDisplay: previewDisplay,
        previewInvokeMethod: previewInvokeMethod,
        hoverTime: hoverTime,
        definitionId: (_definitionIdRef$curr2 = definitionIdRef.current) !== null && _definitionIdRef$curr2 !== void 0 ? _definitionIdRef$curr2 : null
      });
    };
  }, []);
  var getDestinationUrl = (0, _react.useCallback)(function () {
    var _getClickUrl, _appendCrossProductAn;
    // FIXME: destinationUrl should be rendered in the DOM anchor href instead of derived at click time
    var preferredUrl = (_getClickUrl = (0, _helpers.getClickUrl)(url, linkState.details)) !== null && _getClickUrl !== void 0 ? _getClickUrl : url;
    return (_appendCrossProductAn = appendCrossProductAnalyticsParams(preferredUrl)) !== null && _appendCrossProductAn !== void 0 ? _appendCrossProductAn : preferredUrl;
  }, [appendCrossProductAnalyticsParams, linkState.details, url]);

  // Middle-click handler to trigger fire3PClickEvent on middle-clicks.
  // Scope is limited to 3P click analytics to keep the experiment focused.
  var onAuxClick = (0, _react.useCallback)(function (event) {
    var destinationUrl = getDestinationUrl();
    (0, _clickHelpers.updateAnchorHref)(event, destinationUrl);
  }, [getDestinationUrl]);

  // Right-click handler to trigger fire3PClickEvent on right-clicks.
  // Scope is limited to 3P click analytics to keep the experiment focused.
  var onContextMenu = (0, _react.useCallback)(function (event) {
    var destinationUrl = getDestinationUrl();
    (0, _clickHelpers.updateAnchorHref)(event, destinationUrl);
  }, [getDestinationUrl]);
  var onClick = (0, _react.useCallback)(function (event) {
    if ((0, _platformFeatureFlags.fg)('platform_smartlink_xpc_url_wrapping')) {
      // Prevent the anchor's native navigation so we can open the destination URL
      // with cross-product analytics query parameters appended.
      // The cross-product params are client-only and cannot be rendered
      // server-side. Falls back to the original `url` prop if the event target is
      // not an anchor element.
      event.preventDefault();
      var _getAnchorAttributesF = (0, _clickHelpers.getAnchorAttributesFromEvent)(event),
        target = _getAnchorAttributesF.target;
      var destinationUrl = getDestinationUrl();
      (0, _clickHelpers.updateAnchorHref)(event, destinationUrl);
      window.open(destinationUrl, target);
    }
    var isModifierKeyPressed = (0, _utils.isSpecialEvent)(event);
    fireEvent('ui.smartLink.clicked.titleGoToLink', {
      id: id,
      display: _constants.CardDisplay.HoverCardPreview,
      isModifierKeyPressed: isModifierKeyPressed,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
    });
    (0, _click.fireLinkClickedEvent)(createAnalyticsEvent)(event);
  }, [createAnalyticsEvent, getDestinationUrl, id, fireEvent, definitionId]);
  var data = (_cardState$details = cardState.details) === null || _cardState$details === void 0 ? void 0 : _cardState$details.data;
  var _getMetadata = (0, _utils2.getMetadata)(extensionKey, data),
    subtitle = _getMetadata.subtitle;
  var titleMaxLines = subtitle && subtitle.length > 0 ? 1 : 2;
  var titleBlockProps = {
    maxLines: titleMaxLines,
    size: _constants.SmartLinkSize.Large,
    position: _constants.SmartLinkPosition.Center,
    subtitle: subtitle,
    anchorTarget: product === 'ATLAS' ? '_self' : undefined
  };
  var uiOptions = _styled.flexibleUiOptions;
  uiOptions.enableSnippetRenderer = true;
  var flexibleCardProps = _objectSpread(_objectSpread({
    appearance: _constants.CardDisplay.HoverCardPreview,
    cardState: cardState,
    onClick: onClick
  }, (0, _platformFeatureFlags.fg)('platform_smartlink_xpc_url_wrapping') ? {
    onAuxClick: onAuxClick,
    onContextMenu: onContextMenu
  } : undefined), {}, {
    onResolve: onResolve,
    origin: 'smartLinkPreviewHoverCard',
    renderers: renderers,
    actionOptions: actionOptions,
    ui: uiOptions,
    url: url,
    children: null
  });
  var onClickStopPropagation = (0, _react.useCallback)(function (e) {
    return e.stopPropagation();
  }, []);
  var useIsResolvedViewGated = (0, _platformFeatureFlagsReact.functionUnionWithCondition)(function () {
    return (0, _platformFeatureFlags.fg)('platform_sl_3p_preauth_better_hovercard_killswitch');
  }, useIsResolvedView, function () {
    return undefined;
  });
  var useIsUnauthorisedViewGated = (0, _platformFeatureFlagsReact.functionUnionWithCondition)(function () {
    return (0, _platformFeatureFlags.fg)('platform_sl_3p_preauth_better_hovercard_killswitch');
  }, useIsUnauthorisedView, function () {
    return undefined;
  });
  var useIsShowPreauthBetterHovercardGated = (0, _platformFeatureFlagsReact.functionUnionWithCondition)(function () {
    return (0, _platformFeatureFlags.fg)('platform_sl_3p_preauth_better_hovercard_killswitch');
  }, useIsShowPreauthBetterHovercard, function () {
    return undefined;
  });
  var isResolved = useIsResolvedViewGated({
    cardState: cardState,
    hoverPreviewOptions: hoverPreviewOptions
  });
  var isUnauthorised = useIsUnauthorisedViewGated({
    cardState: cardState,
    url: url,
    hoverPreviewOptions: hoverPreviewOptions
  });
  var showPreauthBetterHovercard = useIsShowPreauthBetterHovercardGated({
    cardState: cardState,
    url: url,
    hoverPreviewOptions: hoverPreviewOptions
  });
  if ((0, _platformFeatureFlags.fg)('platform_sl_3p_preauth_better_hovercard_killswitch')) {
    var cardView = function (_hoverPreviewOptions$3) {
      var overrideView = hoverPreviewOptions === null || hoverPreviewOptions === void 0 || (_hoverPreviewOptions$3 = hoverPreviewOptions.render) === null || _hoverPreviewOptions$3 === void 0 ? void 0 : _hoverPreviewOptions$3.call(hoverPreviewOptions);
      if (overrideView) {
        return overrideView;
      }
      if (cardState.status === 'errored') {
        return null;
      }
      if (cardState.status === 'resolving' || cardState.metadataStatus === 'pending') {
        return /*#__PURE__*/_react.default.createElement(_resolving.default, {
          flexibleCardProps: flexibleCardProps,
          titleBlockProps: titleBlockProps
        });
      }
      if (isUnauthorised) {
        if (showPreauthBetterHovercard) {
          return /*#__PURE__*/_react.default.createElement(_RovoUnauthorisedView.default, {
            extensionKey: extensionKey,
            id: id,
            flexibleCardProps: flexibleCardProps,
            onDismiss: onDismiss,
            url: url
          });
        }
        return /*#__PURE__*/_react.default.createElement(_unauthorised.default, {
          extensionKey: extensionKey,
          id: id,
          flexibleCardProps: flexibleCardProps,
          url: url
        });
      }
      if (cardState.status === 'forbidden' || cardState.status === 'not_found') {
        return /*#__PURE__*/_react.default.createElement(_forbidden.default, {
          flexibleCardProps: flexibleCardProps
        });
      }
      if (isResolved) {
        return /*#__PURE__*/_react.default.createElement(_resolved.default, {
          cardState: cardState,
          extensionKey: extensionKey,
          flexibleCardProps: flexibleCardProps,
          isAISummaryEnabled: isAISummaryEnabled,
          onActionClick: onActionClick,
          titleBlockProps: titleBlockProps
        });
      }
      return null;
    }();
    return cardView ? /*#__PURE__*/_react.default.createElement(_ContentContainer.default, {
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onClickStopPropagation,
      widthAppearance: showPreauthBetterHovercard ? 'slim' : undefined,
      isAIEnabled: isAISummaryEnabled,
      url: url
    }, cardView) : null;
  } else {
    var getCardView = function getCardView(cardState) {
      var _hoverPreviewOptions$4;
      var overrideView = hoverPreviewOptions === null || hoverPreviewOptions === void 0 || (_hoverPreviewOptions$4 = hoverPreviewOptions.render) === null || _hoverPreviewOptions$4 === void 0 ? void 0 : _hoverPreviewOptions$4.call(hoverPreviewOptions);
      if (overrideView) {
        return overrideView;
      }
      if (cardState.status === 'errored') {
        return null;
      }
      if (cardState.status === 'resolving' || cardState.metadataStatus === 'pending') {
        return /*#__PURE__*/_react.default.createElement(_resolving.default, {
          flexibleCardProps: flexibleCardProps,
          titleBlockProps: titleBlockProps
        });
      }
      if (cardState.status === 'unauthorized' && services !== null && services !== void 0 && services.length) {
        return /*#__PURE__*/_react.default.createElement(_unauthorised.default, {
          extensionKey: extensionKey,
          id: id,
          flexibleCardProps: flexibleCardProps,
          url: url
        });
      }
      if (cardState.status === 'forbidden' || cardState.status === 'not_found') {
        return /*#__PURE__*/_react.default.createElement(_forbidden.default, {
          flexibleCardProps: flexibleCardProps
        });
      }
      if (cardState.status === 'resolved') {
        return /*#__PURE__*/_react.default.createElement(_resolved.default, {
          cardState: cardState,
          extensionKey: extensionKey,
          flexibleCardProps: flexibleCardProps,
          isAISummaryEnabled: isAISummaryEnabled,
          onActionClick: onActionClick,
          titleBlockProps: titleBlockProps
        });
      }
      return null;
    };
    var _cardView = getCardView(cardState);
    return _cardView ? /*#__PURE__*/_react.default.createElement(_ContentContainer.default, {
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onClickStopPropagation,
      isAIEnabled: isAISummaryEnabled,
      url: url
    }, _cardView) : null;
  }
};
var HoverCardContentWithViewVariant = function HoverCardContentWithViewVariant(props) {
  var showPreauthBetterHovercard = useIsShowPreauthBetterHovercard(props);
  var data = (0, _react.useMemo)(function () {
    var viewVariant = 'default';
    if (showPreauthBetterHovercard) {
      viewVariant = 'rovo-unauthorised-view';
    }
    return {
      attributes: {
        viewVariant: viewVariant
      }
    };
  }, [showPreauthBetterHovercard]);
  return /*#__PURE__*/_react.default.createElement(_analyticsNext.AnalyticsContext, {
    data: data
  }, /*#__PURE__*/_react.default.createElement(HoverCardContent, props));
};
var _default_1 = (0, _platformFeatureFlagsReact.componentWithCondition)(function () {
  return (0, _platformFeatureFlags.fg)('platform_sl_3p_preauth_better_hovercard_killswitch');
}, HoverCardContentWithViewVariant, HoverCardContent);
var _default = exports.default = _default_1;