/* UnauthorisedView.tsx generated by @compiled/babel-plugin v0.38.1 */
import _extends from "@babel/runtime/helpers/extends";
import "./UnauthorisedView.compiled.css";
import * as React from 'react';
import { ax, ix } from "@compiled/react/runtime";
import { useCallback, useMemo } from 'react';
import { FormattedMessage } from 'react-intl-next';
import { extractSmartLinkProvider } from '@atlaskit/link-extractors';
import { fg } from '@atlaskit/platform-feature-flags';
import { Box } from '@atlaskit/primitives/compiled';
import { useAnalyticsEvents } from '../../../common/analytics/generated/use-analytics-events';
import { ElementName, SmartLinkDirection, SmartLinkSize, SmartLinkWidth } from '../../../constants';
import { messages } from '../../../messages';
import { useFlexibleCardContext } from '../../../state/flexible-ui-context';
import { getExtensionKey, hasAuthScopeOverrides } from '../../../state/helpers';
import { isNewBlockcardUnauthorizedRefreshExperimentEnabled } from '../../../utils/experiments';
import UnauthorisedViewContent from '../../common/UnauthorisedViewContent';
import FlexibleCard from '../../FlexibleCard';
import ActionGroup from '../../FlexibleCard/components/blocks/action-group';
import Block from '../../FlexibleCard/components/blocks/block';
import ElementGroup from '../../FlexibleCard/components/blocks/element-group';
import { renderElementItems } from '../../FlexibleCard/components/blocks/utils';
import { LinkIcon, Title } from '../../FlexibleCard/components/elements';
import { AuthorizeAction } from '../actions/AuthorizeAction';
import unauthIllustrationFigma from './assets/figma@2x.png';
import unauthIllustrationGeneral from './assets/general@2x.png';
import unauthIllustrationGdrive from './assets/google-drive@2x.png';
import unauthIllustrationOnedrive from './assets/onedrive@2x.png';
import unauthIllustrationSlack from './assets/slack@2x.png';
import UnresolvedView from './unresolved-view';
import { FlexibleCardUiOptions, titleBlockOptions } from './utils';
import { withFlexibleUIBlockCardStyle } from './utils/withFlexibleUIBlockCardStyle';
const contentStyles = null;
const newContentStyles = null;
const contentAdditionalStyles = null;
const newTitleBlockStyles = null;
const intermediumGapStyles = null;
const titleBlockStyles = null;
const previewBlockStyle = null;
const previewBlockStyleWithOverlap = null;
const linkIconStyles = null;
const containerStyles = null;
const previewBlockImageStyle = null;
const styles = {
  titleBoxCard: "_1e0c1txw _2lx2vrvc _4cvr1h6o _1bsb1osq"
};
const getBetterTitle = url => {
  // List of regexps to extract human-readable titles from URLs
  // Each regex should have a capture group for the title at index 1
  const titleExtractors = [
  // Dropbox: https://www.dropbox.com/scl/fi/scebraopvx4bni0sechq9/Atlas23_D1_A_0014.jpg?rlkey=... -> Atlas23_D1_A_0014.jpg
  /^https:\/\/www\.dropbox\.com\/scl\/fi\/[^\/]+\/([^\/\?]+)/,
  // Dropbox: https://www.dropbox.com/home/Teamwork%20Ecosystem?preview=xsociety00.dat -> Teamwork Ecosystem
  /^https:\/\/www\.dropbox\.com\/home\/([^\/\?]+)/,
  // Dropbox: https://www.dropbox.com/home?preview=Insomnia-All_2019-03-14.json -> Insomnia-All_2019-03-14.json
  /^https:\/\/www\.dropbox\.com\/home\?(?:.*?&)?preview=([^&#]+)/,
  // Dropbox: https://www.dropbox.com/preview/AI%20Contest -> AI Contest
  /^https:\/\/www\.dropbox\.com\/preview\/([^&?]+)/,
  // Dropbox: https://www.dropbox.com/s/votiehk00g4opif/xsociety00.dat?dl=0 -> xsociety00.dat
  /^https:\/\/www\.dropbox\.com\/(?:s|sh|sc|t)\/[^\/]+\/([^\/\?]+)/,
  // Figma: https://www.figma.com/slides/vW47To0dYPnT7jlrJdUd7h/Universal-Create-in-TwC?node-id=... -> Universal-Create-in-TwC
  // Also supports: /file/, /design/, /board/, /proto/
  /^https:\/\/(?:[\w.-]+\.)?figma\.com\/(?:design|board|file|proto|slides)\/[0-9a-zA-Z]{22,128}\/([^\/\?]+)/,
  // OneDrive: https://1drv.ms/w/s!ABC123DEF456/Project_Plan.docx?e=abcdEF -> Project_Plan.docx
  /^https:\/\/1drv\.ms\/[a-z]+\/s![^\/]+\/([^\/\?]+)/,
  // Statsig: https://console.statsig.com/LqivKg6ADZZaGczRfBKfX/experiments/platform_inline_smartcard_connect_button_exp/results -> platform_inline_smartcard_connect_button_exp
  /^https:\/\/console\.statsig\.com\/[^\/]+\/experiments\/([^\/\?]+)\//,
  // Miro: https://miro.com/app/board/uXjVOPnT123=/my-board-name/ -> my-board-name
  /^https:\/\/miro\.com\/app\/board\/[^\/]+\/([^\/\?]+)\/?/];

  // Try each extractor pattern
  for (const pattern of titleExtractors) {
    const match = url.match(pattern);
    if (match) {
      const extracted = decodeURIComponent(match[1]);
      if (extracted) {
        return extracted;
      }
    }
  }
  try {
    const {
      pathname,
      search
    } = new URL(url);
    if (pathname.length > 1) {
      return pathname.substring(1);
    } else {
      return search;
    }
  } catch {
    return url;
  }
};
const NewUnauthorisedBlock = ({
  actions,
  children,
  url,
  CompetitorPrompt,
  testId,
  cardState
}) => {
  var _useFlexibleCardConte, _getExtensionKey, _data$preview;
  const {
    ui,
    data
  } = (_useFlexibleCardConte = useFlexibleCardContext()) !== null && _useFlexibleCardConte !== void 0 ? _useFlexibleCardConte : {
    ui: undefined,
    data: undefined
  };
  const hasActions = actions && actions.length > 0;
  const actionGroup = hasActions ? /*#__PURE__*/React.createElement(ActionGroup, {
    size: SmartLinkSize.Large,
    items: actions
  }) : null;
  const competitorPrompt = CompetitorPrompt && data !== null && data !== void 0 && data.url && fg('prompt_whiteboard_competitor_link_gate') ? /*#__PURE__*/React.createElement(CompetitorPrompt, {
    sourceUrl: data === null || data === void 0 ? void 0 : data.url,
    linkType: 'card'
  }) : null;
  const title = /*#__PURE__*/React.createElement(Title, {
    hideTooltip: false,
    maxLines: 1,
    theme: ui === null || ui === void 0 ? void 0 : ui.theme,
    text: getBetterTitle(url),
    className: ax(["_k48p1pd9 _syaz13af"])
  });
  const {
    position
  } = titleBlockOptions;
  const extensionKey = (_getExtensionKey = getExtensionKey(cardState === null || cardState === void 0 ? void 0 : cardState.details)) !== null && _getExtensionKey !== void 0 ? _getExtensionKey : '';
  let overrideUrl = data === null || data === void 0 ? void 0 : (_data$preview = data.preview) === null || _data$preview === void 0 ? void 0 : _data$preview.url;
  let isHardcodedImage = !overrideUrl;
  if (isHardcodedImage) {
    switch (extensionKey) {
      case 'figma-object-provider':
        overrideUrl = unauthIllustrationFigma;
        break;
      case 'google-object-provider':
        overrideUrl = unauthIllustrationGdrive;
        break;
      case 'onedrive-object-provider':
        overrideUrl = unauthIllustrationOnedrive;
        break;
      case 'slack-object-provider':
        overrideUrl = unauthIllustrationSlack;
        break;
      default:
        overrideUrl = unauthIllustrationGeneral;
        break;
    }
  }
  return /*#__PURE__*/React.createElement(Block, _extends({}, titleBlockOptions, {
    testId: `${testId}-errored-view`,
    className: ax(["_7cca15wb _1f3816vg"])
  }), /*#__PURE__*/React.createElement(ElementGroup, {
    direction: SmartLinkDirection.Vertical,
    width: SmartLinkWidth.Flexible,
    size: SmartLinkSize.Medium,
    className: ax(["_zulputpp"])
  }, /*#__PURE__*/React.createElement(Block, null, /*#__PURE__*/React.createElement(LinkIcon, {
    position: position,
    size: SmartLinkSize.Medium,
    isTiledIcon: true,
    className: ax(["_vsqgglyw"])
  }), /*#__PURE__*/React.createElement(ElementGroup, {
    direction: SmartLinkDirection.Vertical,
    width: SmartLinkWidth.Flexible,
    size: SmartLinkSize.Large,
    className: ax(["_zulpidpf"])
  }, competitorPrompt ? /*#__PURE__*/React.createElement(Box, {
    xcss: styles.titleBoxCard
  }, title, competitorPrompt) : title, /*#__PURE__*/React.createElement(ElementGroup, {
    size: SmartLinkSize.Medium,
    direction: SmartLinkDirection.Horizontal
  }, renderElementItems([{
    name: ElementName.HostName
  }])))), children, actionGroup), hasActions ? /*#__PURE__*/React.createElement("div", {
    className: ax(["_1reo15vq _18m915vq _1bsb1o87 _1wpz1fhb _1dptglyw", isHardcodedImage && "_1bsbo60d"])
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      backgroundImage: `url(${overrideUrl})`
    },
    className: ax(["_kqswstnw _154iidpf _1xi2idpf _94n5idpf _4t3i1osq _1bsb1o87 _1lrw1f51 _ouxl1ssb _12vemgnk"])
  })) : null);
};

