import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
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; }
/**
 * @jsxRuntime classic
 * @jsx jsx
 */
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';

// eslint-disable-next-line @atlaskit/ui-styling-standard/use-compiled, @typescript-eslint/consistent-type-imports -- Ignored via go/DSP-18766; jsx required at runtime for @jsxRuntime classic
import { jsx } from '@emotion/react';
import ReactDOM from 'react-dom';
import { createIntl, injectIntl } from 'react-intl';
import { useAnalyticsEvents } from '@atlaskit/analytics-next/useAnalyticsEvents';
import { fireFailedMediaInlineEvent, fireSucceededMediaInlineEvent, MediaCardError } from '@atlaskit/media-card';
import { FileFetcherError } from '@atlaskit/media-client';
import { MediaClientContext } from '@atlaskit/media-client-react';
import { MediaViewer } from '@atlaskit/media-viewer';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { editorExperiment } from '@atlaskit/tmp-editor-statsig/experiments';
import { messages } from '../messages/media-inline-card';
import { referenceHeights } from './constants';
import { InlineImageCard } from './inline-image-card';
import { InlineImageWrapper } from './inline-image-wrapper';
import { InlineImageCardErrorView } from './views/error-view';
import { InlineImageCardLoadingView } from './views/loading-view';
export var MediaInlineImageCardInternal = function MediaInlineImageCardInternal(_ref) {
  var mediaClient = _ref.mediaClient,
    identifier = _ref.identifier,
    isSelected = _ref.isSelected,
    intl = _ref.intl,
    alt = _ref.alt,
    isLazy = _ref.isLazy,
    width = _ref.width,
    height = _ref.height,
    border = _ref.border,
    ssr = _ref.ssr,
    serializeDataAttrs = _ref.serializeDataAttrs,
    shouldOpenMediaViewer = _ref.shouldOpenMediaViewer,
    isViewOnly = _ref.isViewOnly;
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    fileState = _useState2[0],
    setFileState = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    subscribeError = _useState4[0],
    setSubscribeError = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    isFailedEventSent = _useState6[0],
    setIsFailedEventSent = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    isSucceededEventSent = _useState8[0],
    setIsSucceededEventSent = _useState8[1];
  var _useState9 = useState(false),
    _useState0 = _slicedToArray(_useState9, 2),
    isMediaViewerVisible = _useState0[0],
    setMediaViewerVisible = _useState0[1];
  var _ref2 = intl || createIntl({
      locale: 'en'
    }),
    formatMessage = _ref2.formatMessage;
  var _useAnalyticsEvents = useAnalyticsEvents(),
    createAnalyticsEvent = _useAnalyticsEvents.createAnalyticsEvent;
  var fireFailedOperationalEvent = function fireFailedOperationalEvent() {
    var error = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new MediaCardError('missing-error-data');
    var failReason = arguments.length > 1 ? arguments[1] : undefined;
    if (!isFailedEventSent && fileState) {
      setIsFailedEventSent(true);
      fireFailedMediaInlineEvent(fileState, error, failReason, createAnalyticsEvent);
    }
  };
  var fireSucceededOperationalEvent = function fireSucceededOperationalEvent() {
    if (!isSucceededEventSent && fileState) {
      setIsSucceededEventSent(true);
      fireSucceededMediaInlineEvent(fileState, createAnalyticsEvent);
    }
  };
  useEffect(function () {
    if (mediaClient) {
      var subscription = mediaClient.file.getFileState(identifier.id, {
        collectionName: identifier.collectionName
      }).subscribe({
        next: function next(fileState) {
          setFileState(fileState);
          setSubscribeError(undefined);
        },
        error: function error(e) {
          setSubscribeError(e);
        }
      });
      return function () {
        subscription.unsubscribe();
      };
    }
  }, [identifier, mediaClient]);
  var memoizedRenderError = useCallback(function () {
    return jsx(InlineImageCardErrorView, {
      message: formatMessage(messages.unableToLoadContent)
    });
  }, [formatMessage]);
  var content = function content(dimensions) {
    if (!mediaClient) {
      return jsx(InlineImageCardLoadingView, null);
    }
    if (!ssr) {
      if (subscribeError) {
        var isUploading = (fileState === null || fileState === void 0 ? void 0 : fileState.status) === 'uploading';
        var errorMessage = isUploading ? messages.failedToUpload : messages.unableToLoadContent;
        var errorReason = (fileState === null || fileState === void 0 ? void 0 : fileState.status) === 'uploading' ? 'upload' : 'metadata-fetch';
        fireFailedOperationalEvent(new MediaCardError(errorReason, subscribeError));
        return jsx(InlineImageCardErrorView, {
          message: formatMessage(errorMessage)
        });
      }
      if (!fileState || (fileState === null || fileState === void 0 ? void 0 : fileState.status) === 'uploading') {
        return jsx(InlineImageCardLoadingView, null);
      }
      if (fileState.status === 'error') {
        fireFailedOperationalEvent(new MediaCardError('error-file-state', new Error(fileState.message)));
        return jsx(InlineImageCardErrorView, {
          message: formatMessage(messages.unableToLoadContent)
        });
      } else if (fileState.status === 'failed-processing') {
        fireFailedOperationalEvent(undefined, 'failed-processing');
        return jsx(InlineImageCardErrorView, {
          message: formatMessage(messages.unableToLoadContent)
        });
      } else if (!fileState.name) {
        fireFailedOperationalEvent(new MediaCardError('metadata-fetch', new FileFetcherError('emptyFileName', {
          id: fileState.id
        })));
        return jsx(InlineImageCardErrorView, {
          message: formatMessage(messages.unableToLoadContent)
        });
      }
      if (fileState.status === 'processed') {
        fireSucceededOperationalEvent();
      }
    }
    return jsx(MediaClientContext.Provider, {
      value: mediaClient
    }, jsx(InlineImageCard, {
      dimensions: dimensions,
      identifier: identifier,
      renderError: expValEquals('platform_editor_perf_lint_cleanup', 'isEnabled', true) ? memoizedRenderError :
      // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- intentional fallback for experiment off path
      function () {
        return jsx(InlineImageCardErrorView, {
          message: formatMessage(messages.unableToLoadContent)
        });
      },
      alt: alt,
      ssr: ssr === null || ssr === void 0 ? void 0 : ssr.mode,
      isLazy: isLazy,
      crop: true,
      stretch: false
    }));
  };
  var aspectRatio = useMemo(function () {
    return width && height ? width / height : undefined;
  }, [width, height]);

  /**
   * scaledDimensions is used to define the correct media size fetched from media service
   * inline images will only ever be rendered at a maximum height of H1 and so scaled dimensions
   * will only ever return a width and height where the height has a maximum height of H1
   */
  var scaledDimension = useMemo(function () {
    if (!width || !height || !aspectRatio) {
      return {
        width: width,
        height: height
      };
    }
    return {
      width: Math.round(aspectRatio * referenceHeights['h1']),
      height: referenceHeights['h1']
    };
  }, [width, height, aspectRatio]);
  var htmlAttributes = useMemo(function () {
    if (serializeDataAttrs) {
      var resolvedAttrs = fileState && fileState.status !== 'error' ? {
        'data-file-size': fileState.size,
        'data-file-mime-type': fileState.mimeType,
        'data-file-name': fileState.name
      } : {};
      return _objectSpread({
        'data-type': 'image',
        'data-node-type': 'mediaInline',
        'data-id': identifier.id,
        'data-collection': identifier.collectionName,
        'data-width': width,
        'data-height': height,
        'data-alt': alt
      }, resolvedAttrs);
    }
    return {};
  }, [alt, fileState, height, identifier, width, serializeDataAttrs]);
  var onMediaInlineImageClick = useCallback(function (e) {
    if (shouldOpenMediaViewer) {
      setMediaViewerVisible(true);
    }

    // In edit mode (node content wrapper has contenteditable set to true), link redirection is disabled by default
    // We need to call "stopPropagation" here in order to prevent in editor view mode, the browser from navigating to
    // another URL if the media node is wrapped in a link mark.
    if (isViewOnly && editorExperiment('platform_editor_controls', 'variant1')) {
      e.preventDefault();
    }
  }, [shouldOpenMediaViewer, isViewOnly]);
  var onMediaInlinePreviewClose = useCallback(function () {
    setMediaViewerVisible(false);
  }, []);
  var memoizedMediaViewerItems = useMemo(function () {
    return [identifier];
  }, [identifier]);
  var mediaViewer = useMemo(function () {
    if (isMediaViewerVisible && mediaClient !== null && mediaClient !== void 0 && mediaClient.mediaClientConfig) {
      return /*#__PURE__*/ReactDOM.createPortal(jsx(MediaViewer, {
        collectionName: identifier.collectionName || '',
        items: expValEquals('platform_editor_perf_lint_cleanup', 'isEnabled', true) ? memoizedMediaViewerItems :
        // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- intentional fallback for experiment off path
        [identifier],
        mediaClientConfig: mediaClient === null || mediaClient === void 0 ? void 0 : mediaClient.mediaClientConfig,
        selectedItem: identifier,
        onClose: onMediaInlinePreviewClose
      }), document.body);
    }
    return null;
  }, [identifier, isMediaViewerVisible, mediaClient === null || mediaClient === void 0 ? void 0 : mediaClient.mediaClientConfig, onMediaInlinePreviewClose, memoizedMediaViewerItems]);
  return jsx(Fragment, null, jsx(InlineImageWrapper, {
    isSelected: isSelected,
    aspectRatio: aspectRatio,
    borderColor: border === null || border === void 0 ? void 0 : border.borderColor,
    borderSize: border === null || border === void 0 ? void 0 : border.borderSize,
    htmlAttrs: htmlAttributes,
    onClick: onMediaInlineImageClick
  }, content(scaledDimension)), mediaViewer);
};

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export var MediaInlineImageCard = injectIntl(MediaInlineImageCardInternal, {
  enforceContext: false
});