"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client";




var _chunkGKY5DAIHjs = require('./chunk-GKY5DAIH.js');
require('./chunk-T5YYOT4Z.js');





var _chunkZNGEVB5Mjs = require('./chunk-ZNGEVB5M.js');
require('./chunk-LXKSUWAV.js');
require('./chunk-IBS6NI7D.js');
require('./chunk-FM6WRAN5.js');
require('./chunk-3EPNHTMH.js');


var _chunk7QVYU63Ejs = require('./chunk-7QVYU63E.js');

// src/components/editors/BlockNoteEditor.tsx
var _core = require('@blocknote/core');
var _react = require('@blocknote/react');
var _shadcn = require('@blocknote/shadcn');
require('@blocknote/shadcn/style.css');
var _lucidereact = require('lucide-react');
var _nextintl = require('next-intl');
var _react3 = require('react');

// src/components/editors/BlockNoteEditorFormattingToolbar.tsx










var _jsxruntime = require('react/jsx-runtime');
function BlockNoteEditorFormattingToolbar() {
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, 
    _react.FormattingToolbarController,
    {
      formattingToolbar: () => /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _react.FormattingToolbar, { children: [
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.BlockTypeSelect, {}, "blockTypeSelect"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.FileCaptionButton, {}, "fileCaptionButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.FileReplaceButton, {}, "replaceFileButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.BasicTextStyleButton, { basicTextStyle: "bold" }, "boldStyleButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.BasicTextStyleButton, { basicTextStyle: "italic" }, "italicStyleButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.BasicTextStyleButton, { basicTextStyle: "underline" }, "underlineStyleButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.BasicTextStyleButton, { basicTextStyle: "strike" }, "strikeStyleButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.TextAlignButton, { textAlignment: "left" }, "textAlignLeftButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.TextAlignButton, { textAlignment: "center" }, "textAlignCenterButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.TextAlignButton, { textAlignment: "right" }, "textAlignRightButton"),
        /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.CreateLinkButton, {}, "createLinkButton")
      ] })
    }
  );
}
_chunk7QVYU63Ejs.__name.call(void 0, BlockNoteEditorFormattingToolbar, "BlockNoteEditorFormattingToolbar");

// src/components/editors/BlockNoteEditor.tsx

