import _objectDestructuringEmpty from "@babel/runtime/helpers/objectDestructuringEmpty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
var _excluded = ["url"];
/* eslint-disable @atlaskit/design-system/prefer-primitives */
/**
 * @jsxRuntime classic
 * @jsx jsx
 */

import React, { Fragment, 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 { css, jsx } from '@emotion/react';
import classnames from 'classnames';
import EditorFileIcon from '@atlaskit/icon/core/file';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { useSharedPluginStateWithSelector } from '../../hooks';
import { removeMarginsAndBorder, sharedMultiBodiedExtensionStyles } from '../../ui/MultiBodiedExtension';
import { calculateBreakoutStyles, getExtensionLozengeData } from '../../utils';
import ExtensionLozenge from '../Extension/Lozenge';
import { shouldExtensionBreakout } from '../utils/should-extension-breakout';
import { useMultiBodiedExtensionActions } from './action-api';
import { mbeExtensionWrapperCSSStyles, overlayStyles } from './styles';
var getContainerCssExtendedStyles = function getContainerCssExtendedStyles(activeChildIndex, showMacroInteractionDesignUpdates) {
  return (
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
    css(sharedMultiBodiedExtensionStyles.mbeExtensionContainer, _defineProperty({}, ".multiBodiedExtension-content-dom-wrapper > [data-extension-frame='true']:nth-of-type(".concat(activeChildIndex + 1
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
    , ")"), css(
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
    sharedMultiBodiedExtensionStyles.extensionFrameContent,
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/ui-styling-standard/no-imported-style-values -- Ignored via go/DSP-18766
    showMacroInteractionDesignUpdates && removeMarginsAndBorder)))
  );
};
var imageStyles = css({
  maxHeight: '24px',
  maxWidth: '24px'
});
var hoverStyles = css({
  '&:hover': {
    boxShadow: "0 0 0 1px ".concat("var(--ds-border-input, #8C8F97)")
  }
});
var MultiBodiedExtensionFrames = function MultiBodiedExtensionFrames(_ref) {
  var articleRef = _ref.articleRef;
  return jsx("article", {
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    className: "multiBodiedExtension--frames",
    "data-testid": "multiBodiedExtension--frames",
    ref: articleRef
  });
};

// Similar to the one in platform/packages/editor/editor-common/src/extensibility/Extension/Lozenge.tsx
var getWrapperTitleContent = function getWrapperTitleContent(imageData, title, showMacroInteractionDesignUpdates) {
  if (showMacroInteractionDesignUpdates) {
    return null;
  }
  if (imageData) {
    var url = imageData.url,
      rest = _objectWithoutProperties(imageData, _excluded);
    return (
      // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
      jsx("div", {
        className: "extension-title"
      }, jsx("img", _extends({
        css: imageStyles,
        src: url
        // Ignored via go/ees005
        // eslint-disable-next-line react/jsx-props-no-spreading
      }, rest, {
        alt: title
      })), title)
    );
  }
  return jsx("div", {
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    className: "extension-title",
    "data-testid": 'multiBodiedExtension-default-lozenge'
  }, jsx(EditorFileIcon, {
    label: title
  }), title);
};
var MultiBodiedExtensionWithWidth = function MultiBodiedExtensionWithWidth(_ref2) {
  var node = _ref2.node,
    handleContentDOMRef = _ref2.handleContentDOMRef,
    getPos = _ref2.getPos,
    tryExtensionHandler = _ref2.tryExtensionHandler,
    editorView = _ref2.editorView,
    eventDispatcher = _ref2.eventDispatcher,
    widthState = _ref2.widthState,
    editorAppearance = _ref2.editorAppearance,
    macroInteractionDesignFeatureFlags = _ref2.macroInteractionDesignFeatureFlags,
    isNodeSelected = _ref2.isNodeSelected,
    isNodeHovered = _ref2.isNodeHovered,
    isNodeNested = _ref2.isNodeNested,
    setIsNodeHovered = _ref2.setIsNodeHovered,
    pluginInjectionApi = _ref2.pluginInjectionApi,
    isLivePageViewMode = _ref2.isLivePageViewMode,
    _ref2$allowBodiedOver = _ref2.allowBodiedOverride,
    allowBodiedOverride = _ref2$allowBodiedOver === void 0 ? false : _ref2$allowBodiedOver;
  var _ref3 = macroInteractionDesignFeatureFlags || {},
    showMacroInteractionDesignUpdates = _ref3.showMacroInteractionDesignUpdates;
  var _node$attrs = node.attrs,
    parameters = _node$attrs.parameters,
    extensionKey = _node$attrs.extensionKey;
  var title = parameters && parameters.extensionTitle || parameters && parameters.macroMetadata && parameters.macroMetadata.title || extensionKey || node.type.name;
  var imageData = getExtensionLozengeData({
    node: node,
    type: 'image'
  });
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    activeChildIndex = _useState2[0],
    setActiveChildIndex = _useState2[1];
  // Adding to avoid aliasing `this` for the callbacks
  var updateActiveChild = React.useCallback(function (index) {
    if (typeof index !== 'number') {
      setActiveChildIndex(0);
      throw new Error('Index is not valid');
    }
    setActiveChildIndex(index);
    return true;
  }, [setActiveChildIndex]);
  var articleRef = React.useCallback(function (node) {
    return handleContentDOMRef(node);
  }, [handleContentDOMRef]);
  var childrenContainer = React.useMemo(function () {
    return jsx(MultiBodiedExtensionFrames, {
      articleRef: articleRef
    });
  }, [articleRef]);
  var actions = useMultiBodiedExtensionActions({
    updateActiveChild: updateActiveChild,
    editorView: editorView,
    getPos: getPos,
    node: node,
    eventDispatcher: eventDispatcher,
    allowBodiedOverride: allowBodiedOverride,
    childrenContainer: childrenContainer
  });
  var extensionHandlerResult = React.useMemo(function () {
    return tryExtensionHandler(actions);
  }, [tryExtensionHandler, actions]);
  var layout = node.attrs.layout;
  var legacyShouldBreakout = ['full-width', 'wide'].includes(layout) && editorAppearance !== 'full-width';
  var tinymceFullWidthModeEnabled = expValEquals('confluence_max_width_content_appearance', 'isEnabled', true);
  var breakoutExtensionFixEnabled = expValEquals('confluence_max_width_breakout_extension_fix', 'isEnabled', true);
  var shouldUseBreakoutFix = tinymceFullWidthModeEnabled && breakoutExtensionFixEnabled;
  var shouldBreakout = shouldUseBreakoutFix ? shouldExtensionBreakout({
    layout: layout,
    editorAppearance: editorAppearance,
    isTopLevelNode: true
  }) : legacyShouldBreakout;
  var mbeWrapperStyles = {};
  if (shouldBreakout) {
    var _calculateBreakoutSty = calculateBreakoutStyles({
        mode: node.attrs.layout,
        widthStateLineLength: widthState === null || widthState === void 0 ? void 0 : widthState.lineLength,
        widthStateWidth: widthState === null || widthState === void 0 ? void 0 : widthState.width
      }),
      breakoutStyles = _extends({}, (_objectDestructuringEmpty(_calculateBreakoutSty), _calculateBreakoutSty));
    mbeWrapperStyles = breakoutStyles;
  }
  var wrapperClassNames = classnames('multiBodiedExtension--wrapper', 'extension-container', 'block', {
    'with-border': showMacroInteractionDesignUpdates,
    'with-danger-overlay': showMacroInteractionDesignUpdates,
    'with-padding-background-styles': showMacroInteractionDesignUpdates,
    'with-margin-styles': showMacroInteractionDesignUpdates && !isNodeNested,
    'with-hover-border': expValEquals('cc_editor_ttvc_release_bundle_one', 'extensionHoverRefactor', true) ? false : showMacroInteractionDesignUpdates && isNodeHovered
  });
  var containerClassNames = classnames('multiBodiedExtension--container', {
    'remove-padding': showMacroInteractionDesignUpdates
  });
  var bodyContainerClassNames = classnames('multiBodiedExtension--body-container');
  var navigationClassNames = classnames('multiBodiedExtension--navigation', {
    'remove-margins': showMacroInteractionDesignUpdates,
    'remove-border': showMacroInteractionDesignUpdates
  });
  var overlayClassNames = classnames('multiBodiedExtension--overlay', {
    'with-margin': showMacroInteractionDesignUpdates
  });
  var handleMouseEvent = function handleMouseEvent(didHover) {
    if (setIsNodeHovered) {
      setIsNodeHovered(didHover);
    }
  };
  return jsx(Fragment, null, showMacroInteractionDesignUpdates && !isLivePageViewMode && jsx(ExtensionLozenge, {
    isNodeSelected: isNodeSelected,
    node: node,
    showMacroInteractionDesignUpdates: true,
    customContainerStyles: mbeWrapperStyles,
    isNodeHovered: isNodeHovered,
    isNodeNested: isNodeNested,
    setIsNodeHovered: setIsNodeHovered,
    isBodiedMacro: true,
    pluginInjectionApi: pluginInjectionApi
  }), jsx("div", {
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    className: wrapperClassNames,
    css: [
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
    mbeExtensionWrapperCSSStyles, showMacroInteractionDesignUpdates && !isLivePageViewMode && expValEquals('cc_editor_ttvc_release_bundle_one', 'extensionHoverRefactor', true) && hoverStyles],
    "data-testid": "multiBodiedExtension--wrapper-editor",
    "data-layout": node.attrs.layout
    // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
    ,
    style: mbeWrapperStyles,
    onMouseEnter: function onMouseEnter() {
      return handleMouseEvent(true);
    }
    // @atlassian/a11y/mouse-events-have-key-events: hover border is also applied via .ak-editor-selected-node
    // CSS on keyboard selection. No-ops here satisfy the rule without duplicating state updates.
    ,
    onFocus: expValEquals('editor_a11y__enghealth-46814_fy26', 'isEnabled', true) ? function () {} : undefined,
    onMouseLeave: function onMouseLeave() {
      return handleMouseEvent(false);
    },
    onBlur: expValEquals('editor_a11y__enghealth-46814_fy26', 'isEnabled', true) ? function () {} : undefined
  }, jsx("div", {
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
    css: overlayStyles
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    ,
    className: overlayClassNames,
    "data-testid": "multiBodiedExtension--overlay"
  }), getWrapperTitleContent(imageData, title, showMacroInteractionDesignUpdates), jsx("div", {
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    className: containerClassNames
    // eslint-disable-next-line @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
    ,
    css: getContainerCssExtendedStyles(activeChildIndex, showMacroInteractionDesignUpdates),
    "data-testid": "multiBodiedExtension--container",
    "data-active-child-index": activeChildIndex
  }, allowBodiedOverride ? jsx("div", {
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    className: bodyContainerClassNames,
    "data-testid": "multiBodiedExtension--body-container"
  }, extensionHandlerResult) : jsx(Fragment, null, jsx("nav", {
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    className: navigationClassNames
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values -- Ignored via go/DSP-18766
    ,
    css: sharedMultiBodiedExtensionStyles.mbeNavigation,
    "data-testid": "multiBodiedExtension-navigation"
  }, extensionHandlerResult), childrenContainer))));
};
var MultiBodiedExtension = function MultiBodiedExtension(props) {
  var pluginInjectionApi = props.pluginInjectionApi;
  var _useSharedPluginState = useSharedPluginStateWithSelector(pluginInjectionApi, ['width'], function (states) {
      var _states$widthState, _states$widthState2;
      return {
        width: (_states$widthState = states.widthState) === null || _states$widthState === void 0 ? void 0 : _states$widthState.width,
        lineLength: (_states$widthState2 = states.widthState) === null || _states$widthState2 === void 0 ? void 0 : _states$widthState2.lineLength
      };
    }),
    width = _useSharedPluginState.width,
    lineLength = _useSharedPluginState.lineLength;
  // Ignored via go/ees005
  return jsx(MultiBodiedExtensionWithWidth, _extends({
    widthState: width === undefined ? undefined : {
      width: width,
      lineLength: lineLength
    }
    // eslint-disable-next-line react/jsx-props-no-spreading
  }, props));
};
export default MultiBodiedExtension;