import { jsx } from "react/jsx-runtime";
import { tcx } from "@choiceform/design-system";
import React__default, { memo } from "react";
import { useCodeBlock } from "./hooks/use-code-block.js";
import { useLineCount } from "./hooks/use-line-count.js";
import { useScrollDetection } from "./hooks/use-scroll-detection.js";
import { useStickToBottom } from "../../../_vendor/use-stick-to-bottom/dist-useStickToBottom.js";
const CodeBlock = memo(function CodeBlock2(props) {
  const {
    children,
    className,
    filename,
    language = "code",
    lineThreshold = 20,
    expandable = true,
    defaultExpanded = true,
    defaultCodeExpanded = false,
    onExpandChange,
    onCodeExpandChange
  } = props;
  const { scrollRef, contentRef, scrollToBottom } = useStickToBottom({
    resize: "smooth",
    initial: "smooth"
  });
  const codeContentRef = React__default.useRef("");
  const {
    isExpanded,
    codeExpanded,
    copied,
    handleExpand,
    handleCodeExpand,
    handleCopy: originalHandleCopy
  } = useCodeBlock({
    defaultExpanded,
    defaultCodeExpanded,
    onExpandChange,
    onCodeExpandChange,
    scrollToBottom
  });
  const handleCopy = React__default.useCallback(
    (code) => {
      const codeToUse = code || codeContentRef.current;
      if (codeToUse) {
        originalHandleCopy(codeToUse);
      }
    },
    [originalHandleCopy]
  );
  React__default.useEffect(() => {
    React__default.Children.forEach(children, (child) => {
      if (React__default.isValidElement(child)) {
        if (child.props?.code && typeof child.props.code === "string") {
          codeContentRef.current = child.props.code;
        }
      }
    });
  }, [children]);
  const lineCount = useLineCount(children);
  const needsScroll = useScrollDetection({
    scrollRef,
    contentRef,
    isExpanded,
    codeExpanded,
    children
  });
  const contextValue = {
    language,
    filename,
    lineCount,
    isExpanded,
    codeExpanded,
    copied,
    needsScroll,
    expandable,
    lineThreshold,
    handleExpand,
    handleCodeExpand,
    handleCopy,
    scrollRef,
    contentRef
  };
  const injectedChildren = React__default.Children.map(children, (child) => {
    if (React__default.isValidElement(child)) {
      return React__default.cloneElement(
        child,
        {
          codeBlock: contextValue
        }
      );
    }
    return child;
  });
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: tcx(
        "bg-default-background group relative overflow-hidden rounded-lg border",
        className
      ),
      children: injectedChildren
    }
  );
});
export {
  CodeBlock
};
//# sourceMappingURL=code-block.js.map
