import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useCallback, memo, useRef, useState, useMemo } from 'react';
import classnames from 'classnames';
import { useFormikContext } from 'formik';
import { isPresent, noop } from '@bigbinary/neeto-cist';
import FormikEditor from '@bigbinary/neeto-editor/FormikEditor';
import MenuHorizontal from '@bigbinary/neeto-icons/MenuHorizontal';
import Modal from '@bigbinary/neetoui/Modal';
import Typography from '@bigbinary/neetoui/Typography';
import Dropdown from '@bigbinary/neetoui/Dropdown';
import Textarea from '@bigbinary/neetoui/formik/Textarea';
import { isEmpty, mergeRight } from 'ramda';
import { useTranslation } from 'react-i18next';
import { n } from './inject-css-C2dztUxs.js';
import useHotkeys from '@bigbinary/neeto-hotkeys';
import ImageUploader from '@bigbinary/neeto-image-uploader-frontend/ImageUploader';
import Spinner from '@bigbinary/neetoui/Spinner';
import { jsx, jsxs } from 'react/jsx-runtime';
import { t } from 'i18next';
import Image from '@bigbinary/neeto-icons/Image';

var EDITOR_ADDONS = ["highlight", "emoji", "video-upload", "code-block", "block-quote", "image-upload", "image-upload-unsplash", "divider", "video-embed", "undo", "redo", "table", "callout"];
var DEFAULT_EDITOR_PROPS = {
  isMenuIndependent: true,
  addons: [],
  size: "medium"
};
var IMAGE_UPLOAD_CONFIG = {
  maxImageSize: 1,
  allowedImageTypes: {
    "image/jpg": [".jpg", ".jpeg"],
    "image/png": [".png"],
    "image/svg": [".svg"]
  }
};

var css = ".neeto-molecules-document__wrapper{height:100%}@media screen and (max-width:768px){.neeto-molecules-document__wrapper{width:100%}}.neeto-molecules-document__wrapper .neeto-molecules-document__container{margin:0 auto;max-width:48rem!important;width:100%}.neeto-molecules-document__wrapper .neeto-molecules-document-editor__menubar{position:sticky;top:0;width:100%;z-index:20}.neeto-molecules-document__wrapper .neeto-molecules-document__title{margin:1.5rem 0 0;width:100%}.neeto-molecules-document__wrapper .neeto-molecules-document__title .neeto-ui-input{padding:0!important}.neeto-molecules-document__wrapper .neeto-molecules-document__title .neeto-ui-input textarea{color:rgb(var(--neeto-ui-black));font-size:2.625rem;font-weight:700;line-height:3rem;max-height:none;resize:none}.neeto-molecules-document__wrapper .neeto-molecules-document__title .neeto-ui-input textarea::-moz-placeholder{color:rgb(var(--neeto-ui-gray-300))}.neeto-molecules-document__wrapper .neeto-molecules-document__title .neeto-ui-input textarea::placeholder{color:rgb(var(--neeto-ui-gray-300))}@media screen and (max-width:1024px){.neeto-molecules-document__wrapper .neeto-molecules-document__title .neeto-ui-input textarea{font-size:2rem;line-height:1.25}}.neeto-molecules-document__wrapper .neeto-molecules-editor-content__error{margin:.75rem auto}.neeto-molecules-document__wrapper .ProseMirror{flex-grow:1;height:auto;max-height:none;overflow-y:hidden}.neeto-molecules-document__wrapper .neeto-editor-fixed-menu{border:thin solid rgb(var(--neeto-ui-gray-200));border-inline-end:none;border-inline-start:none}@media screen and (max-width:768px){.neeto-molecules-document__wrapper .neeto-editor-fixed-menu button.neeto-editor-fixed-menu__item{padding:.375rem}}.neeto-molecules-document__wrapper .neeto-editor-fixed-menu__wrapper{margin:0 auto;max-width:46.875rem;padding-inline-end:0!important;padding-inline-start:0!important}.neeto-molecules-document__wrapper .neeto-editor-fixed-menu__wrapper button.neeto-editor-fixed-menu__item{flex-shrink:0}@media screen and (max-width:768px){.neeto-molecules-document__wrapper .neeto-editor-fixed-menu__wrapper{overflow-x:auto}}.neeto-molecules-document__wrapper .editor-content__wrapper{border:none!important;padding:.75rem 1.5rem 2rem!important;width:100%!important}.neeto-molecules-document__wrapper .editor-content-attachments{border:none;margin:.75rem auto 0;max-width:48rem!important;padding-inline-end:1rem;padding-inline-start:1rem}.neeto-molecules-document__wrapper .editor-content-attachments--no-attachments{display:none!important}.neeto-molecules-document__wrapper .neeto-editor-character-count{margin:0 auto;max-width:48rem!important;padding-inline-end:1rem;padding-inline-start:1rem}.neeto-molecules-document__wrapper .ne-attachments__wrapper{width:100%}.neeto-molecules-document__wrapper ins{background-color:#c1f4cb!important;text-decoration:none!important}.neeto-molecules-document__wrapper del{background-color:#faa!important}.neeto-molecules-document__wrapper .neeto-molecules-document__thumbnail-image{border-radius:5px;overflow:hidden;padding-bottom:56.25%;position:relative;width:100%}.neeto-molecules-document__wrapper .neeto-molecules-document__thumbnail-image img{height:100%;inset-inline-start:0;-o-object-fit:cover;object-fit:cover;position:absolute;top:0;width:100%}@media screen and (max-width:767px){.ne-media-uploader-modal{width:95vw!important}}";
n(css,{});

