import _extends from "@babel/runtime/helpers/extends";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
/**
 * @jsxRuntime classic
 * @jsx jsx
 */
import React, { memo, useCallback, useEffect, useRef, useState } from 'react';

// eslint-disable-next-line @atlaskit/ui-styling-standard/use-compiled -- Ignored via go/DSP-18766
import { css, jsx } from '@emotion/react';
import { FormattedMessage } from 'react-intl-next';
import withAnalyticsContext from '@atlaskit/analytics-next/withAnalyticsContext';
import withAnalyticsEvents from '@atlaskit/analytics-next/withAnalyticsEvents';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { ACTION, ACTION_SUBJECT, EVENT_TYPE, fireAnalyticsEvent } from '../../analytics';
import editorUGCToken from '../../ugc-tokens/get-editor-ugc-token';
import { ViewMore } from '../components/ViewMore';
import { DEVICE_BREAKPOINT_NUMBERS, ELEMENT_BROWSER_ID, ELEMENT_BROWSER_LIST_ID, GRID_SIZE, INLINE_SIDEBAR_HEIGHT, SIDEBAR_HEADING_WRAPPER_HEIGHT, SIDEBAR_WIDTH } from '../constants';
import useContainerWidth from '../hooks/use-container-width';
import useSelectAndFocusOnArrowNavigation from '../hooks/use-select-and-focus-on-arrow-navigation';
import CategoryList from './CategoryList';
import ElementList from './ElementList/ElementList';
import ElementSearch from './ElementSearch';
var wrapper = css({
  width: '100%',
  maxHeight: 'inherit',
  overflow: 'hidden'
});
var baseBrowserContainerStyles = css({
  display: 'flex',
  height: '100%',
  minHeight: '-webkit-fill-available'
});

// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var mobileElementBrowserContainer = css(baseBrowserContainerStyles, {
  flexDirection: 'column'
});

// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var elementBrowserContainer = css(baseBrowserContainerStyles, {
  flexDirection: 'row'
});
var baseSidebarStyles = css({
  display: 'flex',
  flexDirection: 'column',
  overflowX: 'auto',
  overflowY: 'hidden'
});

// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var mobileSideBar = css(baseSidebarStyles, {
  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
  flex: "0 0 ".concat(INLINE_SIDEBAR_HEIGHT),
  padding: "var(--ds-space-150, 12px)".concat(" ", "var(--ds-space-150, 12px)", " 0 ", "var(--ds-space-150, 12px)")
});
var mobileSideBarShowCategories = css({
  flex: '0 0 auto'
});
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var sideBar = css(baseSidebarStyles, {
  flex: "0 0 'auto'"
});

// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var sideBarShowCategories = css(baseSidebarStyles, {
  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
  flex: "0 0 ".concat(SIDEBAR_WIDTH)
});
var sidebarHeading = 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
  flex: "0 0 ".concat(SIDEBAR_HEADING_WRAPPER_HEIGHT),
  display: 'inline-flex',
  alignItems: 'center',
  paddingLeft: "var(--ds-space-150, 12px)",
  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values
  font: editorUGCToken('editor.font.heading.h1')
});
var mobileMainContent = css({
  flex: '1 1 auto',
  display: 'flex',
  flexDirection: 'column',
  overflowY: 'auto',
  height: '100%'
});

// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var mainContent = css(mobileMainContent, {
  marginLeft: "var(--ds-space-200, 16px)",
  height: 'auto'
});
var searchContainer = css({
  paddingBottom: "var(--ds-space-200, 16px)"
});
var mobileCategoryListWrapper = css({
  display: 'flex',
  overflowX: 'auto',
  padding: "var(--ds-space-200, 8px)".concat(" 0 ", "var(--ds-space-200, 16px)", " 0"),
  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
  minHeight: "".concat(GRID_SIZE * 4, "px"),
  overflow: '-moz-scrollbars-none',
  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-selectors -- Ignored via go/DSP-18766
  '&::-webkit-scrollbar': {
    display: 'none'
  },
  scrollbarWidth: 'none',
  MsOverflowStyle: 'none'
});

// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
var categoryListWrapper = css(mobileCategoryListWrapper, {
  padding: 0,
  marginTop: "var(--ds-space-200, 24px)",
  flexDirection: 'column'
});
function StatelessElementBrowser(props) {
  var _props$categories;
  var items = props.items,
    onSelectItem = props.onSelectItem,
    onInsertItem = props.onInsertItem,
    onViewMore = props.onViewMore,
    selectedCategory = props.selectedCategory,
    onSelectCategory = props.onSelectCategory,
    searchTerm = props.searchTerm,
    showCategories = props.showCategories,
    cache = props.cache,
    _props$autoFocusSearc = props.autoFocusSearch,
    autoFocusSearch = _props$autoFocusSearc === void 0 ? true : _props$autoFocusSearc;
  var _useContainerWidth = useContainerWidth(),
    containerWidth = _useContainerWidth.containerWidth,
    ContainerWidthMonitor = _useContainerWidth.ContainerWidthMonitor;
  var categoryBeenChosen = useRef(false);
  var _useState = useState(1),
    _useState2 = _slicedToArray(_useState, 2),
    columnCount = _useState2[0],
    setColumnCount = _useState2[1];
  var isFocusSearch;
  var selectedCategoryIndex = (_props$categories = props.categories) === null || _props$categories === void 0 ? void 0 : _props$categories.findIndex(function (category) {
    return category.name === selectedCategory;
  });
  var _useState3 = useState(autoFocusSearch),
    _useState4 = _slicedToArray(_useState3, 2),
    canFocusSearch = _useState4[0],
    setCanFocusSearch = _useState4[1];
  if (showCategories) {
    var isEmptySearchTerm = !searchTerm || (searchTerm === null || searchTerm === void 0 ? void 0 : searchTerm.length) === 0;
    if (!isEmptySearchTerm) {
      // clear the flag if the search happens after a user has chosen the category
      categoryBeenChosen.current = false;
    }

    // A11Y: if categories exists and search can be focused, on the initial render it should receive focus.
    // After user pick some category the category should stay focused.
    isFocusSearch = canFocusSearch && (!categoryBeenChosen.current || !isEmptySearchTerm);
  }
  var itemIsDisabled = useCallback(function (index) {
    var _items$index$isDisabl, _items$index;
    return (_items$index$isDisabl = (_items$index = items[index]) === null || _items$index === void 0 ? void 0 : _items$index.isDisabled) !== null && _items$index$isDisabl !== void 0 ? _items$index$isDisabl : false;
  }, [items]);
  var _useSelectAndFocusOnA = useSelectAndFocusOnArrowNavigation(items.length - 1, columnCount, !!onViewMore, itemIsDisabled, isFocusSearch, autoFocusSearch),
    selectedItemIndex = _useSelectAndFocusOnA.selectedItemIndex,
    focusedItemIndex = _useSelectAndFocusOnA.focusedItemIndex,
    setFocusedItemIndex = _useSelectAndFocusOnA.setFocusedItemIndex,
    setFocusedCategoryIndex = _useSelectAndFocusOnA.setFocusedCategoryIndex,
    focusOnEmptyStateButton = _useSelectAndFocusOnA.focusOnEmptyStateButton,
    focusedCategoryIndex = _useSelectAndFocusOnA.focusedCategoryIndex,
    focusOnSearch = _useSelectAndFocusOnA.focusOnSearch,
    focusOnViewMore = _useSelectAndFocusOnA.focusOnViewMore,
    onKeyDown = _useSelectAndFocusOnA.onKeyDown,
    setFocusOnSearch = _useSelectAndFocusOnA.setFocusOnSearch;
  useEffect(function () {
    fireAnalyticsEvent(props.createAnalyticsEvent)({
      payload: {
        action: ACTION.OPENED,
        actionSubject: ACTION_SUBJECT.ELEMENT_BROWSER,
        eventType: EVENT_TYPE.UI,
        attributes: {
          mode: props.mode
        }
      }
    });
    return function () {
      fireAnalyticsEvent(props.createAnalyticsEvent)({
        payload: {
          action: ACTION.CLOSED,
          actionSubject: ACTION_SUBJECT.ELEMENT_BROWSER,
          eventType: EVENT_TYPE.UI,
          attributes: {
            mode: props.mode
          }
        }
      });
    };
  }, [props.createAnalyticsEvent, props.mode]);

  /* Only for hitting enter to select item when focused on search bar,
   * The actual enter key press is handled on individual items level.
   */
  var selectedItem = selectedItemIndex !== undefined ? items[selectedItemIndex] : null;
  var onItemsEnterTabKeyPress = useCallback(function (e) {
    var _selectedItem$isDisab;
    if (e.key !== 'Enter' && (e.key !== 'Tab' || !showCategories)) {
      return;
    }
    if (showCategories && e.key === 'Tab' && selectedCategoryIndex !== undefined) {
      // A11Y: Set focus on first category if tab pressed on search
      setFocusedCategoryIndex(selectedCategoryIndex);
      e.preventDefault();
      return;
    }
    if (onInsertItem && selectedItem != null && !((_selectedItem$isDisab = selectedItem.isDisabled) !== null && _selectedItem$isDisab !== void 0 ? _selectedItem$isDisab : false)) {
      onInsertItem(selectedItem);
    }
    e.preventDefault();
  }, [onInsertItem, selectedItem, setFocusedCategoryIndex, showCategories, selectedCategoryIndex]);

  /**
   * On arrow key selection and clicks the selectedItemIndex will change.
   * Making sure to update parent component.
   */
  useEffect(function () {
    if (onSelectItem && selectedItem != null) {
      onSelectItem(selectedItem);
    }
  }, [onSelectItem, selectedItem]);
  var onSelectCategoryCB = useCallback(function (category) {
    onSelectCategory(category);
    categoryBeenChosen.current = true;
  }, [categoryBeenChosen, onSelectCategory]);
  var handleKeyPress = function handleKeyPress(e) {
    if (e.key === 'Tab') {
      // only Tab key can change focus from close button (if present)
      setCanFocusSearch(true);
    }
  };
  var handleClick = function handleClick() {
    setCanFocusSearch(true);
  };
  return /* eslint-disable-next-line @atlassian/a11y/interactive-element-not-keyboard-focusable*/(
    jsx("div", {
      css: wrapper,
      "data-testid": "element-browser",
      id: ELEMENT_BROWSER_ID,
      onKeyUp: canFocusSearch ? undefined : handleKeyPress,
      onClick: canFocusSearch ? undefined : handleClick
    }, jsx(ContainerWidthMonitor, null), containerWidth < DEVICE_BREAKPOINT_NUMBERS.medium ? jsx(MobileBrowser
    // Ignored via go/ees005
    // eslint-disable-next-line react/jsx-props-no-spreading
    , _extends({}, props, {
      selectedItemIndex: selectedItemIndex,
      focusOnEmptyStateButton: focusOnEmptyStateButton,
      focusedItemIndex: focusedItemIndex,
      setFocusedItemIndex: setFocusedItemIndex,
      focusedCategoryIndex: focusedCategoryIndex,
      setFocusedCategoryIndex: setFocusedCategoryIndex,
      focusOnSearch: focusOnSearch,
      columnCount: columnCount,
      setColumnCount: setColumnCount,
      setFocusOnSearch: setFocusOnSearch,
      onKeyPress: onItemsEnterTabKeyPress,
      onKeyDown: onKeyDown,
      onViewMore: onViewMore,
      focusOnViewMore: focusOnViewMore,
      cache: cache
    })) : jsx(DesktopBrowser
    // Ignored via go/ees005
    // eslint-disable-next-line react/jsx-props-no-spreading
    , _extends({}, props, {
      selectedItemIndex: selectedItemIndex,
      focusOnEmptyStateButton: focusOnEmptyStateButton,
      focusedItemIndex: focusedItemIndex,
      setFocusedItemIndex: setFocusedItemIndex,
      focusOnSearch: focusOnSearch,
      setColumnCount: setColumnCount,
      columnCount: columnCount,
      setFocusOnSearch: setFocusOnSearch,
      onKeyPress: onItemsEnterTabKeyPress,
      onKeyDown: onKeyDown,
      focusedCategoryIndex: focusedCategoryIndex,
      setFocusedCategoryIndex: setFocusedCategoryIndex,
      selectedCategoryIndex: selectedCategoryIndex,
      onSelectCategory: onSelectCategoryCB,
      cache: cache
    })))
  );
}
function MobileBrowser(_ref) {
  var showCategories = _ref.showCategories,
    showSearch = _ref.showSearch,
    onSearch = _ref.onSearch,
    mode = _ref.mode,
    categories = _ref.categories,
    onSelectCategory = _ref.onSelectCategory,
    items = _ref.items,
    onInsertItem = _ref.onInsertItem,
    selectedCategory = _ref.selectedCategory,
    selectedItemIndex = _ref.selectedItemIndex,
    focusedItemIndex = _ref.focusedItemIndex,
    setFocusedItemIndex = _ref.setFocusedItemIndex,
    focusedCategoryIndex = _ref.focusedCategoryIndex,
    setFocusedCategoryIndex = _ref.setFocusedCategoryIndex,
    focusOnSearch = _ref.focusOnSearch,
    focusOnViewMore = _ref.focusOnViewMore,
    columnCount = _ref.columnCount,
    setColumnCount = _ref.setColumnCount,
    setFocusOnSearch = _ref.setFocusOnSearch,
    onKeyPress = _ref.onKeyPress,
    onKeyDown = _ref.onKeyDown,
    searchTerm = _ref.searchTerm,
    createAnalyticsEvent = _ref.createAnalyticsEvent,
    emptyStateHandler = _ref.emptyStateHandler,
    onViewMore = _ref.onViewMore,
    cache = _ref.cache,
    _ref$focusOnEmptyStat = _ref.focusOnEmptyStateButton,
    focusOnEmptyStateButton = _ref$focusOnEmptyStat === void 0 ? false : _ref$focusOnEmptyStat;
  return (
    // eslint-disable-next-line @atlassian/a11y/no-static-element-interactions
    jsx("div", {
      css: mobileElementBrowserContainer,
      onKeyDown: onKeyDown,
      "data-testid": "mobile__element-browser"
    }, jsx("div", {
      css: showCategories ? [mobileSideBar, mobileSideBarShowCategories] : mobileSideBar
    }, showSearch && jsx(ElementSearch, {
      onSearch: onSearch,
      onKeyDown: onKeyPress,
      mode: mode,
      focus: focusOnSearch,
      onClick: setFocusOnSearch,
      searchTerm: searchTerm,
      items: items,
      selectedItemIndex: selectedItemIndex,
      ariaControlsId: expValEquals('platform_editor_august_a11y', 'isEnabled', true) ? ELEMENT_BROWSER_LIST_ID : undefined
    }), showCategories && jsx("nav", {
      css: mobileCategoryListWrapper,
      tabIndex: -1
    }, jsx(CategoryList, {
      categories: categories,
      onSelectCategory: onSelectCategory,
      selectedCategory: selectedCategory,
      focusedCategoryIndex: focusedCategoryIndex,
      setFocusedCategoryIndex: setFocusedCategoryIndex,
      setFocusedItemIndex: setFocusedItemIndex,
      setFocusOnSearch: setFocusOnSearch
    }))), jsx("div", {
      css: mobileMainContent,
      id: expValEquals('platform_editor_august_a11y', 'isEnabled', true) ? ELEMENT_BROWSER_LIST_ID : undefined
    }, jsx(ElementList, {
      items: items,
      mode: mode,
      onInsertItem: onInsertItem,
      selectedItemIndex: selectedItemIndex,
      focusedItemIndex: focusedItemIndex,
      focusOnEmptyStateButton: focusOnEmptyStateButton,
      setFocusedItemIndex: setFocusedItemIndex,
      columnCount: columnCount,
      setColumnCount: setColumnCount,
      createAnalyticsEvent: createAnalyticsEvent,
      emptyStateHandler: emptyStateHandler,
      selectedCategory: selectedCategory,
      searchTerm: searchTerm,
      cache: cache,
      hasTabListContext: false
    })), onViewMore && jsx(ViewMore, {
      onViewMore: onViewMore,
      focus: focusOnViewMore
    }))
  );
}
function DesktopBrowser(_ref2) {
  var showCategories = _ref2.showCategories,
    showSearch = _ref2.showSearch,
    onSearch = _ref2.onSearch,
    mode = _ref2.mode,
    categories = _ref2.categories,
    onSelectCategory = _ref2.onSelectCategory,
    items = _ref2.items,
    onInsertItem = _ref2.onInsertItem,
    selectedCategory = _ref2.selectedCategory,
    selectedItemIndex = _ref2.selectedItemIndex,
    focusedItemIndex = _ref2.focusedItemIndex,
    setFocusedItemIndex = _ref2.setFocusedItemIndex,
    focusedCategoryIndex = _ref2.focusedCategoryIndex,
    setFocusedCategoryIndex = _ref2.setFocusedCategoryIndex,
    selectedCategoryIndex = _ref2.selectedCategoryIndex,
    focusOnSearch = _ref2.focusOnSearch,
    columnCount = _ref2.columnCount,
    setColumnCount = _ref2.setColumnCount,
    setFocusOnSearch = _ref2.setFocusOnSearch,
    onKeyPress = _ref2.onKeyPress,
    onKeyDown = _ref2.onKeyDown,
    searchTerm = _ref2.searchTerm,
    createAnalyticsEvent = _ref2.createAnalyticsEvent,
    emptyStateHandler = _ref2.emptyStateHandler,
    cache = _ref2.cache,
    _ref2$focusOnEmptySta = _ref2.focusOnEmptyStateButton,
    focusOnEmptyStateButton = _ref2$focusOnEmptySta === void 0 ? false : _ref2$focusOnEmptySta;
  return jsx("div", {
    css: elementBrowserContainer,
    "data-testid": "desktop__element-browser"
  }, showCategories && jsx("div", {
    css: showCategories ? sideBarShowCategories : sideBar
  }, jsx("div", {
    css: sidebarHeading,
    "data-testid": "sidebar-heading",
    id: "sidebar-heading"
  }, jsx(FormattedMessage, {
    id: "fabric.editor.elementbrowser.sidebar.heading",
    defaultMessage: "Browse",
    description: "Sidebar heading"
  })), jsx("nav", {
    role: "tablist",
    "aria-labelledby": "sidebar-heading",
    css: categoryListWrapper
  }, jsx(CategoryList, {
    categories: categories,
    onSelectCategory: onSelectCategory,
    selectedCategory: selectedCategory,
    createAnalyticsEvent: createAnalyticsEvent,
    focusedCategoryIndex: focusedCategoryIndex,
    setFocusedCategoryIndex: setFocusedCategoryIndex,
    setFocusedItemIndex: setFocusedItemIndex,
    setFocusOnSearch: setFocusOnSearch
  }))), jsx("div", {
    css: mainContent,
    onKeyDown: onKeyDown,
    "data-testid": "main-content"
  }, showSearch &&
  // eslint-disable-next-line
  jsx("div", {
    css: searchContainer
  }, jsx(ElementSearch, {
    onSearch: onSearch,
    onKeyDown: onKeyPress,
    mode: mode,
    focus: focusOnSearch,
    onClick: setFocusOnSearch,
    searchTerm: searchTerm,
    items: items,
    selectedItemIndex: selectedItemIndex,
    ariaControlsId: selectedCategory ? "browse-category-".concat(selectedCategory, "-tab") : 'browse-category-tab'
  })), jsx(ElementList, {
    items: items,
    mode: mode,
    onInsertItem: onInsertItem,
    selectedItemIndex: selectedItemIndex,
    focusedItemIndex: focusedItemIndex,
    focusOnEmptyStateButton: focusOnEmptyStateButton,
    setFocusedItemIndex: setFocusedItemIndex,
    columnCount: columnCount,
    setColumnCount: setColumnCount,
    createAnalyticsEvent: createAnalyticsEvent,
    emptyStateHandler: emptyStateHandler,
    selectedCategory: selectedCategory,
    selectedCategoryIndex: selectedCategoryIndex,
    searchTerm: searchTerm,
    setFocusedCategoryIndex: showCategories ? setFocusedCategoryIndex : undefined,
    cache: cache,
    hasTabListContext: showCategories
  })));
}
var MemoizedElementBrowser = /*#__PURE__*/memo(withAnalyticsContext({
  source: 'ElementBrowser'
})(withAnalyticsEvents()(StatelessElementBrowser)));
export default MemoizedElementBrowser;