import React from 'react';
import { Item } from '../Item/Item.js';
import { Box } from '../../../Box/Box.js';
import { Text } from '../../../Text/Text.js';

function Section({
  section,
  hasMultipleSections,
  isFirst,
  actionRole,
  onActionAnyItem
}) {
  const handleAction = itemOnAction => {
    return () => {
      if (itemOnAction) {
        itemOnAction();
      }

      if (onActionAnyItem) {
        onActionAnyItem();
      }
    };
  };

  const actionMarkup = section.items.map(({
    content,
    helpText,
    onAction,
    ...item
  }, index) => {
    return /*#__PURE__*/React.createElement("li", {
      key: `${content}-${index}`,
      role: actionRole === 'menuitem' ? 'presentation' : undefined
    }, /*#__PURE__*/React.createElement(Item, Object.assign({
      content: content,
      helpText: helpText,
      role: actionRole,
      onAction: handleAction(onAction)
    }, item)));
  });
  let titleMarkup = null;

  if (section.title) {
    titleMarkup = typeof section.title === 'string' ? /*#__PURE__*/React.createElement(Box, {
      paddingBlockStart: "4",
      paddingInlineStart: "4",
      paddingBlockEnd: "2",
      paddingInlineEnd: "4"
    }, /*#__PURE__*/React.createElement(Text, {
      as: "p",
      variant: "headingXs"
    }, section.title)) : /*#__PURE__*/React.createElement(Box, {
      padding: "2"
    }, section.title);
  }

  let sectionRole;

  switch (actionRole) {
    case 'option':
      sectionRole = 'presentation';
      break;

    case 'menuitem':
      sectionRole = !hasMultipleSections ? 'menu' : 'presentation';
      break;

    default:
      sectionRole = undefined;
      break;
  }

  const sectionMarkup = /*#__PURE__*/React.createElement(React.Fragment, null, titleMarkup, /*#__PURE__*/React.createElement(Box, Object.assign({
    as: "ul",
    padding: "2"
  }, hasMultipleSections && {
    paddingBlockStart: '0'
  }, sectionRole && {
    role: sectionRole
  }, {
    tabIndex: !hasMultipleSections ? -1 : undefined
  }), actionMarkup));
  return hasMultipleSections ? /*#__PURE__*/React.createElement(Box, Object.assign({
    as: "li",
    role: "presentation",
    borderColor: "border-subdued"
  }, !isFirst && {
    borderBlockStartWidth: '1'
  }, !section.title && {
    paddingBlockStart: '2'
  }), sectionMarkup) : sectionMarkup;
}

export { Section };
