"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const crepe = require('@milkdown/crepe');
require('@milkdown/crepe/theme/common/style.css');
const utils = require('../../../utils.cjs');
const core = require('@milkdown/kit/core');
const listener = require('@milkdown/kit/plugin/listener');
const model = require('@milkdown/kit/prose/model');
const state = require('@milkdown/kit/prose/state');
const React = require('react');

function MarkdownEditor({
  value,
  onChange,
  className,
  uploadImage,
  placeholder = "Write something..."
}) {
  const containerRef = React.useRef(null);
  const crepeRef = React.useRef(null);
  const isReadyRef = React.useRef(false);
  const [isReady, setIsReady] = React.useState(false);
  const onChangeRef = React.useRef(onChange);
  const initialValueRef = React.useRef(value ?? "");
  const throttledOnChangeRef = React.useRef(null);
  onChangeRef.current = onChange;
  React.useLayoutEffect(() => {
    if (crepeRef.current) return;
    const container = containerRef.current;
    if (!container) return;
    const crepe$1 = new crepe.Crepe({
      root: container,
      defaultValue: initialValueRef.current,
      featureConfigs: {
        [crepe.CrepeFeature.Placeholder]: {
          text: placeholder
        },
        ...uploadImage ? {
          [crepe.CrepeFeature.ImageBlock]: {
            onUpload: async (file) => {
              const url = await uploadImage(file);
              return url;
            }
          }
        } : {}
      }
    });
    throttledOnChangeRef.current = utils.throttle((markdown) => {
      if (onChangeRef.current) onChangeRef.current(markdown);
    }, 200);
    crepe$1.editor.config((ctx) => {
      ctx.get(listener.listenerCtx).markdownUpdated((_, markdown) => {
        throttledOnChangeRef.current?.(markdown);
      });
    }).use(listener.listener);
    crepe$1.create().then(() => {
      isReadyRef.current = true;
      setIsReady(true);
    });
    crepeRef.current = crepe$1;
    return () => {
      try {
        isReadyRef.current = false;
        throttledOnChangeRef.current?.cancel?.();
        throttledOnChangeRef.current = null;
        crepe$1.destroy();
      } finally {
        crepeRef.current = null;
      }
    };
  }, []);
  React.useLayoutEffect(() => {
    if (!isReady) return;
    if (!crepeRef.current) return;
    if (typeof value !== "string") return;
    let currentMarkdown;
    try {
      currentMarkdown = crepeRef.current?.getMarkdown?.();
    } catch {
      return;
    }
    if (currentMarkdown === value) return;
    crepeRef.current.editor.action((ctx) => {
      const view = ctx.get(core.editorViewCtx);
      if (view?.hasFocus?.() === true) return;
      const parser = ctx.get(core.parserCtx);
      const doc = parser(value);
      if (!doc) return;
      const state$1 = view.state;
      const selection = state$1.selection;
      const from = selection.from;
      let tr = state$1.tr;
      tr = tr.replace(0, state$1.doc.content.size, new model.Slice(doc.content, 0, 0));
      const docSize = doc.content.size;
      const safeFrom = Math.max(1, Math.min(from, Math.max(1, docSize - 2)));
      tr = tr.setSelection(state.Selection.near(tr.doc.resolve(safeFrom)));
      view.dispatch(tr);
    });
  }, [value, isReady]);
  return /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: utils.cn("milkdown-custom", className) });
}

exports.MarkdownEditor = MarkdownEditor;
