import React, { useMemo, useContext, useEffect } from 'react';
import classnames from 'classnames';
import isEqual from 'lodash-es/isEqual';
import { withHistory } from 'slate-history';
import { resetNodes } from '../chat';
import TextEditorContext from './text-editor-context';
import TextEditorContent, { Element, Leaf } from './text-editor-content';
import withLinks from './hooks/with-links';
import TextEditorLoader from './text-editor-loader';
import { jsx as _jsx } from "react/jsx-runtime";
function EditedTextComponent({
  value,
  placeholder,
  isScrollable = true,
  elementRender = Element,
  leafRender = Leaf,
  testId,
  ariaLabel
}) {
  const {
    slate,
    slateReact
  } = useContext(TextEditorContext);
  const {
    createEditor
  } = slate;
  const {
    withReact,
    Slate
  } = slateReact;
  const editor = useMemo(() => withLinks(withHistory(withReact(createEditor()))), []);
  useEffect(() => {
    if (value && !isEqual(editor.children, value)) {
      // Update the cached value inside the editor
      resetNodes(editor, value);
    }
  }, [value, editor]);
  const ariaAttrs = useMemo(() => {
    return {
      'aria-label': ariaLabel
    };
  }, [ariaLabel]);
  return (
    /*#__PURE__*/
    // Slate throws an error when no onChange is given, providing a noop func to avoid issues
    _jsx(Slate, {
      editor: editor,
      initialValue: value,
      onChange: () => undefined,
      children: /*#__PURE__*/_jsx(TextEditorContent, {
        placeholder: placeholder,
        isScrollable: isScrollable,
        elementRender: elementRender,
        leafRender: leafRender,
        readOnly: true,
        testId: testId,
        ariaAttrs: ariaAttrs
      })
    })
  );
}
export default function EditedText({
  value,
  placeholder,
  className = '',
  isScrollable = true,
  elementRender = Element,
  leafRender = Leaf,
  ariaLabel,
  testId
}) {
  return /*#__PURE__*/_jsx("div", {
    className: classnames('edited-text', className),
    children: /*#__PURE__*/_jsx(TextEditorLoader, {
      children: /*#__PURE__*/_jsx(EditedTextComponent, {
        isScrollable: isScrollable,
        elementRender: elementRender,
        leafRender: leafRender,
        value: value,
        placeholder: placeholder,
        testId: testId,
        ariaLabel: ariaLabel
      })
    })
  });
}