/**
 * This view represents a Block card that has an 'Unauthorized' status .
 * It should have a "Connect" button that will allow a user to connect their account and view the block card.
 *
 * @see SmartLinkStatus
 * @see FlexibleCardProps
 */
const UnauthorisedView = ({
  testId = 'smart-block-unauthorized-view',
  ...props
}) => {
  var _extractSmartLinkProv;
  const {
    cardState,
    onAuthorize
  } = props;
  const providerName = (_extractSmartLinkProv = extractSmartLinkProvider(cardState.details)) === null || _extractSmartLinkProv === void 0 ? void 0 : _extractSmartLinkProv.text;
  const isProductIntegrationSupported = hasAuthScopeOverrides(cardState.details);
  const {
    fireEvent
  } = useAnalyticsEvents();
  const handleAuthorize = useCallback(() => {
    if (onAuthorize) {
      fireEvent('track.applicationAccount.authStarted', {});
      onAuthorize();
    }
  }, [onAuthorize, fireEvent]);
  const content = useMemo(() => onAuthorize ? /*#__PURE__*/React.createElement(UnauthorisedViewContent, {
    providerName: providerName,
    isProductIntegrationSupported: isProductIntegrationSupported,
    testId: testId
  }) : /*#__PURE__*/React.createElement(FormattedMessage, _extends({}, messages[providerName ? 'unauthorised_account_description' : 'unauthorised_account_description_no_provider'], {
    values: {
      context: providerName
    }
  })), [isProductIntegrationSupported, onAuthorize, providerName, testId]);
  const actions = useMemo(() => onAuthorize ? [AuthorizeAction(handleAuthorize, providerName)] : [], [handleAuthorize, onAuthorize, providerName]);
  if (isNewBlockcardUnauthorizedRefreshExperimentEnabled(true)) {
    return /*#__PURE__*/React.createElement(FlexibleCard, _extends({
      appearance: "block",
      onAuthorize: onAuthorize,
      origin: "smartLinkCard",
      testId: testId,
      ui: FlexibleCardUiOptions
    }, props), /*#__PURE__*/React.createElement(NewUnauthorisedBlock, _extends({}, props, {
      actions: actions,
      testId: testId
    }), /*#__PURE__*/React.createElement("div", {
      "data-testid": `${testId}-content`,
      className: ax(["_11c82smr _syazi7uo _19pku2gc", actions.length > 0 && "_1reo15vq _18m915vq _otyrpxbi _p12f1osq _o5721q9c _1bto1l2s"])
    }, content)));
  } else {
    return /*#__PURE__*/React.createElement(UnresolvedView, _extends({}, props, {
      actions: actions,
      testId: testId
    }), /*#__PURE__*/React.createElement("div", {
      "data-testid": `${testId}-content`,
      className: ax(["_11c8dcr7 _syazi7uo _19pku2gc"])
    }, content));
  }
};
export default withFlexibleUIBlockCardStyle(UnauthorisedView);