import React from "react";
import { RicosContext } from "./../ricos-context/index.js";
import { getListTag, getMarker } from "./markers.js";
import {
  alphabeticalIndexEntryListStyle,
  alphabeticalIndexNavListStyle,
  alphabeticalIndexSectionStyle,
  listDepthStyle,
  markerStyle,
  placeholderStyle,
  resolveViewStyles
} from "./resolve-styles.js";
import tocStyles from "./toc-view-scss.js";
import { buildAlphabeticalGroups, buildTree } from "./tree-builder.js";
const getScrollBehavior = () => {
  if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
    return "smooth";
  }
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth";
};
const renderItems = ({
  items,
  data,
  depth,
  parentIndices,
  onNavigate,
  onSelect,
  getNextVisibleIndex,
  resolvedLinkStyle,
  resolvedListItemStyle
}) => {
  const ListTag = getListTag(data.listStyle);
  return /* @__PURE__ */ React.createElement(ListTag, { role: "list", style: listDepthStyle(depth) }, items.map((item, index) => {
    const indices = [...parentIndices, index + 1];
    const marker = getMarker({
      data,
      depth,
      indices,
      visibleIndex: getNextVisibleIndex()
    });
    return /* @__PURE__ */ React.createElement("li", { key: item.nodeId, style: resolvedListItemStyle }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: `#${item.anchor}`,
        className: tocStyles.tocLink,
        onClick: (event) => {
          event.preventDefault();
          if (onSelect?.()) {
            return;
          }
          onNavigate?.(item);
        },
        style: {
          ...resolvedLinkStyle,
          marginLeft: 0
        }
      },
      marker ? /* @__PURE__ */ React.createElement("span", { "aria-hidden": "true", style: markerStyle }, marker) : null,
      /* @__PURE__ */ React.createElement("span", null, item.text)
    ), data.indentation !== "FLAT" && item.children.length > 0 ? renderItems({
      items: item.children,
      data,
      depth: depth + 1,
      parentIndices: indices,
      onNavigate,
      onSelect,
      getNextVisibleIndex,
      resolvedLinkStyle,
      resolvedListItemStyle
    }) : null);
  }));
};
const renderAlphabeticalIndex = ({
  data,
  headings,
  tocId,
  onNavigate,
  onSelect,
  resolvedStyles,
  t
}) => {
  const groups = buildAlphabeticalGroups(headings);
  const tocAnchorPrefix = tocId || "toc";
  const isCompact = data.listStyle === "ALPHABETICAL_INDEX_COMPACT";
  return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("ul", { role: "list", style: alphabeticalIndexNavListStyle }, groups.map((group) => {
    const sectionAnchor = `${tocAnchorPrefix}-${group.letter.toLowerCase()}`;
    const firstHeading = group.items[0];
    if (!firstHeading) {
      return null;
    }
    return /* @__PURE__ */ React.createElement("li", { key: group.letter }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: isCompact ? `#${firstHeading.anchor}` : `#${sectionAnchor}`,
        "aria-label": t("TocPlugin_AlphabeticalIndex_JumpTo", { letter: group.letter }),
        className: tocStyles.tocLink,
        onClick: (event) => {
          event.preventDefault();
          if (onSelect?.()) {
            return;
          }
          if (isCompact) {
            onNavigate?.(firstHeading);
            return;
          }
          if (typeof document === "undefined") {
            return;
          }
          const target = document.getElementById(sectionAnchor);
          target?.scrollIntoView?.({
            behavior: getScrollBehavior(),
            block: "start"
          });
          target?.focus?.({ preventScroll: true });
        },
        style: resolvedStyles.alphabeticalIndexGroupLinkStyle
      },
      group.letter
    ));
  })), isCompact ? null : groups.map((group) => {
    const sectionAnchor = `${tocAnchorPrefix}-${group.letter.toLowerCase()}`;
    return /* @__PURE__ */ React.createElement("div", { key: group.letter, style: alphabeticalIndexSectionStyle }, /* @__PURE__ */ React.createElement(
      "div",
      {
        id: sectionAnchor,
        tabIndex: -1,
        role: "heading",
        "aria-level": 2,
        style: resolvedStyles.alphabeticalIndexLetterStyle
      },
      group.letter
    ), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", style: resolvedStyles.alphabeticalIndexDividerStyle }), /* @__PURE__ */ React.createElement("ul", { role: "list", style: alphabeticalIndexEntryListStyle }, group.items.map((item) => /* @__PURE__ */ React.createElement("li", { key: item.nodeId, style: resolvedStyles.alphabeticalIndexEntryStyle }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: `#${item.anchor}`,
        className: tocStyles.tocLink,
        onClick: (event) => {
          event.preventDefault();
          if (onSelect?.()) {
            return;
          }
          onNavigate?.(item);
        },
        style: resolvedStyles.alphabeticalIndexEntryLinkStyle
      },
      item.text
    )))));
  }));
};
const TocView = ({ data, headings, mode, onNavigate, onSelect, tocId }) => {
  const { t, theme } = React.useContext(RicosContext);
  const resolvedStyles = resolveViewStyles({ data, theme });
  if (headings.length === 0) {
    return mode === "editor" ? /* @__PURE__ */ React.createElement("div", { style: resolvedStyles.containerStyle }, /* @__PURE__ */ React.createElement("div", { style: placeholderStyle }, t("TocPlugin_Placeholder"))) : null;
  }
  const items = data.indentation !== "FLAT" ? buildTree(headings) : headings.map((heading) => ({
    ...heading,
    children: []
  }));
  let visibleIndex = 0;
  const getNextVisibleIndex = () => {
    visibleIndex += 1;
    return visibleIndex;
  };
  return /* @__PURE__ */ React.createElement(
    "nav",
    {
      contentEditable: false,
      style: resolvedStyles.containerStyle,
      "aria-label": t("TocPlugin_AriaLabel")
    },
    data.listStyle === "ALPHABETICAL_INDEX" || data.listStyle === "ALPHABETICAL_INDEX_COMPACT" ? renderAlphabeticalIndex({
      data,
      headings,
      tocId,
      onNavigate,
      onSelect,
      resolvedStyles,
      t
    }) : renderItems({
      items,
      data,
      depth: 0,
      parentIndices: [],
      onNavigate,
      onSelect,
      getNextVisibleIndex,
      resolvedLinkStyle: resolvedStyles.linkStyle,
      resolvedListItemStyle: resolvedStyles.listItemStyle
    })
  );
};
export {
  TocView,
  getScrollBehavior
};
//# sourceMappingURL=toc-view.js.map
