import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
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, { useCallback, useEffect, useMemo, useRef } from 'react';
import { AnalyticsContext, useAnalyticsEvents as useAnalyticsEventsNext } from '@atlaskit/analytics-next';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { fg } from '@atlaskit/platform-feature-flags';
import { componentWithCondition, functionUnionWithCondition } from '@atlaskit/platform-feature-flags-react';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { expValEqualsNoExposure } from '@atlaskit/tmp-editor-statsig/exp-val-equals-no-exposure';
import { useAnalyticsEvents } from '../../../common/analytics/generated/use-analytics-events';
import { CardDisplay, SmartLinkPosition, SmartLinkSize } from '../../../constants';
import extractRovoChatAction from '../../../extractors/flexible/actions/extract-rovo-chat-action';
import { getDefinitionId, getExtensionKey, getServices } from '../../../state/helpers';
import useInlineActionNudgeExperiment from '../../../state/hooks/use-inline-action-nudge-experiment';
import useRovoConfig from '../../../state/hooks/use-rovo-config';
import { useSmartCardState } from '../../../state/store';
import { isSpecialEvent } from '../../../utils';
import { getIsAISummaryEnabled } from '../../../utils/ai-summary';
import { fireLinkClickedEvent } from '../../../utils/analytics/click';
import { flexibleUiOptions } from '../styled';
import { getMetadata } from '../utils';
import ContentContainer from './ContentContainer';
import HoverCardForbiddenView from './views/forbidden';
import HoverCardResolvedView from './views/resolved';
import HoverCardLoadingView from './views/resolving';
import HoverCardUnauthorisedView from './views/unauthorised';
import RovoUnauthorisedView from './views/unauthorised/RovoUnauthorisedView';
export var 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 = useSmartCardState(url);
  var services = 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 = useRovoConfig(),
    rovoConfig = _useRovoConfig.rovoOptions;
  return Boolean(useIsUnauthorisedView(props) && (rovoConfig === null || rovoConfig === void 0 ? void 0 : rovoConfig.isRovoEnabled) && 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,
    showRovoResolvedView = _ref4.showRovoResolvedView;
  var _useAnalyticsEventsNe = useAnalyticsEventsNext(),
    createAnalyticsEvent = _useAnalyticsEventsNe.createAnalyticsEvent;
  var _useAnalyticsEvents = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var extensionKey = useMemo(function () {
    return getExtensionKey(cardState.details);
  }, [cardState.details]);
  var linkState = useSmartCardState(url);
  var linkStatus = (_linkState$status = linkState.status) !== null && _linkState$status !== void 0 ? _linkState$status : 'pending';
  var definitionId = useMemo(function () {
    return getDefinitionId(cardState.details);
  }, [cardState.details]);
  var _useSmartLinkContext = useSmartLinkContext(),
    isAdminHubAIEnabled = _useSmartLinkContext.isAdminHubAIEnabled,
    product = _useSmartLinkContext.product;
  var isAISummaryEnabled = getIsAISummaryEnabled(isAdminHubAIEnabled, cardState.details);
  var services = getServices(linkState.details);
  var statusRef = useRef(linkStatus);
  var fireEventRef = useRef(fireEvent);
  var definitionIdRef = useRef(definitionId);
  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]);
  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 onClick = useCallback(function (event) {
    var isModifierKeyPressed = isSpecialEvent(event);
    fireEvent('ui.smartLink.clicked.titleGoToLink', {
      id: id,
      display: CardDisplay.HoverCardPreview,
      isModifierKeyPressed: isModifierKeyPressed,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
    });
    fireLinkClickedEvent(createAnalyticsEvent)(event);
  }, [createAnalyticsEvent, id, fireEvent, definitionId]);
  var data = (_cardState$details = cardState.details) === null || _cardState$details === void 0 ? void 0 : _cardState$details.data;
  var _getMetadata = getMetadata(extensionKey, data),
    subtitle = _getMetadata.subtitle;
  var titleMaxLines = subtitle && subtitle.length > 0 ? 1 : 2;

  // Platform apps (Home, Goals, Projects, and Teams) should by default open in the same tab when the FF is enabled.
  var isSameTabAlignmentEnabled = fg('townsquare-same-tab-alignment-gcko-849');
  var anchorTarget = product === 'ATLAS' && isSameTabAlignmentEnabled ? '_self' : undefined;
  var titleBlockProps = _objectSpread({
    maxLines: titleMaxLines,
    size: SmartLinkSize.Large,
    position: SmartLinkPosition.Center,
    subtitle: subtitle
  }, isSameTabAlignmentEnabled ? {
    anchorTarget: anchorTarget
  } : undefined);
  var uiOptions = flexibleUiOptions;
  uiOptions.enableSnippetRenderer = true;
  var flexibleCardProps = {
    appearance: CardDisplay.HoverCardPreview,
    cardState: cardState,
    onClick: onClick,
    onResolve: onResolve,
    origin: 'smartLinkPreviewHoverCard',
    renderers: renderers,
    actionOptions: actionOptions,
    ui: uiOptions,
    url: url,
    children: null
  };
  var onClickStopPropagation = useCallback(function (e) {
    return e.stopPropagation();
  }, []);
  var useIsResolvedViewGated = functionUnionWithCondition(function () {
    return fg('platform_sl_3p_preauth_better_hovercard_killswitch');
  }, useIsResolvedView, function () {
    return undefined;
  });
  var useIsUnauthorisedViewGated = functionUnionWithCondition(function () {
    return fg('platform_sl_3p_preauth_better_hovercard_killswitch');
  }, useIsUnauthorisedView, function () {
    return undefined;
  });
  var useIsShowPreauthBetterHovercardGated = functionUnionWithCondition(function () {
    return 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 (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.createElement(HoverCardLoadingView, {
          flexibleCardProps: flexibleCardProps,
          titleBlockProps: titleBlockProps
        });
      }
      if (isUnauthorised) {
        if (showPreauthBetterHovercard) {
          return /*#__PURE__*/React.createElement(RovoUnauthorisedView, {
            extensionKey: extensionKey,
            id: id,
            flexibleCardProps: flexibleCardProps,
            onDismiss: onDismiss,
            url: url
          });
        }
        return /*#__PURE__*/React.createElement(HoverCardUnauthorisedView, {
          extensionKey: extensionKey,
          id: id,
          flexibleCardProps: flexibleCardProps,
          url: url
        });
      }
      if (cardState.status === 'forbidden' || cardState.status === 'not_found') {
        return /*#__PURE__*/React.createElement(HoverCardForbiddenView, {
          flexibleCardProps: flexibleCardProps
        });
      }
      var is3PInlinePostAuthActionsEnabled = fg('rovogrowth-640-inline-action-nudge-fg') && expValEqualsNoExposure('rovogrowth-640-inline-action-nudge-exp', 'isEnabled', true);
      if (isResolved) {
        return /*#__PURE__*/React.createElement(HoverCardResolvedView, _extends({}, fg('platform_sl_3p_auth_rovo_action_kill_switch') || is3PInlinePostAuthActionsEnabled ? {
          actionOptions: actionOptions,
          showRovoResolvedView: showRovoResolvedView
        } : undefined, {
          cardState: cardState,
          extensionKey: extensionKey,
          flexibleCardProps: flexibleCardProps,
          isAISummaryEnabled: isAISummaryEnabled,
          onActionClick: onActionClick,
          titleBlockProps: titleBlockProps
        }));
      }
      return null;
    }();
    return cardView ? /*#__PURE__*/React.createElement(ContentContainer, {
      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.createElement(HoverCardLoadingView, {
          flexibleCardProps: flexibleCardProps,
          titleBlockProps: titleBlockProps
        });
      }
      if (cardState.status === 'unauthorized' && services !== null && services !== void 0 && services.length) {
        return /*#__PURE__*/React.createElement(HoverCardUnauthorisedView, {
          extensionKey: extensionKey,
          id: id,
          flexibleCardProps: flexibleCardProps,
          url: url
        });
      }
      if (cardState.status === 'forbidden' || cardState.status === 'not_found') {
        return /*#__PURE__*/React.createElement(HoverCardForbiddenView, {
          flexibleCardProps: flexibleCardProps
        });
      }
      var is3PInlinePostAuthActionsEnabled = fg('rovogrowth-640-inline-action-nudge-fg') && expValEqualsNoExposure('rovogrowth-640-inline-action-nudge-exp', 'isEnabled', true);
      if (cardState.status === 'resolved') {
        return /*#__PURE__*/React.createElement(HoverCardResolvedView, _extends({}, fg('platform_sl_3p_auth_rovo_action_kill_switch') || is3PInlinePostAuthActionsEnabled ? {
          actionOptions: actionOptions,
          showRovoResolvedView: showRovoResolvedView
        } : undefined, {
          cardState: cardState,
          extensionKey: extensionKey,
          flexibleCardProps: flexibleCardProps,
          isAISummaryEnabled: isAISummaryEnabled,
          onActionClick: onActionClick,
          titleBlockProps: titleBlockProps
        }));
      }
      return null;
    };
    var _cardView = getCardView(cardState);
    return _cardView ? /*#__PURE__*/React.createElement(ContentContainer, {
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onClickStopPropagation,
      isAIEnabled: isAISummaryEnabled,
      url: url
    }, _cardView) : null;
  }
};
var HoverCardContentWithViewVariant = function HoverCardContentWithViewVariant(props) {
  var cardState = props.cardState,
    actionOptions = props.actionOptions,
    url = props.url;
  var rovoConfig = useRovoConfig();
  var isResolved = useIsResolvedView(props);
  var showPreauthBetterHovercard = useIsShowPreauthBetterHovercard(props);
  var showRovoResolvedView = useMemo(function () {
    return isResolved && cardState.details && extractRovoChatAction({
      response: cardState.details,
      rovoConfig: rovoConfig,
      actionOptions: actionOptions
    }) !== undefined;
  }, [actionOptions, cardState.details, rovoConfig, isResolved]);
  var _useInlineActionNudge = useInlineActionNudgeExperiment(url, true, actionOptions),
    rovoActionsCtaShown = _useInlineActionNudge.isEnabled;
  var data = useMemo(function () {
    var viewVariant = 'default';
    if (showRovoResolvedView && (expValEqualsNoExposure('platform_sl_3p_auth_rovo_action', 'isEnabled', true) || expValEqualsNoExposure('rovogrowth-640-inline-action-nudge-exp', 'isEnabled', true))) {
      viewVariant = 'rovo-resolved-view';
    } else if (showPreauthBetterHovercard) {
      viewVariant = 'rovo-unauthorised-view';
    }
    return {
      attributes: {
        viewVariant: viewVariant,
        rovoActionsCtaShown: rovoActionsCtaShown
      }
    };
  }, [showRovoResolvedView, showPreauthBetterHovercard, rovoActionsCtaShown]);
  return /*#__PURE__*/React.createElement(AnalyticsContext, {
    data: data
  }, /*#__PURE__*/React.createElement(HoverCardContent, _extends({}, props, {
    showRovoResolvedView: showRovoResolvedView
  })));
};
var _default_1 = componentWithCondition(function () {
  // We need to read both of them to sutisfy some of the tests that expect both to be checked.
  var flagA = fg('platform_sl_3p_preauth_better_hovercard_killswitch');
  var flagB = fg('platform_sl_3p_auth_rovo_action_kill_switch');
  var flagC = fg('rovogrowth-640-inline-action-nudge-fg');
  return flagA || flagB || flagC;
}, HoverCardContentWithViewVariant, HoverCardContent);
export default _default_1;