import { f as cesc, u as useRecordVisibilityChanges, j as jsxRuntimeExports } from "./doenetml-BPsLSRHD.js";
import React__default, { useRef, useEffect } from "react";
import { F as FontAwesomeIcon } from "./index.es-XE1CVwqn.js";
import { f as faCaretDown, a as faCaretRight } from "./index-BDlitCgu.js";
import { u as useDoenetRenderer } from "./useDoenetRenderer-BDC0Rur_.js";
import { a as addCommasForCompositeRanges } from "./composites-BvS-pDok.js";
import { c as calculateValidationState, u as useSubmitActionWithDelay, a as createCheckWorkComponent } from "./useSubmitActionWithDelay-bJj16Fl0.js";
const section = React__default.memo(function Section(props) {
  let { id, SVs, children, actions, callAction } = useDoenetRenderer(props);
  const LIST_ITEM_INDENT = "2em";
  const LIST_ITEM_SPACING = "0.3em";
  const BOX_PADDING = "6px";
  const EMPTY_HEADING_MIN_HEIGHT = "1.5em";
  const ref = useRef(null);
  const hasTitle = !!SVs.titleChildName || !!SVs.title && !SVs.isListItem;
  let heading = null;
  const getSectionNumberStyles = (hasHeading) => {
    if (hasHeading) {
      return `
                display: inline-block;
                width: calc(${LIST_ITEM_INDENT} - ${LIST_ITEM_SPACING});
                margin-left: calc(-1 * ${LIST_ITEM_INDENT});
                margin-right: ${LIST_ITEM_SPACING};
                text-align: right;
                flex-shrink: 0;
            `;
    } else {
      return `
                position: absolute;
                left: 0;
                width: calc(${LIST_ITEM_INDENT} - ${LIST_ITEM_SPACING});
                text-align: right;
            `;
    }
  };
  const getHeadingBoxStyle = (isCollapsible) => {
    const baseStyle = {
      padding: BOX_PADDING,
      backgroundColor: SVs.titleColor,
      borderTopLeftRadius: "var(--mainBorderRadius)",
      borderTopRightRadius: "var(--mainBorderRadius)",
      ...isCollapsible && {
        cursor: "pointer",
        borderBottom: SVs.open ? "var(--mainBorder)" : "none"
      },
      ...!isCollapsible && {
        borderBottom: "var(--mainBorder)"
      }
    };
    if (SVs.isListItem) {
      if (!heading) {
        return {
          ...baseStyle,
          position: "relative",
          paddingLeft: LIST_ITEM_INDENT
        };
      } else {
        return {
          ...baseStyle,
          display: "flex",
          alignItems: "baseline",
          paddingLeft: LIST_ITEM_INDENT
        };
      }
    }
    return baseStyle;
  };
  const renderContainer = (content2, style) => {
    const props2 = { id, style, ref };
    switch (SVs.containerTag) {
      case "aside":
        return /* @__PURE__ */ jsxRuntimeExports.jsx("aside", { ...props2, children: content2 });
      case "article":
        return /* @__PURE__ */ jsxRuntimeExports.jsx("article", { ...props2, children: content2 });
      case "div":
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ...props2, children: content2 });
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx("section", { ...props2, children: content2 });
    }
  };
  useEffect(() => {
    if (!SVs.isListItem) {
      return;
    }
    const styleId = `section-list-item-styles-${id}`;
    const existingStyle = document.getElementById(styleId);
    if (existingStyle) {
      existingStyle.remove();
    }
    const styleElement = document.createElement("style");
    styleElement.id = styleId;
    const cssRules = [];
    const escapedId = cesc(id);
    const escapedHeadingWrapperId = cesc(`${id}-heading-wrapper`);
    if (!SVs.collapsible && !SVs.boxed && hasTitle) {
      cssRules.push(`
                #${escapedHeadingWrapperId}::before {
                    content: "${SVs.sectionNumber}.";
                    display: inline-block;
                    width: calc(${LIST_ITEM_INDENT} - ${LIST_ITEM_SPACING});
                    margin-left: calc(-1 * ${LIST_ITEM_INDENT});
                    margin-right: ${LIST_ITEM_SPACING};
                    text-align: right;
                    flex-shrink: 0;
                }
            `);
    }
    if (!SVs.collapsible && !SVs.boxed && !hasTitle) {
      cssRules.push(`
                #${escapedId}::before {
                    content: "${SVs.sectionNumber}.";
                    display: inline-block;
                    width: calc(${LIST_ITEM_INDENT} - ${LIST_ITEM_SPACING});
                    margin-left: calc(-1 * ${LIST_ITEM_INDENT});
                    margin-right: ${LIST_ITEM_SPACING};
                    text-align: right;
                    vertical-align: baseline;
                }
            `);
    }
    if (SVs.collapsible) {
      const headingBoxClassName = `section-heading-${id}`;
      const escapedHeadingBoxClassName = cesc(headingBoxClassName);
      cssRules.push(`
                #${escapedId} .${escapedHeadingBoxClassName}::before {
                    content: "${SVs.sectionNumber}.";
                    text-align: right;
                    ${getSectionNumberStyles(hasTitle)}
                }
            `);
    }
    if (SVs.boxed && !SVs.collapsible) {
      const headingBoxClassName = `section-heading-${id}`;
      const escapedHeadingBoxClassName = cesc(headingBoxClassName);
      cssRules.push(`
                #${escapedId} .${escapedHeadingBoxClassName}::before {
                    content: "${SVs.sectionNumber}.";
                    text-align: right;
                    ${getSectionNumberStyles(hasTitle)}
                }
            `);
    }
    if (cssRules.length > 0) {
      styleElement.textContent = cssRules.join("\n");
      document.head.appendChild(styleElement);
    }
    return () => {
      const style = document.getElementById(styleId);
      if (style) {
        style.remove();
      }
    };
  }, [
    SVs.isListItem,
    SVs.sectionNumber,
    SVs.collapsible,
    SVs.boxed,
    hasTitle,
    id
  ]);
  useRecordVisibilityChanges(ref, callAction, actions);
  if (SVs.hidden) {
    return null;
  }
  const validationState = calculateValidationState(SVs);
  const { isPending, submitActionWithPending } = useSubmitActionWithDelay({
    actionKey: "submitAllAnswers",
    actions,
    callAction,
    validationState,
    justSubmitted: SVs.justSubmitted
  });
  let title;
  let removedChildInd = null;
  if (SVs.titleChildName) {
    for (let [ind, child] of children.entries()) {
      if (child?.props?.componentInstructions.componentIdx === SVs.titleChildName) {
        title = children[ind];
        children.splice(ind, 1);
        removedChildInd = ind;
        break;
      }
    }
  }
  if (title) {
    title = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      SVs.titlePrefix,
      title
    ] });
  } else if (!SVs.isListItem) {
    title = SVs.title;
  }
  let headingId = id + "_title";
  if (SVs.collapsible) {
    if (SVs.open) {
      title = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(FontAwesomeIcon, { icon: faCaretDown }),
        " ",
        title,
        " (click to close)"
      ] });
    } else {
      title = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(FontAwesomeIcon, { icon: faCaretRight }),
        " ",
        title,
        " (click to open)"
      ] });
    }
  }
  let headingStyle = {};
  if (SVs.collapsible || SVs.boxed) {
    headingStyle = {
      marginBlockStart: 0,
      marginBlockEnd: 0
    };
  }
  if (title) {
    switch (SVs.level) {
      case 0:
        heading = /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { id: headingId, style: headingStyle, children: title });
        break;
      case 1:
        heading = /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: headingId, style: headingStyle, children: title });
        break;
      case 2:
        heading = /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { id: headingId, style: headingStyle, children: title });
        break;
      case 3:
        heading = /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { id: headingId, style: headingStyle, children: title });
        break;
      case 4:
        heading = /* @__PURE__ */ jsxRuntimeExports.jsx("h5", { id: headingId, style: headingStyle, children: title });
        break;
      default:
        heading = /* @__PURE__ */ jsxRuntimeExports.jsx("h6", { id: headingId, style: headingStyle, children: title });
        break;
    }
  }
  let checkWorkComponent = createCheckWorkComponent(
    SVs,
    id,
    validationState,
    submitActionWithPending,
    true,
    isPending
  );
  if (checkWorkComponent) {
    checkWorkComponent = /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: checkWorkComponent });
  }
  if (SVs._compositeReplacementActiveRange) {
    children = addCommasForCompositeRanges({
      children,
      compositeReplacementActiveRange: SVs._compositeReplacementActiveRange,
      startInd: 0,
      endInd: children.length - 1,
      removedInd: removedChildInd
    });
  }
  let content = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    SVs.isListItem && !SVs.collapsible && !SVs.boxed && heading ? /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        id: `${id}-heading-wrapper`,
        style: {
          display: "flex",
          alignItems: "baseline",
          position: "relative"
        },
        children: heading
      }
    ) : heading,
    children,
    checkWorkComponent
  ] });
  if (SVs.collapsible) {
    let innerContent = null;
    if (SVs.open) {
      const innerContentStyle = {
        display: "block",
        padding: BOX_PADDING,
        ...SVs.isListItem && { paddingLeft: LIST_ITEM_INDENT }
      };
      innerContent = /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: innerContentStyle, children: [
        SVs.rendered ? children : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Initializing..." }),
        checkWorkComponent
      ] });
    }
    const headingBoxStyle = getHeadingBoxStyle(true);
    const headingBoxClassName = `section-heading-${id}`;
    content = /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        style: {
          border: "var(--mainBorder)",
          borderRadius: "var(--mainBorderRadius)",
          marginTop: "24px"
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: headingBoxClassName,
              style: headingBoxStyle,
              tabIndex: "0",
              onKeyPress: (e) => {
                if (e.key === "Enter") {
                  callAction({
                    action: SVs.open ? actions.closeSection : actions.revealSection
                  });
                }
              },
              onClick: () => callAction({
                action: SVs.open ? actions.closeSection : actions.revealSection
              }),
              children: heading || (SVs.isListItem ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  style: {
                    minHeight: EMPTY_HEADING_MIN_HEIGHT,
                    display: "inline-block"
                  },
                  children: " "
                }
              ) : null)
            }
          ),
          innerContent
        ]
      }
    );
  } else if (SVs.boxed) {
    const headingBoxStyle = getHeadingBoxStyle(false);
    const contentDivStyle = {
      display: "block",
      padding: BOX_PADDING,
      ...SVs.isListItem && { paddingLeft: LIST_ITEM_INDENT }
    };
    const headingBoxClassName = `section-heading-${id}`;
    content = /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        style: {
          border: "var(--mainBorder)",
          borderRadius: "var(--mainBorderRadius)",
          marginTop: "24px"
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: headingBoxClassName, style: headingBoxStyle, children: heading || (SVs.isListItem ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              style: {
                minHeight: EMPTY_HEADING_MIN_HEIGHT,
                display: "inline-block"
              },
              children: " "
            }
          ) : null) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: contentDivStyle, children: [
            children,
            checkWorkComponent
          ] })
        ]
      }
    );
  }
  if (SVs.isListItem && !SVs.collapsible && !SVs.boxed) {
    const containerStyle = {
      margin: "12px 0",
      position: "relative",
      marginLeft: LIST_ITEM_INDENT
    };
    return renderContainer(content, containerStyle);
  }
  return renderContainer(content, { margin: "12px 0" });
});
export {
  section as default
};