var useEditor = function useEditor(_ref) {
  var onContentChange = _ref.onContentChange,
    editorContentFieldName = _ref.editorContentFieldName,
    onAttachmentChange = _ref.onAttachmentChange,
    onTitleChange = _ref.onTitleChange,
    titleFieldName = _ref.titleFieldName,
    editorRef = _ref.editorRef,
    titleRef = _ref.titleRef;
  var _useFormikContext = useFormikContext(),
    setFieldValue = _useFormikContext.setFieldValue,
    errors = _useFormikContext.errors;
  var handleContentChange = useCallback(function (content) {
    setFieldValue(editorContentFieldName, content);
    onContentChange === null || onContentChange === void 0 || onContentChange(content);
  }, [editorContentFieldName, onContentChange, setFieldValue]);
  var handleAttachmentChange = useCallback(function (attachments) {
    setFieldValue("attachments", attachments);
    onAttachmentChange === null || onAttachmentChange === void 0 || onAttachmentChange(attachments);
  }, [onAttachmentChange, setFieldValue]);
  var handleTitleChange = function handleTitleChange(event) {
    var title = event.target.value;
    setFieldValue(titleFieldName, title);
    onTitleChange === null || onTitleChange === void 0 || onTitleChange(title);
  };
  var handleEditorBackspaceKeypress = function handleEditorBackspaceKeypress() {
    var _editorRef$current, _editor$state;
    var editor = (_editorRef$current = editorRef.current) === null || _editorRef$current === void 0 ? void 0 : _editorRef$current.editor;
    var selection = editor === null || editor === void 0 || (_editor$state = editor.state) === null || _editor$state === void 0 ? void 0 : _editor$state.selection;
    if (editor !== null && editor !== void 0 && editor.isFocused && isPresent(titleRef.current) && (selection === null || selection === void 0 ? void 0 : selection.anchor) === 1) {
      var title = titleRef.current.value;
      titleRef.current.focus();
      titleRef.current.setSelectionRange(title === null || title === void 0 ? void 0 : title.length, title === null || title === void 0 ? void 0 : title.length);
    }
  };
  var titleHotkeyRef = useHotkeys("return", function () {
    var _editorRef$current2, _editorRef$current3;
    (_editorRef$current2 = editorRef.current) === null || _editorRef$current2 === void 0 || (_editorRef$current2 = _editorRef$current2.editor) === null || _editorRef$current2 === void 0 || (_editorRef$current2 = _editorRef$current2.commands) === null || _editorRef$current2 === void 0 || _editorRef$current2.insertContentAt(0, "<p />");
    (_editorRef$current3 = editorRef.current) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.editor) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.commands) === null || _editorRef$current3 === void 0 || _editorRef$current3.focus("start");
  }, {
    mode: "scoped"
  });
  var editorHotkeyRef = useHotkeys("backspace", handleEditorBackspaceKeypress, {
    mode: "scoped"
  });
  return {
    handleContentChange: handleContentChange,
    handleAttachmentChange: handleAttachmentChange,
    handleTitleChange: handleTitleChange,
    editorHotkeyRef: editorHotkeyRef,
    titleHotkeyRef: titleHotkeyRef,
    errors: errors
  };
};

var MediaUploader = function MediaUploader(_ref) {
  var setIsThumbnailImageModalOpen = _ref.setIsThumbnailImageModalOpen;
  var _useFormikContext = useFormikContext(),
    thumbnailImageUrl = _useFormikContext.values.thumbnailImageUrl,
    setFieldValue = _useFormikContext.setFieldValue,
    initialValues = _useFormikContext.initialValues,
    submitForm = _useFormikContext.submitForm;
  var handleUpload = function handleUpload(file) {
    var url = file.url,
      signedId = file.signedId;
    setFieldValue("thumbnailImage", signedId);
    setFieldValue("thumbnailImageUrl", url);
    setTimeout(function () {
      setIsThumbnailImageModalOpen(false);
      submitForm();
    });
  };
  if (isEmpty(initialValues)) {
    return /*#__PURE__*/jsx(Spinner, {});
  }
  return /*#__PURE__*/jsx(ImageUploader, {
    className: "h-auto w-full",
    src: thumbnailImageUrl,
    uploadConfig: IMAGE_UPLOAD_CONFIG,
    onUploadComplete: handleUpload
  }, thumbnailImageUrl);
};