var createDiffActionsInlineContentSpec = /* @__PURE__ */ _chunk7QVYU63Ejs.__name.call(void 0, (handleAcceptChange, handleRejectChange) => {
  return _react.createReactInlineContentSpec.call(void 0, 
    {
      type: "diffActions",
      propSchema: {
        diffIds: {
          default: ""
        }
      },
      content: "none"
    },
    {
      render: /* @__PURE__ */ _chunk7QVYU63Ejs.__name.call(void 0, (props) => {
        const diffIds = props.inlineContent.props.diffIds;
        return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "span", { className: "diff-actions-container mx-2 inline-flex items-center gap-1 align-middle", children: [
          /* @__PURE__ */ _jsxruntime.jsx.call(void 0, 
            _chunkGKY5DAIHjs.Button,
            {
              title: "Accept change",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                diffIds.split(",").forEach((id) => handleAcceptChange(id.trim()));
              },
              children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _lucidereact.CheckIcon, { className: "h-3 w-3 text-green-600" })
            }
          ),
          /* @__PURE__ */ _jsxruntime.jsx.call(void 0, 
            _chunkGKY5DAIHjs.Button,
            {
              title: "Reject change",
              className: "mx-2 p-0",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                diffIds.split(",").forEach((id) => handleRejectChange(id.trim()));
              },
              children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _lucidereact.XIcon, { className: "h-3 w-3 text-red-600" })
            }
          )
        ] });
      }, "render")
    }
  );
}, "createDiffActionsInlineContentSpec");
function BlockNoteEditor({
  id,
  type,
  initialContent,
  onChange,
  size,
  className,
  markdownContent,
  diffContent,
  placeholder,
  bordered
}) {
  const t = _nextintl.useTranslations.call(void 0, );
  const { company } = _chunkGKY5DAIHjs.useCurrentUserContext.call(void 0, );
  const [acceptedChanges, setAcceptedChanges] = _react3.useState.call(void 0, /* @__PURE__ */ new Set());
  const [rejectedChanges, setRejectedChanges] = _react3.useState.call(void 0, /* @__PURE__ */ new Set());
  const editorRef = _react3.useRef.call(void 0, null);
  const handleAcceptChange = _react3.useCallback.call(void 0, (diffId) => {
    setAcceptedChanges((prev) => /* @__PURE__ */ new Set([...prev, diffId]));
    setRejectedChanges((prev) => {
      const newSet = new Set(prev);
      newSet.delete(diffId);
      return newSet;
    });
  }, []);
  const handleRejectChange = _react3.useCallback.call(void 0, (diffId) => {
    setRejectedChanges((prev) => /* @__PURE__ */ new Set([...prev, diffId]));
    setAcceptedChanges((prev) => {
      const newSet = new Set(prev);
      newSet.delete(diffId);
      return newSet;
    });
  }, []);
  const DiffActionsInlineContent = _react3.useMemo.call(void 0, 
    () => createDiffActionsInlineContentSpec(handleAcceptChange, handleRejectChange),
    [handleAcceptChange, handleRejectChange]
  );
  const schema = _react3.useMemo.call(void 0, 
    () => _core.BlockNoteSchema.create({
      inlineContentSpecs: {
        ..._core.defaultInlineContentSpecs,
        diffActions: DiffActionsInlineContent
      }
    }),
    [DiffActionsInlineContent]
  );
  const uploadImage = _react3.useCallback.call(void 0, 
    async (file) => {
      if (!company) {
        _chunkGKY5DAIHjs.errorToast.call(void 0, {
          title: t(`common.errors.upload`),
          error: t(`common.errors.upload_description`)
        });
        throw new Error(t(`common.errors.upload`));
      }
      const fileType = file.type;
      const key = `companies/${company.id}/${type}/${id}/${file.name}`;
      const s3 = await _chunkZNGEVB5Mjs.S3Service.getPreSignedUrl({
        key,
        contentType: fileType,
        isPublic: true
      });
      await fetch(s3.url, {
        method: "PUT",
        headers: s3.headers,
        body: file
      });
      const signedImage = await _chunkZNGEVB5Mjs.S3Service.getSignedUrl({
        key,
        isPublic: true
      });
      return signedImage.url;
    },
    [company, id, t]
  );
  const removeTrailingEmptyBlocks = _react3.useCallback.call(void 0, 
    (blocks) => {
      if (!blocks || blocks.length === 0) return blocks;
      if (onChange !== void 0) return blocks;
      const result = [...blocks];
      while (result.length > 1) {
        const lastBlock = result[result.length - 1];
        const isEmptyParagraph = lastBlock.type === "paragraph" && (!lastBlock.content || lastBlock.content.length === 0 || Array.isArray(lastBlock.content) && lastBlock.content.every((c) => !c.text || c.text.trim() === ""));
        if (isEmptyParagraph) {
          result.pop();
        } else {
          break;
        }
      }
      return result;
    },
    [onChange]
  );
  const processedContent = _react3.useMemo.call(void 0, () => {
    if (diffContent && initialContent) {
      try {
        const diffResult = _chunkZNGEVB5Mjs.BlockNoteDiffUtil.diff(initialContent, diffContent);
        const renderedDiff = _chunkZNGEVB5Mjs.BlockNoteWordDiffRendererUtil.renderWordDiffs(
          diffResult.blocks,
          handleAcceptChange,
          handleRejectChange,
          acceptedChanges,
          rejectedChanges
        );
        return removeTrailingEmptyBlocks(renderedDiff);
      } catch (_error) {
        return initialContent && Array.isArray(initialContent) && initialContent.length > 0 ? removeTrailingEmptyBlocks(initialContent) : [];
      }
    }
    if (!initialContent) {
      return [];
    }
    if (!Array.isArray(initialContent)) {
      return [];
    }
    return initialContent.length > 0 ? removeTrailingEmptyBlocks(initialContent) : [];
  }, [
    initialContent,
    diffContent,
    handleAcceptChange,
    handleRejectChange,
    acceptedChanges,
    rejectedChanges,
    removeTrailingEmptyBlocks
  ]);
  const validatedInitialContent = _react3.useMemo.call(void 0, () => {
    if (processedContent && Array.isArray(processedContent) && processedContent.length > 0) {
      const validatedContent = processedContent.filter((block) => {
        if (!block || typeof block !== "object") return false;
        if (!block.type) return false;
        return true;
      });
      return validatedContent.length > 0 ? validatedContent : void 0;
    }
    return void 0;
  }, [processedContent]);
  const editor = _react.useCreateBlockNote.call(void 0, 
    _react3.useMemo.call(void 0, 
      () => ({
        placeholders: {
          emptyDocument: placeholder || t(`common.blocknote.placeholder`)
        },
        schema,
        initialContent: validatedInitialContent,
        uploadFile: uploadImage
      }),
      [placeholder, t, schema, validatedInitialContent, uploadImage]
    )
  );
  const handleChange = _react3.useCallback.call(void 0, async () => {
    if (!onChange) return;
    const newBlocks = editor.document;
    const markdownFromBlocks = (await editor.blocksToMarkdownLossy(editor.document)).trim();
    function hasUnresolvedDiffsRecursive(block) {
      if (!block || typeof block !== "object") return false;
      let diffId = void 0;
      if (block.props && block.props.diffId) diffId = block.props.diffId;
      if (!diffId && block.attrs && block.attrs.diffId) diffId = block.attrs.diffId;
      if (diffId && !acceptedChanges.has(diffId) && !rejectedChanges.has(diffId)) {
        return true;
      }
      if (block.content) {
        const contentArr = Array.isArray(block.content) ? block.content : [block.content];
        for (const inline of contentArr) {
          if (inline && typeof inline === "object") {
            if (inline.type === "diffActions" && inline.props && inline.props.diffIds) {
              const ids = typeof inline.props.diffIds === "string" ? inline.props.diffIds.split(",") : inline.props.diffIds;
              for (const id2 of ids) {
                const trimmed = (id2 || "").toString().trim();
                if (trimmed && !acceptedChanges.has(trimmed) && !rejectedChanges.has(trimmed)) {
                  return true;
                }
              }
            }
            if (inline.props && inline.props.diffId) {
              const diffIdInline = inline.props.diffId;
              if (diffIdInline && !acceptedChanges.has(diffIdInline) && !rejectedChanges.has(diffIdInline)) {
                return true;
              }
            }
            if (inline.children && Array.isArray(inline.children)) {
              for (const child of inline.children) {
                if (hasUnresolvedDiffsRecursive(child)) return true;
              }
            }
          }
        }
      }
      if (Array.isArray(block.children)) {
        for (const child of block.children) {
          if (hasUnresolvedDiffsRecursive(child)) return true;
        }
      }
      return false;
    }
    _chunk7QVYU63Ejs.__name.call(void 0, hasUnresolvedDiffsRecursive, "hasUnresolvedDiffsRecursive");
    let hasUnresolvedDiff = false;
    if (Array.isArray(newBlocks)) {
      hasUnresolvedDiff = newBlocks.some((block) => hasUnresolvedDiffsRecursive(block));
    }
    onChange(newBlocks, !markdownFromBlocks.length, hasUnresolvedDiff);
  }, [editor, onChange, id, acceptedChanges, rejectedChanges]);
  const areBlocksEqual = /* @__PURE__ */ _chunk7QVYU63Ejs.__name.call(void 0, (a, b) => {
    return JSON.stringify(a) === JSON.stringify(b);
  }, "areBlocksEqual");
  const hasInitializedFromMarkdown = _react3.useRef.call(void 0, null);
  _react3.useEffect.call(void 0, () => {
    const updateContent = /* @__PURE__ */ _chunk7QVYU63Ejs.__name.call(void 0, async (markdown) => {
      const blocks = await editor.tryParseMarkdownToBlocks(markdown);
      if (!areBlocksEqual(blocks, editor.document)) {
        editor.replaceBlocks(editor.document, blocks);
      }
    }, "updateContent");
    if (markdownContent && hasInitializedFromMarkdown.current !== markdownContent) {
      hasInitializedFromMarkdown.current = markdownContent;
      updateContent(markdownContent).then(() => handleChange());
    }
  }, [markdownContent, editor]);
  const previousContentHashRef = _react3.useRef.call(void 0, null);
  _react3.useEffect.call(void 0, () => {
    if (!processedContent || !editor) return;
    const hash = JSON.stringify(processedContent);
    if (previousContentHashRef.current === hash) return;
    const currentHash = JSON.stringify(editor.document);
    if (currentHash === hash) {
      previousContentHashRef.current = hash;
      return;
    }
    editor.replaceBlocks(editor.document, processedContent);
    previousContentHashRef.current = hash;
  }, [processedContent, editor]);
  const _handleAudioReceived = _react3.useCallback.call(void 0, 
    (message) => {
      try {
        const editorElement = _optionalChain([editorRef, 'access', _ => _.current, 'optionalAccess', _2 => _2.querySelector, 'call', _3 => _3('[contenteditable="true"]')]);
        if (editorElement && document.activeElement !== editorElement) {
          editorElement.focus();
        }
        editor.insertInlineContent(message);
      } catch (error) {
        console.error("Error inserting transcribed text:", error);
        try {
          const blocks = editor.document;
          if (blocks.length > 0) {
            const lastBlock = blocks[blocks.length - 1];
            editor.setTextCursorPosition(lastBlock.id, "end");
            editor.insertInlineContent(message);
          }
        } catch (fallbackError) {
          console.error("Fallback insertion also failed:", fallbackError);
        }
      }
    },
    [editor]
  );
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { ref: editorRef, className: _chunkZNGEVB5Mjs.cn.call(void 0, bordered ? "rounded-md border" : "", "w-full"), children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, 
    _shadcn.BlockNoteView,
    {
      editor,
      onChange: handleChange,
      editable: onChange !== void 0,
      formattingToolbar: false,
      theme: "light",
      className: _chunkZNGEVB5Mjs.cn.call(void 0, `BlockNoteView ${onChange ? "min-h-96 p-4" : ""}`, className, size === "sm" && "small"),
      children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, BlockNoteEditorFormattingToolbar, {})
    }
  ) });
}
_chunk7QVYU63Ejs.__name.call(void 0, BlockNoteEditor, "BlockNoteEditor");


exports.default = BlockNoteEditor;
//# sourceMappingURL=BlockNoteEditor-4G3L3LSF.js.map