import _extends from "@babel/runtime/helpers/extends";
/** @jsx jsx */
import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import { css, jsx } from '@emotion/react';
import { FormattedMessage } from 'react-intl-next';
import { withAnalyticsContext, withAnalyticsEvents } from '@atlaskit/analytics-next';
import { getBooleanFF } from '@atlaskit/platform-feature-flags';
import { ACTION, ACTION_SUBJECT, EVENT_TYPE, fireAnalyticsEvent } from '../../analytics';
import { DEVICE_BREAKPOINT_NUMBERS, 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 { ViewMore } from '../ViewMore';
import CategoryList from './CategoryList';
import ElementList from './ElementList/ElementList';
import ElementSearch from './ElementSearch';
const wrapper = css({
  width: '100%',
  maxHeight: 'inherit',
  overflow: 'hidden'
});
const baseBrowserContainerStyles = css({
  display: 'flex',
  height: '100%',
  minHeight: '-webkit-fill-available'
});
const mobileElementBrowserContainer = css(baseBrowserContainerStyles, {
  flexDirection: 'column'
});
const elementBrowserContainer = css(baseBrowserContainerStyles, {
  flexDirection: 'row'
});
const baseSidebarStyles = css({
  display: 'flex',
  flexDirection: 'column',
  overflowX: 'auto',
  overflowY: 'hidden'
});
const mobileSideBar = css(baseSidebarStyles, {
  flex: `0 0 ${INLINE_SIDEBAR_HEIGHT}`,
  padding: `${"var(--ds-space-150, 12px)"} ${"var(--ds-space-150, 12px)"} 0 ${"var(--ds-space-150, 12px)"}`
});
const mobileSideBarShowCategories = css({
  flex: '0 0 auto'
});
const sideBar = css(baseSidebarStyles, {
  flex: "0 0 'auto'"
});
const sideBarShowCategories = css(baseSidebarStyles, {
  flex: `0 0 ${SIDEBAR_WIDTH}`
});
const sidebarHeading = css({
  flex: `0 0 ${SIDEBAR_HEADING_WRAPPER_HEIGHT}`,
  display: 'inline-flex',
  alignItems: 'center',
  paddingLeft: "var(--ds-space-150, 12px)",
  fontWeight: 700
});
const mobileMainContent = css({
  flex: '1 1 auto',
  display: 'flex',
  flexDirection: 'column',
  overflowY: 'auto',
  height: '100%'
});
const mainContent = css(mobileMainContent, {
  marginLeft: "var(--ds-space-200, 16px)",
  height: 'auto'
});
const searchContainer = css({
  paddingBottom: "var(--ds-space-200, 16px)"
});
const mobileCategoryListWrapper = css({
  display: 'flex',
  overflowX: 'auto',
  padding: `${"var(--ds-space-200, 8px)"} 0 ${"var(--ds-space-200, 16px)"} 0`,
  minHeight: `${GRID_SIZE * 4}px`,
  overflow: '-moz-scrollbars-none',
  '::-webkit-scrollbar': {
    display: 'none'
  },
  scrollbarWidth: 'none',
  MsOverflowStyle: 'none'
});
const categoryListWrapper = css(mobileCategoryListWrapper, {
  padding: 0,
  marginTop: "var(--ds-space-200, 24px)",
  flexDirection: 'column'
});
function StatelessElementBrowser(props) {
  const {
    items,
    onSelectItem,
    onInsertItem,
    viewMoreItem,
    selectedCategory,
    onSelectCategory,
    searchTerm,
    showCategories
  } = props;
  const {
    containerWidth,
    ContainerWidthMonitor
  } = useContainerWidth();
  const categoryBeenChosen = useRef(false);
  const [columnCount, setColumnCount] = useState(1);
  let selectedCategoryIndex;
  let isFocusSearch;
  if (getBooleanFF('platform.editor.a11y-focus-order-for-element-browser-categories_ztiw1')) {
    var _props$categories;
    selectedCategoryIndex = (_props$categories = props.categories) === null || _props$categories === void 0 ? void 0 : _props$categories.findIndex(category => {
      return category.name === selectedCategory;
    });
    if (showCategories) {
      const 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, on the initial render search element should receive focus.
      // After user pick some category the category should stay focused.
      isFocusSearch = !categoryBeenChosen.current || !isEmptySearchTerm;
    }
  }
  const {
    selectedItemIndex,
    focusedItemIndex,
    setFocusedItemIndex,
    setFocusedCategoryIndex,
    focusedCategoryIndex,
    focusOnSearch,
    focusOnViewMore,
    onKeyDown,
    setFocusOnSearch
  } = useSelectAndFocusOnArrowNavigation(items.length - 1, columnCount, !!viewMoreItem, isFocusSearch);
  useEffect(() => {
    fireAnalyticsEvent(props.createAnalyticsEvent)({
      payload: {
        action: ACTION.OPENED,
        actionSubject: ACTION_SUBJECT.ELEMENT_BROWSER,
        eventType: EVENT_TYPE.UI,
        attributes: {
          mode: props.mode
        }
      }
    });
    return () => {
      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.
   */
  const selectedItem = selectedItemIndex !== undefined ? items[selectedItemIndex] : null;
  const onItemsEnterTabKeyPress = useCallback(e => {
    if (getBooleanFF('platform.editor.a11y-focus-order-for-element-browser-categories_ztiw1')) {
      if (e.key !== 'Enter' && (e.key !== 'Tab' || !showCategories)) {
        return;
      }
    } else {
      if (e.key !== 'Enter') {
        return;
      }
    }
    if (getBooleanFF('platform.editor.a11y-focus-order-for-element-browser-categories_ztiw1')) {
      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) {
      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(() => {
    if (onSelectItem && selectedItem != null) {
      onSelectItem(selectedItem);
    }
  }, [onSelectItem, selectedItem]);
  const onSelectCategoryCB = useCallback(category => {
    onSelectCategory(category);
    categoryBeenChosen.current = true;
  }, [categoryBeenChosen, onSelectCategory]);
  return jsx("div", {
    css: wrapper,
    "data-testid": "element-browser"
  }, jsx(ContainerWidthMonitor, null), containerWidth < DEVICE_BREAKPOINT_NUMBERS.medium ? jsx(MobileBrowser, _extends({}, props, {
    selectedItemIndex: selectedItemIndex,
    focusedItemIndex: focusedItemIndex,
    setFocusedItemIndex: setFocusedItemIndex,
    focusedCategoryIndex: focusedCategoryIndex,
    setFocusedCategoryIndex: setFocusedCategoryIndex,
    focusOnSearch: focusOnSearch,
    setColumnCount: setColumnCount,
    setFocusOnSearch: setFocusOnSearch,
    onKeyPress: onItemsEnterTabKeyPress,
    onKeyDown: onKeyDown,
    viewMoreItem: viewMoreItem,
    focusOnViewMore: focusOnViewMore
  })) : jsx(DesktopBrowser, _extends({}, props, {
    selectedItemIndex: selectedItemIndex,
    focusedItemIndex: focusedItemIndex,
    setFocusedItemIndex: setFocusedItemIndex,
    focusOnSearch: focusOnSearch,
    setColumnCount: setColumnCount,
    setFocusOnSearch: setFocusOnSearch,
    onKeyPress: onItemsEnterTabKeyPress,
    onKeyDown: onKeyDown,
    focusedCategoryIndex: focusedCategoryIndex,
    setFocusedCategoryIndex: setFocusedCategoryIndex,
    selectedCategoryIndex: selectedCategoryIndex,
    onSelectCategory: getBooleanFF('platform.editor.a11y-focus-order-for-element-browser-categories_ztiw1') ? onSelectCategoryCB : onSelectCategory
  })));
}
function MobileBrowser({
  showCategories,
  showSearch,
  onSearch,
  mode,
  categories,
  onSelectCategory,
  items,
  onInsertItem,
  selectedCategory,
  selectedItemIndex,
  focusedItemIndex,
  setFocusedItemIndex,
  focusedCategoryIndex,
  setFocusedCategoryIndex,
  focusOnSearch,
  focusOnViewMore,
  setColumnCount,
  setFocusOnSearch,
  onKeyPress,
  onKeyDown,
  searchTerm,
  createAnalyticsEvent,
  emptyStateHandler,
  viewMoreItem
}) {
  return 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
  }), 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
  }, jsx(ElementList, {
    items: items,
    mode: mode,
    onInsertItem: onInsertItem,
    selectedItemIndex: selectedItemIndex,
    focusedItemIndex: focusedItemIndex,
    setFocusedItemIndex: setFocusedItemIndex,
    setColumnCount: setColumnCount,
    createAnalyticsEvent: createAnalyticsEvent,
    emptyStateHandler: emptyStateHandler,
    selectedCategory: selectedCategory,
    searchTerm: searchTerm
  })), viewMoreItem && jsx(ViewMore, {
    item: viewMoreItem,
    focus: focusOnViewMore
  }));
}
function DesktopBrowser({
  showCategories,
  showSearch,
  onSearch,
  mode,
  categories,
  onSelectCategory,
  items,
  onInsertItem,
  selectedCategory,
  selectedItemIndex,
  focusedItemIndex,
  setFocusedItemIndex,
  focusedCategoryIndex,
  setFocusedCategoryIndex,
  selectedCategoryIndex,
  focusOnSearch,
  setColumnCount,
  setFocusOnSearch,
  onKeyPress,
  onKeyDown,
  searchTerm,
  createAnalyticsEvent,
  emptyStateHandler
}) {
  return jsx("div", {
    css: elementBrowserContainer,
    "data-testid": "desktop__element-browser"
  }, showCategories && jsx("div", {
    css: showCategories ? sideBarShowCategories : sideBar
  }, jsx("h2", {
    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
  })), jsx(ElementList, {
    items: items,
    mode: mode,
    onInsertItem: onInsertItem,
    selectedItemIndex: selectedItemIndex,
    focusedItemIndex: focusedItemIndex,
    setFocusedItemIndex: setFocusedItemIndex,
    setColumnCount: setColumnCount,
    createAnalyticsEvent: createAnalyticsEvent,
    emptyStateHandler: emptyStateHandler,
    selectedCategory: selectedCategory,
    selectedCategoryIndex: selectedCategoryIndex,
    searchTerm: searchTerm,
    setFocusedCategoryIndex: showCategories ? setFocusedCategoryIndex : undefined
  })));
}
const MemoizedElementBrowser = /*#__PURE__*/memo(withAnalyticsContext({
  source: 'ElementBrowser'
})(withAnalyticsEvents()(StatelessElementBrowser)));
export default MemoizedElementBrowser;