var getThumbnailAddon = function getThumbnailAddon(command) {
  return {
    label: t("neetoMolecules.documentEditor.thumbnailImage"),
    optionName: "thumbnail-image",
    command: command,
    icon: Image,
    isEnabled: true,
    "data-testid": "thumbnail-image-addon"
  };
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var Editor = function Editor(_ref) {
  var attachments = _ref.attachments,
    onContentChange = _ref.onContentChange,
    onAttachmentChange = _ref.onAttachmentChange,
    onTitleChange = _ref.onTitleChange,
    _ref$getTitleRef = _ref.getTitleRef,
    getTitleRef = _ref$getTitleRef === void 0 ? noop : _ref$getTitleRef,
    _ref$getEditorRef = _ref.getEditorRef,
    getEditorRef = _ref$getEditorRef === void 0 ? noop : _ref$getEditorRef,
    menuClassName = _ref.menuClassName,
    _ref$editorContentFie = _ref.editorContentFieldName,
    editorContentFieldName = _ref$editorContentFie === void 0 ? "htmlContent" : _ref$editorContentFie,
    _ref$titleFieldName = _ref.titleFieldName,
    titleFieldName = _ref$titleFieldName === void 0 ? "title" : _ref$titleFieldName,
    _ref$editorProps = _ref.editorProps,
    customEditorProps = _ref$editorProps === void 0 ? {} : _ref$editorProps,
    _ref$titleProps = _ref.titleProps,
    titleProps = _ref$titleProps === void 0 ? {} : _ref$titleProps,
    _ref$hasThumbnailImag = _ref.hasThumbnailImage,
    hasThumbnailImage = _ref$hasThumbnailImag === void 0 ? false : _ref$hasThumbnailImag,
    children = _ref.children;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = useFormikContext(),
    values = _useFormikContext.values,
    setFieldValue = _useFormikContext.setFieldValue,
    submitForm = _useFormikContext.submitForm;
  var thumbnailImageUrl = values.thumbnailImageUrl;
  var Menu = Dropdown.Menu,
    MenuItem = Dropdown.MenuItem;
  var titleRef = useRef();
  var editorRef = useRef();
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isThumbnailImageModalOpen = _useState2[0],
    setIsThumbnailImageModalOpen = _useState2[1];
  var editorProps = useMemo(function () {
    var baseProps = mergeRight(DEFAULT_EDITOR_PROPS, customEditorProps);
    if (!hasThumbnailImage) return baseProps;
    var thumbnailAddon = getThumbnailAddon(function () {
      return setIsThumbnailImageModalOpen(true);
    });
    return mergeRight(baseProps, {
      addonCommands: [thumbnailAddon]
    });
  }, [customEditorProps, hasThumbnailImage]);
  var _useEditor = useEditor({
      onContentChange: onContentChange,
      editorContentFieldName: editorContentFieldName,
      onAttachmentChange: onAttachmentChange,
      onTitleChange: onTitleChange,
      titleFieldName: titleFieldName,
      editorRef: editorRef,
      titleRef: titleRef
    }),
    handleContentChange = _useEditor.handleContentChange,
    handleAttachmentChange = _useEditor.handleAttachmentChange,
    handleTitleChange = _useEditor.handleTitleChange,
    editorHotkeyRef = _useEditor.editorHotkeyRef,
    titleHotkeyRef = _useEditor.titleHotkeyRef,
    errors = _useEditor.errors;
  var setTitleRef = function setTitleRef(node) {
    titleHotkeyRef.current = node;
    getTitleRef(node);
    titleRef.current = node;
  };
  var setEditorRef = useCallback(function (node) {
    editorRef.current = node;
    getEditorRef(node);
  }, []);
  var addons = useMemo(function () {
    return EDITOR_ADDONS.concat(editorProps.addons || []);
  }, [editorProps.addons]);
  var handleTab = function handleTab() {
    var _editorRef$current, _editorRef$current2;
    var isListActive = ((_editorRef$current = editorRef.current) === null || _editorRef$current === void 0 || (_editorRef$current = _editorRef$current.editor) === null || _editorRef$current === void 0 ? void 0 : _editorRef$current.isActive("orderedList")) || ((_editorRef$current2 = editorRef.current) === null || _editorRef$current2 === void 0 || (_editorRef$current2 = _editorRef$current2.editor) === null || _editorRef$current2 === void 0 ? void 0 : _editorRef$current2.isActive("bulletList"));
    if (isListActive) {
      var _editorRef$current3;
      (_editorRef$current3 = editorRef.current) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.editor) === null || _editorRef$current3 === void 0 || (_editorRef$current3 = _editorRef$current3.commands) === null || _editorRef$current3 === void 0 || _editorRef$current3.sinkListItem("listItem");
      return true;
    }
    return true;
  };
  var handleDeleteThumbnail = function handleDeleteThumbnail() {
    setFieldValue("thumbnailImage", "");
    setFieldValue("thumbnailImageUrl", "");
    setTimeout(submitForm);
  };
  return /*#__PURE__*/jsxs("div", {
    className: "neeto-molecules-document__wrapper",
    "data-testid": "document-editor-container",
    ref: editorHotkeyRef,
    children: [/*#__PURE__*/jsxs(FormikEditor, _objectSpread(_objectSpread({
      attachmentsClassName: "editor-content-attachments w-full flex-shrink-0",
      className: "h-full w-full",
      contentClassName: "editor-content__wrapper neeto-molecules-document__container",
      "data-testid": "neeto-molecules-document-content-text-area",
      error: undefined,
      errorWrapperClassName: "w-full min-h-full flex flex-col items-center",
      hideSlashCommands: false,
      name: editorContentFieldName,
      ref: setEditorRef,
      menuClassName: classnames("neeto-molecules-document-editor__menubar", menuClassName)
    }, _objectSpread(_objectSpread({
      attachments: attachments
    }, editorProps), {}, {
      addons: addons
    })), {}, {
      contentWrapperClassName: "w-full flex flex-col flex-grow",
      keyboardShortcuts: _objectSpread({
        Tab: handleTab
      }, editorProps.keyboardShortcuts),
      onChange: handleContentChange,
      onChangeAttachments: handleAttachmentChange,
      children: [children, /*#__PURE__*/jsxs("div", {
        className: "neeto-molecules-document__container px-6",
        children: [/*#__PURE__*/jsx(Textarea, _objectSpread({
          nakedTextarea: true,
          className: "neeto-molecules-document__title",
          "data-testid": "neeto-molecules-document-title-text-field",
          name: titleFieldName,
          ref: setTitleRef,
          rows: 1,
          placeholder: titleProps.placeholder || t("neetoMolecules.documentEditor.title"),
          onChange: handleTitleChange,
          onKeyDown: function onKeyDown(e) {
            return e.key === "Enter" && !e.shiftKey && e.preventDefault();
          }
        }, titleProps)), thumbnailImageUrl && /*#__PURE__*/jsxs("div", {
          className: "group relative mt-4",
          children: [/*#__PURE__*/jsx("div", {
            className: "neeto-molecules-document__thumbnail-image",
            children: /*#__PURE__*/jsx("img", {
              alt: "Cover",
              src: thumbnailImageUrl
            })
          }), /*#__PURE__*/jsx("div", {
            className: "neeto-ui-rounded-full absolute end-2 top-2",
            children: /*#__PURE__*/jsx(Dropdown, {
              strategy: "fixed",
              buttonProps: {
                style: "secondary",
                size: "small",
                icon: MenuHorizontal
              },
              children: /*#__PURE__*/jsx(Menu, {
                children: /*#__PURE__*/jsx(MenuItem.Button, {
                  onClick: handleDeleteThumbnail,
                  children: t("neetoMolecules.documentEditor.delete")
                })
              })
            })
          })]
        }), errors[editorContentFieldName] && /*#__PURE__*/jsx(Typography, {
          className: "neeto-ui-input__error neeto-molecules-editor-content__error",
          "data-testid": "articles-content-input-error",
          style: "body3",
          children: errors[editorContentFieldName]
        })]
      })]
    })), /*#__PURE__*/jsxs(Modal, {
      className: "media-uploader-modal p-5 pt-0",
      "data-testid": "thumbnail-image-modal",
      isOpen: isThumbnailImageModalOpen,
      onClose: function onClose() {
        setIsThumbnailImageModalOpen(false);
      },
      children: [/*#__PURE__*/jsx(Modal.Header, {
        className: "ms-0 ps-0",
        children: /*#__PURE__*/jsx(Typography, {
          style: "h2",
          children: t("neetoMolecules.documentEditor.uploadThumbnailImage")
        })
      }), /*#__PURE__*/jsx(MediaUploader, {
        setIsThumbnailImageModalOpen: setIsThumbnailImageModalOpen
      })]
    })]
  });
};
Editor.displayName = "DocumentEditor";
var index = /*#__PURE__*/memo(Editor);

export { index as default };
//# sourceMappingURL=DocumentEditor.js.map
