import React, { useCallback, useEffect, useMemo } from 'react';
import { useAnalyticsEvents as useAnalyticsEventsNext } from '@atlaskit/analytics-next';
import { extractSmartLinkEmbed } from '@atlaskit/link-extractors';
import { fg } from '@atlaskit/platform-feature-flags';
import { componentWithFG } from '@atlaskit/platform-feature-flags-react';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { editorExperiment } from '@atlaskit/tmp-editor-statsig/experiments';
import { useAnalyticsEvents } from '../../common/analytics/generated/use-analytics-events';
import { CardDisplay } from '../../constants';
import { useSmartLink } from '../../state';
import { succeedUfoExperience } from '../../state/analytics';
import { getClickUrl, getDefinitionId, getExtensionKey, getFirstPartyIdentifier, getObjectAri, getObjectIconUrl, getObjectName, getResourceType, getServices, getThirdPartyARI, isFinalState } from '../../state/helpers';
import { SmartLinkModalProvider } from '../../state/modal';
import { isSpecialClick, isSpecialEvent, isSpecialKey } from '../../utils';
import { combineActionOptions } from '../../utils/actions/combine-action-options';
import { fireLinkClickedEvent } from '../../utils/analytics/click';
import { SmartLinkAnalyticsContext } from '../../utils/analytics/SmartLinkAnalyticsContext';
import { isFlexibleUiCard } from '../../utils/flexible';
import * as measure from '../../utils/performance';
import { BlockCard } from '../BlockCard';
import { EmbedCard, EmbedCardUpdated } from '../EmbedCard';
import FlexibleCard from '../FlexibleCard';
import { InlineCard } from '../InlineCard';
import { useFire3PWorkflowsClickEvent } from '../SmartLinkEvents/useSmartLinkEvents';
var thirdPartyARIPrefix = 'ari:third-party';
var EmbedCardComponent = componentWithFG('rovo_chat_embed_card_dwell_and_hover_metrics', EmbedCardUpdated, EmbedCard);
function Component(_ref) {
  var id = _ref.id,
    url = _ref.url,
    isSelected = _ref.isSelected,
    isHovered = _ref.isHovered,
    frameStyle = _ref.frameStyle,
    platform = _ref.platform,
    onClick = _ref.onClick,
    appearance = _ref.appearance,
    onResolve = _ref.onResolve,
    onError = _ref.onError,
    testId = _ref.testId,
    actionOptionsProp = _ref.actionOptions,
    inheritDimensions = _ref.inheritDimensions,
    embedIframeRef = _ref.embedIframeRef,
    embedIframeUrlType = _ref.embedIframeUrlType,
    inlinePreloaderStyle = _ref.inlinePreloaderStyle,
    ui = _ref.ui,
    children = _ref.children,
    showHoverPreview = _ref.showHoverPreview,
    hoverPreviewOptions = _ref.hoverPreviewOptions,
    removeTextHighlightingFromTitle = _ref.removeTextHighlightingFromTitle,
    resolvingPlaceholder = _ref.resolvingPlaceholder,
    truncateInline = _ref.truncateInline,
    CompetitorPrompt = _ref.CompetitorPrompt,
    hideIconLoadingSkeleton = _ref.hideIconLoadingSkeleton,
    disablePreviewPanel = _ref.disablePreviewPanel,
    placeholderData = _ref.placeholderData;
  var _useAnalyticsEventsNe = useAnalyticsEventsNext(),
    createAnalyticsEvent = _useAnalyticsEventsNe.createAnalyticsEvent;
  var _useAnalyticsEvents = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var isFlexibleUi = useMemo(function () {
    return isFlexibleUiCard(children, ui);
  }, [children, ui]);

  // Get state, actions for this card.
  var _useSmartLink = useSmartLink(id, url),
    state = _useSmartLink.state,
    actions = _useSmartLink.actions,
    config = _useSmartLink.config,
    renderers = _useSmartLink.renderers,
    error = _useSmartLink.error,
    isPreviewPanelAvailable = _useSmartLink.isPreviewPanelAvailable,
    openPreviewPanel = _useSmartLink.openPreviewPanel;
  var ari = getObjectAri(state.details);
  var name = getObjectName(state.details);
  var definitionId = getDefinitionId(state.details);
  var extensionKey = getExtensionKey(state.details);
  var resourceType = getResourceType(state.details);
  var services = getServices(state.details);
  var thirdPartyARI = getThirdPartyARI(state.details);
  var firstPartyIdentifier = getFirstPartyIdentifier();
  var actionOptions = combineActionOptions({
    actionOptions: actionOptionsProp,
    platform: platform
  });
  var fire3PClickEvent = fg('platform_smartlink_3pclick_analytics') ?
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useFire3PWorkflowsClickEvent(firstPartyIdentifier, thirdPartyARI) : undefined;

  // Setup UI handlers.
  var handleClickWrapper = useCallback(function (event) {
    var isModifierKeyPressed = isSpecialKey(event) || isSpecialClick(event);
    fireEvent('ui.smartLink.clicked', {
      id: id,
      display: isFlexibleUi ? CardDisplay.Flexible : appearance,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      isModifierKeyPressed: isModifierKeyPressed
    });
    if (fg('platform_smartlink_3pclick_analytics')) {
      if (thirdPartyARI && thirdPartyARI.startsWith(thirdPartyARIPrefix)) {
        var clickURL = getClickUrl(url, state.details);
        if (clickURL === url && fire3PClickEvent) {
          // For questions or concerns about this event,
          // please reach out to the 3P Workflows Team via Slack in #help-3p-connector-workflow
          fire3PClickEvent();
        }
      }
    }
    var isDisablePreviewPanel = disablePreviewPanel && editorExperiment('platform_editor_preview_panel_linking_exp', true, {
      exposure: true
    });

    // If preview panel is available and the user clicked on the link,
    // delegate the click to the preview panel handler
    if (!isModifierKeyPressed && ari && name && openPreviewPanel && isPreviewPanelAvailable !== null && isPreviewPanelAvailable !== void 0 && isPreviewPanelAvailable({
      ari: ari
    }) && !isDisablePreviewPanel) {
      var _extractSmartLinkEmbe;
      event.preventDefault();
      event.stopPropagation();
      openPreviewPanel({
        url: url,
        ari: ari,
        name: name,
        iconUrl: getObjectIconUrl(state.details),
        panelData: {
          embedUrl: expValEquals('platform_hover_card_preview_panel', 'cohort', 'test') ? (_extractSmartLinkEmbe = extractSmartLinkEmbed(state.details)) === null || _extractSmartLinkEmbe === void 0 ? void 0 : _extractSmartLinkEmbe.src : undefined
        }
      });
      fireLinkClickedEvent(createAnalyticsEvent)(event, {
        attributes: {
          clickOutcome: 'previewPanel'
        }
      });
      return;
    } else if (!onClick && !isFlexibleUi) {
      var clickUrl = getClickUrl(url, state.details);

      // Ctrl+left click on mac typically doesn't trigger onClick
      // The event could have potentially had `e.preventDefault()` called on it by now
      // event by smart card internally
      // If it has been called then only then can `isSpecialEvent` be true.
      var target = isSpecialEvent(event) ? '_blank' : '_self';
      window.open(clickUrl, target);
      fireLinkClickedEvent(createAnalyticsEvent)(event, {
        attributes: {
          clickOutcome: target === '_blank' ? 'clickThroughNewTabOrWindow' : 'clickThrough'
        }
      });
    } else {
      if (onClick) {
        onClick(event);
      }
      fireLinkClickedEvent(createAnalyticsEvent)(event);
    }
  }, [fireEvent, id, isFlexibleUi, appearance, definitionId, onClick, url, state.details, ari, name, fire3PClickEvent, isPreviewPanelAvailable, openPreviewPanel, createAnalyticsEvent, thirdPartyARI, disablePreviewPanel]);
  var handleAuthorize = useCallback(function () {
    return actions.authorize(appearance);
  }, [actions, appearance]);
  var handleRetry = useCallback(function () {
    actions.reload();
  }, [actions]);
  var handleInvoke = useCallback(function (opts) {
    return actions.invoke(opts, appearance);
  }, [actions, appearance]);

  // NB: for each status change in a Smart Link, a performance mark is created.
  // Measures are sent relative to the first mark, matching what a user sees.
  useEffect(function () {
    measure.mark(id, state.status);
    if (state.status !== 'pending' && state.status !== 'resolving') {
      var _state$error, _state$error2, _state$error3, _state$error4, _state$error5;
      measure.create(id, state.status);
      if (state.status === 'resolved') {
        var _measure$getMeasure$d, _measure$getMeasure;
        fireEvent('operational.smartLink.resolved', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          duration: (_measure$getMeasure$d = (_measure$getMeasure = measure.getMeasure(id, state.status)) === null || _measure$getMeasure === void 0 ? void 0 : _measure$getMeasure.duration) !== null && _measure$getMeasure$d !== void 0 ? _measure$getMeasure$d : null
        });
      } else if (fg('platform_navx_lp_invalid_url_error') ? ((_state$error = state.error) === null || _state$error === void 0 ? void 0 : _state$error.type) !== 'ResolveUnsupportedError' && ((_state$error2 = state.error) === null || _state$error2 === void 0 ? void 0 : _state$error2.type) !== 'UnsupportedError' && ((_state$error3 = state.error) === null || _state$error3 === void 0 ? void 0 : _state$error3.name) !== 'InvalidUrlError' : ((_state$error4 = state.error) === null || _state$error4 === void 0 ? void 0 : _state$error4.type) !== 'ResolveUnsupportedError' && ((_state$error5 = state.error) === null || _state$error5 === void 0 ? void 0 : _state$error5.type) !== 'UnsupportedError') {
        fireEvent('operational.smartLink.unresolved', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          reason: state.status,
          error: state.error === undefined ? null : {
            name: state.error.name,
            kind: state.error.kind,
            type: state.error.type
          }
        });
      }
    }
  }, [id, appearance, state.status, state.error, definitionId, extensionKey, resourceType, fireEvent]);

  // NB: once the smart-card has rendered into an end state, we capture
  // this as a successful render. These can be one of:
  // - the resolved state: when metadata is shown;
  // - the unresolved states: viz. forbidden, not_found, unauthorized, errored.
  useEffect(function () {
    if (isFinalState(state.status)) {
      succeedUfoExperience('smart-link-rendered', id || 'NULL', {
        extensionKey: extensionKey,
        display: isFlexibleUi ? 'flexible' : appearance
      });

      // UFO will disregard this if authentication experience has not yet been started
      succeedUfoExperience('smart-link-authenticated', id || 'NULL', {
        display: isFlexibleUi ? 'flexible' : appearance
      });
      fireEvent('ui.smartLink.renderSuccess', {
        display: isFlexibleUi ? 'flexible' : appearance
      });
    }
  }, [appearance, extensionKey, fireEvent, id, isFlexibleUi, state.status]);
  var onIframeDwell = useCallback(function (dwellTime, dwellPercentVisible) {
    fireEvent('ui.smartLinkIframe.dwelled', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      dwellPercentVisible: dwellPercentVisible,
      dwellTime: dwellTime
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  var onIframeFocus = useCallback(function () {
    fireEvent('ui.smartLinkIframe.focused', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  if (isFlexibleUi) {
    var cardState = state;
    if (error) {
      if ((error === null || error === void 0 ? void 0 : error.name) === 'APIError') {
        cardState = {
          status: 'errored'
        };
      } else {
        throw error;
      }
    }
    return /*#__PURE__*/React.createElement(FlexibleCard, {
      id: id,
      cardState: cardState,
      placeholderData: placeholderData,
      onAuthorize: services.length && handleAuthorize || undefined,
      onClick: handleClickWrapper,
      origin: "smartLinkCard",
      renderers: renderers,
      ui: ui,
      showHoverPreview: showHoverPreview,
      hoverPreviewOptions: hoverPreviewOptions,
      actionOptions: actionOptions,
      url: url,
      testId: testId,
      onResolve: onResolve,
      onError: onError
    }, children);
  }

  // We have to keep this last to prevent hook order from being violated
  if (error) {
    throw error;
  }
  switch (appearance) {
    case 'inline':
      return /*#__PURE__*/React.createElement(InlineCard, {
        id: id,
        url: url,
        renderers: renderers,
        cardState: state,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleFrameClick: handleClickWrapper,
        isSelected: isSelected,
        isHovered: isHovered,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        inlinePreloaderStyle: inlinePreloaderStyle,
        showHoverPreview: showHoverPreview,
        hoverPreviewOptions: hoverPreviewOptions,
        actionOptions: actionOptions,
        removeTextHighlightingFromTitle: removeTextHighlightingFromTitle,
        resolvingPlaceholder: resolvingPlaceholder,
        truncateInline: truncateInline,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
    case 'block':
      return /*#__PURE__*/React.createElement(BlockCard, {
        id: id,
        url: url,
        renderers: renderers,
        authFlow: config && config.authFlow,
        cardState: state,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleFrameClick: handleClickWrapper,
        isSelected: isSelected,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        actionOptions: actionOptions,
        CompetitorPrompt: CompetitorPrompt,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
    case 'embed':
      return /*#__PURE__*/React.createElement(EmbedCard, {
        id: id,
        url: url,
        renderers: renderers,
        cardState: state,
        iframeUrlType: embedIframeUrlType,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleErrorRetry: handleRetry,
        handleFrameClick: handleClickWrapper,
        handleInvoke: handleInvoke,
        isSelected: isSelected,
        frameStyle: frameStyle,
        platform: platform,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        inheritDimensions: inheritDimensions,
        actionOptions: actionOptions,
        ref: embedIframeRef,
        onIframeDwell: onIframeDwell,
        onIframeFocus: onIframeFocus,
        CompetitorPrompt: CompetitorPrompt,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
  }
}
function ComponentUpdated(_ref2) {
  var id = _ref2.id,
    url = _ref2.url,
    isSelected = _ref2.isSelected,
    isHovered = _ref2.isHovered,
    frameStyle = _ref2.frameStyle,
    platform = _ref2.platform,
    onClick = _ref2.onClick,
    appearance = _ref2.appearance,
    onResolve = _ref2.onResolve,
    onError = _ref2.onError,
    testId = _ref2.testId,
    actionOptionsProp = _ref2.actionOptions,
    inheritDimensions = _ref2.inheritDimensions,
    embedIframeRef = _ref2.embedIframeRef,
    embedIframeUrlType = _ref2.embedIframeUrlType,
    inlinePreloaderStyle = _ref2.inlinePreloaderStyle,
    ui = _ref2.ui,
    children = _ref2.children,
    showHoverPreview = _ref2.showHoverPreview,
    hoverPreviewOptions = _ref2.hoverPreviewOptions,
    removeTextHighlightingFromTitle = _ref2.removeTextHighlightingFromTitle,
    resolvingPlaceholder = _ref2.resolvingPlaceholder,
    truncateInline = _ref2.truncateInline,
    CompetitorPrompt = _ref2.CompetitorPrompt,
    hideIconLoadingSkeleton = _ref2.hideIconLoadingSkeleton,
    disablePreviewPanel = _ref2.disablePreviewPanel,
    placeholderData = _ref2.placeholderData;
  var _useAnalyticsEventsNe2 = useAnalyticsEventsNext(),
    createAnalyticsEvent = _useAnalyticsEventsNe2.createAnalyticsEvent;
  var _useAnalyticsEvents2 = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents2.fireEvent;
  var isFlexibleUi = useMemo(function () {
    return isFlexibleUiCard(children, ui);
  }, [children, ui]);

  // Get state, actions for this card.
  var _useSmartLink2 = useSmartLink(id, url),
    state = _useSmartLink2.state,
    actions = _useSmartLink2.actions,
    config = _useSmartLink2.config,
    renderers = _useSmartLink2.renderers,
    error = _useSmartLink2.error,
    isPreviewPanelAvailable = _useSmartLink2.isPreviewPanelAvailable,
    openPreviewPanel = _useSmartLink2.openPreviewPanel;
  var ari = getObjectAri(state.details);
  var name = getObjectName(state.details);
  var definitionId = getDefinitionId(state.details);
  var extensionKey = getExtensionKey(state.details);
  var resourceType = getResourceType(state.details);
  var services = getServices(state.details);
  var thirdPartyARI = getThirdPartyARI(state.details);
  var firstPartyIdentifier = getFirstPartyIdentifier();
  var actionOptions = combineActionOptions({
    actionOptions: actionOptionsProp,
    platform: platform
  });
  var fire3PClickEvent = fg('platform_smartlink_3pclick_analytics') ?
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useFire3PWorkflowsClickEvent(firstPartyIdentifier, thirdPartyARI) : undefined;

  // Setup UI handlers.
  var handleClickWrapper = useCallback(function (event) {
    var isModifierKeyPressed = isSpecialKey(event) || isSpecialClick(event);
    fireEvent('ui.smartLink.clicked', {
      id: id,
      display: isFlexibleUi ? CardDisplay.Flexible : appearance,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      isModifierKeyPressed: isModifierKeyPressed
    });
    if (fg('platform_smartlink_3pclick_analytics')) {
      if (thirdPartyARI && thirdPartyARI.startsWith(thirdPartyARIPrefix)) {
        var clickURL = getClickUrl(url, state.details);
        if (clickURL === url && fire3PClickEvent) {
          // For questions or concerns about this event,
          // please reach out to the 3P Workflows Team via Slack in #help-3p-connector-workflow
          fire3PClickEvent();
        }
      }
    }
    var isDisablePreviewPanel = disablePreviewPanel && editorExperiment('platform_editor_preview_panel_linking_exp', true, {
      exposure: true
    });

    // If preview panel is available and the user clicked on the link,
    // delegate the click to the preview panel handler
    if (!isModifierKeyPressed && ari && name && openPreviewPanel && isPreviewPanelAvailable !== null && isPreviewPanelAvailable !== void 0 && isPreviewPanelAvailable({
      ari: ari
    }) && !isDisablePreviewPanel) {
      var _extractSmartLinkEmbe2;
      event.preventDefault();
      event.stopPropagation();
      openPreviewPanel({
        url: url,
        ari: ari,
        name: name,
        iconUrl: getObjectIconUrl(state.details),
        panelData: {
          embedUrl: expValEquals('platform_hover_card_preview_panel', 'cohort', 'test') ? (_extractSmartLinkEmbe2 = extractSmartLinkEmbed(state.details)) === null || _extractSmartLinkEmbe2 === void 0 ? void 0 : _extractSmartLinkEmbe2.src : undefined
        }
      });
      fireLinkClickedEvent(createAnalyticsEvent)(event, {
        attributes: {
          clickOutcome: 'previewPanel'
        }
      });
      return;
    } else if (!onClick && !isFlexibleUi) {
      var clickUrl = getClickUrl(url, state.details);

      // Ctrl+left click on mac typically doesn't trigger onClick
      // The event could have potentially had `e.preventDefault()` called on it by now
      // event by smart card internally
      // If it has been called then only then can `isSpecialEvent` be true.
      var target = isSpecialEvent(event) ? '_blank' : '_self';
      window.open(clickUrl, target);
      fireLinkClickedEvent(createAnalyticsEvent)(event, {
        attributes: {
          clickOutcome: target === '_blank' ? 'clickThroughNewTabOrWindow' : 'clickThrough'
        }
      });
    } else {
      if (onClick) {
        onClick(event);
      }
      fireLinkClickedEvent(createAnalyticsEvent)(event);
    }
  }, [fireEvent, id, isFlexibleUi, appearance, definitionId, onClick, url, state.details, ari, name, fire3PClickEvent, isPreviewPanelAvailable, openPreviewPanel, createAnalyticsEvent, thirdPartyARI, disablePreviewPanel]);
  var handleAuthorize = useCallback(function () {
    return actions.authorize(appearance);
  }, [actions, appearance]);
  var handleRetry = useCallback(function () {
    actions.reload();
  }, [actions]);
  var handleInvoke = useCallback(function (opts) {
    return actions.invoke(opts, appearance);
  }, [actions, appearance]);

  // NB: for each status change in a Smart Link, a performance mark is created.
  // Measures are sent relative to the first mark, matching what a user sees.
  useEffect(function () {
    measure.mark(id, state.status);
    if (state.status !== 'pending' && state.status !== 'resolving') {
      var _state$error6, _state$error7, _state$error8, _state$error9, _state$error0;
      measure.create(id, state.status);
      if (state.status === 'resolved') {
        var _measure$getMeasure$d2, _measure$getMeasure2;
        fireEvent('operational.smartLink.resolved', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          duration: (_measure$getMeasure$d2 = (_measure$getMeasure2 = measure.getMeasure(id, state.status)) === null || _measure$getMeasure2 === void 0 ? void 0 : _measure$getMeasure2.duration) !== null && _measure$getMeasure$d2 !== void 0 ? _measure$getMeasure$d2 : null
        });
      } else if (fg('platform_navx_lp_invalid_url_error') ? ((_state$error6 = state.error) === null || _state$error6 === void 0 ? void 0 : _state$error6.type) !== 'ResolveUnsupportedError' && ((_state$error7 = state.error) === null || _state$error7 === void 0 ? void 0 : _state$error7.type) !== 'UnsupportedError' && ((_state$error8 = state.error) === null || _state$error8 === void 0 ? void 0 : _state$error8.name) !== 'InvalidUrlError' : ((_state$error9 = state.error) === null || _state$error9 === void 0 ? void 0 : _state$error9.type) !== 'ResolveUnsupportedError' && ((_state$error0 = state.error) === null || _state$error0 === void 0 ? void 0 : _state$error0.type) !== 'UnsupportedError') {
        fireEvent('operational.smartLink.unresolved', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          reason: state.status,
          error: state.error === undefined ? null : {
            name: state.error.name,
            kind: state.error.kind,
            type: state.error.type
          }
        });
      }
    }
  }, [id, appearance, state.status, state.error, definitionId, extensionKey, resourceType, fireEvent]);

  // NB: once the smart-card has rendered into an end state, we capture
  // this as a successful render. These can be one of:
  // - the resolved state: when metadata is shown;
  // - the unresolved states: viz. forbidden, not_found, unauthorized, errored.
  useEffect(function () {
    if (isFinalState(state.status)) {
      succeedUfoExperience('smart-link-rendered', id || 'NULL', {
        extensionKey: extensionKey,
        display: isFlexibleUi ? 'flexible' : appearance
      });

      // UFO will disregard this if authentication experience has not yet been started
      succeedUfoExperience('smart-link-authenticated', id || 'NULL', {
        display: isFlexibleUi ? 'flexible' : appearance
      });
      fireEvent('ui.smartLink.renderSuccess', {
        display: isFlexibleUi ? 'flexible' : appearance
      });
    }
  }, [appearance, extensionKey, fireEvent, id, isFlexibleUi, state.status]);
  var onIframeDwell = useCallback(function (dwellTime, dwellPercentVisible) {
    fireEvent('ui.smartLinkIframe.dwelled', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      dwellPercentVisible: dwellPercentVisible,
      dwellTime: dwellTime
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  var onIframeFocus = useCallback(function () {
    fireEvent('ui.smartLinkIframe.focused', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      interactionType: 'focus'
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  var onIframeMouseEnter = useCallback(function () {
    fireEvent('ui.smartLinkIframe.focused', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      interactionType: 'mouseenter'
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  var onIframeMouseLeave = useCallback(function () {
    fireEvent('ui.smartLinkIframe.focused', {
      id: id,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
      display: isFlexibleUi ? 'flexible' : appearance,
      interactionType: 'mouseleave'
    });
  }, [id, appearance, definitionId, isFlexibleUi, fireEvent]);
  if (isFlexibleUi) {
    var cardState = state;
    if (error) {
      if ((error === null || error === void 0 ? void 0 : error.name) === 'APIError') {
        cardState = {
          status: 'errored'
        };
      } else {
        throw error;
      }
    }
    return /*#__PURE__*/React.createElement(FlexibleCard, {
      id: id,
      cardState: cardState,
      placeholderData: placeholderData,
      onAuthorize: services.length && handleAuthorize || undefined,
      onClick: handleClickWrapper,
      origin: "smartLinkCard",
      renderers: renderers,
      ui: ui,
      showHoverPreview: showHoverPreview,
      hoverPreviewOptions: hoverPreviewOptions,
      actionOptions: actionOptions,
      url: url,
      testId: testId,
      onResolve: onResolve,
      onError: onError
    }, children);
  }

  // We have to keep this last to prevent hook order from being violated
  if (error) {
    throw error;
  }
  switch (appearance) {
    case 'inline':
      return /*#__PURE__*/React.createElement(InlineCard, {
        id: id,
        url: url,
        renderers: renderers,
        cardState: state,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleFrameClick: handleClickWrapper,
        isSelected: isSelected,
        isHovered: isHovered,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        inlinePreloaderStyle: inlinePreloaderStyle,
        showHoverPreview: showHoverPreview,
        hoverPreviewOptions: hoverPreviewOptions,
        actionOptions: actionOptions,
        removeTextHighlightingFromTitle: removeTextHighlightingFromTitle,
        resolvingPlaceholder: resolvingPlaceholder,
        truncateInline: truncateInline,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
    case 'block':
      return /*#__PURE__*/React.createElement(BlockCard, {
        id: id,
        url: url,
        renderers: renderers,
        authFlow: config && config.authFlow,
        cardState: state,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleFrameClick: handleClickWrapper,
        isSelected: isSelected,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        actionOptions: actionOptions,
        CompetitorPrompt: CompetitorPrompt,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
    case 'embed':
      return /*#__PURE__*/React.createElement(EmbedCardComponent, {
        id: id,
        url: url,
        renderers: renderers,
        cardState: state,
        iframeUrlType: embedIframeUrlType,
        handleAuthorize: services.length && handleAuthorize || undefined,
        handleErrorRetry: handleRetry,
        handleFrameClick: handleClickWrapper,
        handleInvoke: handleInvoke,
        isSelected: isSelected,
        frameStyle: frameStyle,
        platform: platform,
        onResolve: onResolve,
        onError: onError,
        testId: testId,
        inheritDimensions: inheritDimensions,
        actionOptions: actionOptions,
        ref: embedIframeRef,
        onIframeDwell: onIframeDwell,
        onIframeFocus: onIframeFocus,
        onIframeMouseEnter: onIframeMouseEnter,
        onIframeMouseLeave: onIframeMouseLeave,
        CompetitorPrompt: CompetitorPrompt,
        hideIconLoadingSkeleton: hideIconLoadingSkeleton
      });
  }
}
var CardWithUrlContentComponent = componentWithFG('rovo_chat_embed_card_dwell_and_hover_metrics', ComponentUpdated, Component);
export var CardWithUrlContent = function CardWithUrlContent(props) {
  var display = isFlexibleUiCard(props.children, props === null || props === void 0 ? void 0 : props.ui) ? CardDisplay.Flexible : props.appearance;
  return /*#__PURE__*/React.createElement(SmartLinkModalProvider, null, /*#__PURE__*/React.createElement(SmartLinkAnalyticsContext, {
    url: props.url,
    id: props.id,
    display: display
  }, /*#__PURE__*/React.createElement(CardWithUrlContentComponent, props)));
};