"use client";
import {
  Button,
  errorToast,
  useCurrentUserContext
} from "./chunk-MVNVXOC6.mjs";
import "./chunk-KX7YG6LY.mjs";
import {
  BlockNoteDiffUtil,
  BlockNoteWordDiffRendererUtil,
  S3Service,
  cn
} from "./chunk-KUFWHMMY.mjs";
import "./chunk-AUXK7QSA.mjs";
import "./chunk-C7C7VY4F.mjs";
import "./chunk-3VM3WAOV.mjs";
import "./chunk-VOXD3ZLY.mjs";
import {
  __name
} from "./chunk-PAWJFY3S.mjs";

// src/components/editors/BlockNoteEditor.tsx
import { BlockNoteSchema, defaultInlineContentSpecs } from "@blocknote/core";
import { createReactInlineContentSpec, useCreateBlockNote } from "@blocknote/react";
import { BlockNoteView } from "@blocknote/shadcn";
import "@blocknote/shadcn/style.css";
import { CheckIcon, XIcon } from "lucide-react";
import { useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";

// src/components/editors/BlockNoteEditorFormattingToolbar.tsx
import {
  BasicTextStyleButton,
  BlockTypeSelect,
  CreateLinkButton,
  FileCaptionButton,
  FileReplaceButton,
  FormattingToolbar,
  FormattingToolbarController,
  TextAlignButton
} from "@blocknote/react";
import { jsx, jsxs } from "react/jsx-runtime";
function BlockNoteEditorFormattingToolbar() {
  return /* @__PURE__ */ jsx(
    FormattingToolbarController,
    {
      formattingToolbar: () => /* @__PURE__ */ jsxs(FormattingToolbar, { children: [
        /* @__PURE__ */ jsx(BlockTypeSelect, {}, "blockTypeSelect"),
        /* @__PURE__ */ jsx(FileCaptionButton, {}, "fileCaptionButton"),
        /* @__PURE__ */ jsx(FileReplaceButton, {}, "replaceFileButton"),
        /* @__PURE__ */ jsx(BasicTextStyleButton, { basicTextStyle: "bold" }, "boldStyleButton"),
        /* @__PURE__ */ jsx(BasicTextStyleButton, { basicTextStyle: "italic" }, "italicStyleButton"),
        /* @__PURE__ */ jsx(BasicTextStyleButton, { basicTextStyle: "underline" }, "underlineStyleButton"),
        /* @__PURE__ */ jsx(BasicTextStyleButton, { basicTextStyle: "strike" }, "strikeStyleButton"),
        /* @__PURE__ */ jsx(TextAlignButton, { textAlignment: "left" }, "textAlignLeftButton"),
        /* @__PURE__ */ jsx(TextAlignButton, { textAlignment: "center" }, "textAlignCenterButton"),
        /* @__PURE__ */ jsx(TextAlignButton, { textAlignment: "right" }, "textAlignRightButton"),
        /* @__PURE__ */ jsx(CreateLinkButton, {}, "createLinkButton")
      ] })
    }
  );
}
__name(BlockNoteEditorFormattingToolbar, "BlockNoteEditorFormattingToolbar");

// src/components/editors/BlockNoteEditor.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var createDiffActionsInlineContentSpec = /* @__PURE__ */ __name((handleAcceptChange, handleRejectChange) => {
  return createReactInlineContentSpec(
    {
      type: "diffActions",
      propSchema: {
        diffIds: {
          default: ""
        }
      },
      content: "none"
    },
    {
      render: /* @__PURE__ */ __name((props) => {
        const diffIds = props.inlineContent.props.diffIds;
        return /* @__PURE__ */ jsxs2("span", { className: "diff-actions-container mx-2 inline-flex items-center gap-1 align-middle", children: [
          /* @__PURE__ */ jsx2(
            Button,
            {
              title: "Accept change",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                diffIds.split(",").forEach((id) => handleAcceptChange(id.trim()));
              },
              children: /* @__PURE__ */ jsx2(CheckIcon, { className: "h-3 w-3 text-green-600" })
            }
          ),
          /* @__PURE__ */ jsx2(
            Button,
            {
              title: "Reject change",
              className: "mx-2 p-0",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                diffIds.split(",").forEach((id) => handleRejectChange(id.trim()));
              },
              children: /* @__PURE__ */ jsx2(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 = useTranslations();
  const { company } = useCurrentUserContext();
  const [acceptedChanges, setAcceptedChanges] = useState(/* @__PURE__ */ new Set());
  const [rejectedChanges, setRejectedChanges] = useState(/* @__PURE__ */ new Set());
  const editorRef = useRef(null);
  const handleAcceptChange = useCallback((diffId) => {
    setAcceptedChanges((prev) => /* @__PURE__ */ new Set([...prev, diffId]));
    setRejectedChanges((prev) => {
      const newSet = new Set(prev);
      newSet.delete(diffId);
      return newSet;
    });
  }, []);
  const handleRejectChange = useCallback((diffId) => {
    setRejectedChanges((prev) => /* @__PURE__ */ new Set([...prev, diffId]));
    setAcceptedChanges((prev) => {
      const newSet = new Set(prev);
      newSet.delete(diffId);
      return newSet;
    });
  }, []);
  const DiffActionsInlineContent = useMemo(
    () => createDiffActionsInlineContentSpec(handleAcceptChange, handleRejectChange),
    [handleAcceptChange, handleRejectChange]
  );
  const schema = useMemo(
    () => BlockNoteSchema.create({
      inlineContentSpecs: {
        ...defaultInlineContentSpecs,
        diffActions: DiffActionsInlineContent
      }
    }),
    [DiffActionsInlineContent]
  );
  const uploadImage = useCallback(
    async (file) => {
      if (!company) {
        errorToast({
          title: t(`generic.errors.upload`),
          error: t(`generic.errors.upload_description`)
        });
        throw new Error(t(`generic.errors.upload`));
      }
      const fileType = file.type;
      const key = `companies/${company.id}/${type}/${id}/${file.name}`;
      const s3 = await S3Service.getPreSignedUrl({
        key,
        contentType: fileType,
        isPublic: true
      });
      await fetch(s3.url, {
        method: "PUT",
        headers: s3.headers,
        body: file
      });
      const signedImage = await S3Service.getSignedUrl({
        key,
        isPublic: true
      });
      return signedImage.url;
    },
    [company, id, t]
  );
  const removeTrailingEmptyBlocks = useCallback(
    (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 = useMemo(() => {
    if (diffContent && initialContent) {
      try {
        const diffResult = BlockNoteDiffUtil.diff(initialContent, diffContent);
        const renderedDiff = 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 = useMemo(() => {
    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 = useCreateBlockNote(
    useMemo(
      () => ({
        placeholders: {
          emptyDocument: placeholder || t(`generic.blocknote.placeholder`)
        },
        schema,
        initialContent: validatedInitialContent,
        uploadFile: uploadImage
      }),
      [placeholder, t, schema, validatedInitialContent, uploadImage]
    )
  );
  const handleChange = useCallback(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;
    }
    __name(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__ */ __name((a, b) => {
    return JSON.stringify(a) === JSON.stringify(b);
  }, "areBlocksEqual");
  const hasInitializedFromMarkdown = useRef(null);
  useEffect(() => {
    const updateContent = /* @__PURE__ */ __name(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 = useRef(null);
  useEffect(() => {
    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 = useCallback(
    (message) => {
      try {
        const editorElement = editorRef.current?.querySelector('[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__ */ jsx2("div", { ref: editorRef, className: cn(bordered ? "rounded-md border" : "", "w-full"), children: /* @__PURE__ */ jsx2(
    BlockNoteView,
    {
      editor,
      onChange: handleChange,
      editable: onChange !== void 0,
      formattingToolbar: false,
      theme: "light",
      className: cn(`BlockNoteView ${onChange ? "min-h-96 p-4" : ""}`, className, size === "sm" && "small"),
      children: /* @__PURE__ */ jsx2(BlockNoteEditorFormattingToolbar, {})
    }
  ) });
}
__name(BlockNoteEditor, "BlockNoteEditor");
export {
  BlockNoteEditor as default
};
//# sourceMappingURL=BlockNoteEditor-BQ5WWVUF.mjs.map