/* UnauthorisedView.tsx generated by @compiled/babel-plugin v0.40.0 */
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';
import { di } from 'react-magnetic-di';
import { AnalyticsContext } from '@atlaskit/analytics-next';
import { extractSmartLinkProvider } from '@atlaskit/link-extractors';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { componentWithFG } from '@atlaskit/platform-feature-flags-react';
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 { hasAuthScopeOverrides } from '../../../state/helpers';
import useSocialProofExperiment, { getSocialProofExperimentMeta } from '../../../state/hooks/use-social-proof-experiment';
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 unauthIllustrationGeneral from './assets/general@2x.png';
import SocialProofMessage from './SocialProofMessage';
import { FlexibleCardUiOptions, titleBlockOptions } from './utils';
import { withFlexibleUIBlockCardStyle } from './utils/withFlexibleUIBlockCardStyle';
const contentStyles = 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![^\/]+\/([^\/\?]+)/,
  // 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);
    }
    if (search) {
      return search;
    }
    // Fall back to the full URL when there is no useful path/search to display,
    // so the title (and the underlying link) always has accessible text.
    return url;
  } catch {
    return url;
  }
};
const UnauthorisedBlock = ({
  actions,
  children,
  url,
  CompetitorPrompt,
  testId
}) => {
  var _useFlexibleCardConte, _data$preview$url, _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 ? /*#__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;
  let overrideUrl = (_data$preview$url = data === null || data === void 0 ? void 0 : (_data$preview = data.preview) === null || _data$preview === void 0 ? void 0 : _data$preview.url) !== null && _data$preview$url !== void 0 ? _data$preview$url : unauthIllustrationGeneral;
  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", "_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 UnauthorisedViewFrame = ({
  content,
  providerName,
  testId,
  ...props
}) => {
  const {
    onAuthorize
  } = props;
  const {
    fireEvent
  } = useAnalyticsEvents();
  const handleAuthorize = useCallback(() => {
    if (onAuthorize) {
      fireEvent('track.applicationAccount.authStarted', {});
      onAuthorize();
    }
  }, [onAuthorize, fireEvent]);
  const actions = useMemo(() => onAuthorize ? [AuthorizeAction(handleAuthorize, providerName)] : [], [handleAuthorize, onAuthorize, providerName]);
  return /*#__PURE__*/React.createElement(FlexibleCard, _extends({
    appearance: "block",
    onAuthorize: onAuthorize,
    origin: "smartLinkCard",
    testId: testId,
    ui: FlexibleCardUiOptions
  }, props), /*#__PURE__*/React.createElement(UnauthorisedBlock, {
    actions: actions,
    cardState: props.cardState,
    CompetitorPrompt: props.CompetitorPrompt,
    testId: testId,
    url: props.url
  }, /*#__PURE__*/React.createElement("div", {
    "data-testid": `${testId}-content`,
    className: ax(["_11c8fhey _syazi7uo _19pku2gc", actions.length > 0 && "_1reo15vq _18m915vq _otyrpxbi _p12f1osq _o5721q9c _1bto1l2s"])
  }, content)));
};
const UnauthorisedViewBase = ({
  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 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]);
  return /*#__PURE__*/React.createElement(UnauthorisedViewFrame, _extends({}, props, {
    content: content,
    providerName: providerName,
    testId: testId
  }));
};

/**
 * Experiment wrapper: fires social proof exposure and renders social proof UI when FG is on.
 * TODO: remove when social-proof-3p-unauth-block-fg is cleaned up
 */
const UnauthorisedViewWithExperiment = ({
  testId = 'smart-block-unauthorized-view',
  ...props
}) => {
  var _props$cardState, _props$cardState$deta, _props$cardState$deta2, _extractSmartLinkProv2;
  const extensionKey = (_props$cardState = props.cardState) === null || _props$cardState === void 0 ? void 0 : (_props$cardState$deta = _props$cardState.details) === null || _props$cardState$deta === void 0 ? void 0 : (_props$cardState$deta2 = _props$cardState$deta.meta) === null || _props$cardState$deta2 === void 0 ? void 0 : _props$cardState$deta2.key;
  const providerName = (_extractSmartLinkProv2 = extractSmartLinkProvider(props.cardState.details)) === null || _extractSmartLinkProv2 === void 0 ? void 0 : _extractSmartLinkProv2.text;
  const {
    connections
  } = useSmartLinkContext();
  const {
    isTreatment,
    tier,
    connectedPct
  } = useSocialProofExperiment(providerName ? extensionKey : undefined, connections.client.baseUrlOverride);
  const socialProofExperimentMeta = getSocialProofExperimentMeta({
    extensionKey,
    baseUriWithNoTrailingSlash: connections.client.baseUrlOverride
  });
  const analyticsContextData = {
    attributes: {
      experiment: 'social_proof_3p_unauth_block_exp',
      cohort: isTreatment ? 'treatment' : 'control',
      tier,
      experimentMeta: socialProofExperimentMeta
    }
  };
  if (!isTreatment || !providerName) {
    const fallbackView = /*#__PURE__*/React.createElement(UnauthorisedViewBase, _extends({}, props, {
      testId: testId
    }));
    return connectedPct !== undefined ? /*#__PURE__*/React.createElement(AnalyticsContext, {
      data: analyticsContextData
    }, fallbackView) : fallbackView;
  }
  return /*#__PURE__*/React.createElement(AnalyticsContext, {
    data: analyticsContextData
  }, /*#__PURE__*/React.createElement(UnauthorisedViewFrame, _extends({}, props, {
    content: /*#__PURE__*/React.createElement(SocialProofMessage, {
      tier: tier,
      connectedPct: connectedPct,
      providerName: providerName
    }),
    providerName: providerName,
    testId: testId
  })));
};
const UnauthorisedViewWithoutExperiment = props => {
  return /*#__PURE__*/React.createElement(UnauthorisedViewBase, props);
};
const UnauthorisedView = componentWithFG('social-proof-3p-unauth-block-fg', UnauthorisedViewWithExperiment, UnauthorisedViewWithoutExperiment);
const _default_1 = withFlexibleUIBlockCardStyle(UnauthorisedView);
export default _default_1;