import { j as r } from "./index-B0nYVpa0.mjs";
import { useRef as I, useState as D, useEffect as E } from "react";
import { DynamicDropdown as P, Tooltip as y, IconButton as L } from "@fileverse/ui";
import { a3 as A, a4 as _, c as O } from "./index-qkBNm93K.mjs";
const p = (e, n, s = n) => {
  const { state: o } = e, l = o.changeByRange((t) => {
    const u = o.sliceDoc(t.from, t.to), a = o.sliceDoc(
      Math.max(0, t.from - n.length),
      t.from
    ), m = o.sliceDoc(
      t.to,
      Math.min(o.doc.length, t.to + s.length)
    );
    if (a === n && m === s)
      return {
        changes: [
          { from: t.from - n.length, to: t.from, insert: "" },
          { from: t.to, to: t.to + s.length, insert: "" }
        ],
        range: O.range(
          t.from - n.length,
          t.to - n.length
        )
      };
    const b = n + u + s;
    return {
      changes: { from: t.from, to: t.to, insert: b },
      range: O.range(
        t.from + n.length,
        t.from + n.length + u.length
      )
    };
  });
  e.dispatch(o.update(l, { scrollIntoView: !0 })), e.focus();
}, S = (e, n) => {
  const { state: s } = e, o = [], l = /* @__PURE__ */ new Set();
  for (const t of s.selection.ranges) {
    let u = t.from;
    for (; ; ) {
      const a = s.doc.lineAt(u);
      if (!l.has(a.number)) {
        l.add(a.number);
        const m = n(a.text, a.from);
        m && o.push(m);
      }
      if (a.to >= t.to) break;
      u = a.to + 1;
    }
  }
  o.length && e.dispatch(s.update({ changes: o, scrollIntoView: !0 })), e.focus();
}, k = (e, n) => S(
  e,
  (s, o) => s.startsWith(n) ? { from: o, to: o + n.length, insert: "" } : { from: o, insert: n }
), w = (e, n) => {
  const s = "#".repeat(n) + " ";
  return S(e, (o, l) => {
    const t = o.match(/^(#{1,6})\s/);
    return t && t[1].length === n ? { from: l, to: l + t[0].length, insert: "" } : t ? { from: l, to: l + t[0].length, insert: s } : { from: l, insert: s };
  });
}, f = (e, n) => {
  const { state: s } = e, o = s.selection.main, a = `${s.doc.lineAt(o.from).text.trim() === "" ? "" : `

`}${n}
`;
  e.dispatch(
    s.update({
      changes: { from: o.from, insert: a },
      selection: { anchor: o.from + a.length },
      scrollIntoView: !0
    })
  ), e.focus();
}, z = (e, n) => {
  const { state: s } = e, o = s.changeByRange((l) => {
    const t = s.sliceDoc(l.from, l.to) || "text", u = n ?? "url", a = `[${t}](${u})`, m = l.from + 1 + t.length + 2;
    return {
      changes: { from: l.from, to: l.to, insert: a },
      range: O.range(m, m + u.length)
    };
  });
  e.dispatch(s.update(o, { scrollIntoView: !0 })), e.focus();
}, G = (e, n) => {
  const s = `<img src="${n.src}" media-type="secure-img" encryptionKey="${n.encryptionKey}" nonce="${n.nonce}" ipfsUrl="${n.ipfsUrl}" ipfsHash="${n.ipfsHash}" version="2" authTag="${n.authTag}" mimeType="${n.mimeType}" />`;
  f(e, s);
}, K = (e, n) => f(e, `<img src="${n}" media-type="img" />`), M = `| Column 1 | Column 2 |
| -------- | -------- |
|          |          |`, c = {
  bold: (e) => p(e, "**"),
  italic: (e) => p(e, "*"),
  strike: (e) => p(e, "~~"),
  inlineCode: (e) => p(e, "`"),
  underline: (e) => p(e, "<u>", "</u>"),
  heading: (e, n) => w(e, n),
  bulletList: (e) => k(e, "- "),
  orderedList: (e) => k(e, "1. "),
  taskList: (e) => k(e, "- [ ] "),
  blockquote: (e) => k(e, "> "),
  codeBlock: (e) => f(e, "```\n\n```"),
  horizontalRule: (e) => f(e, "---"),
  table: (e) => f(e, M),
  link: (e, n) => z(e, n),
  undo: (e) => {
    _(e), e.focus();
  },
  redo: (e) => {
    A(e), e.focus();
  },
  // Highlight → inline HTML (round-trips via our turndown/DOMPurify rules).
  highlight: (e, n) => n ? p(e, `<mark style="background-color: ${n}">`, "</mark>") : p(e, "<mark>", "</mark>")
}, B = [
  [
    { icon: "Undo", label: "Undo", run: (e) => c.undo(e) },
    { icon: "Redo", label: "Redo", run: (e) => c.redo(e) }
  ],
  [
    {
      icon: "Heading1",
      label: "Heading 1",
      run: (e) => c.heading(e, 1)
    },
    {
      icon: "Heading2",
      label: "Heading 2",
      run: (e) => c.heading(e, 2)
    },
    {
      icon: "Heading3",
      label: "Heading 3",
      run: (e) => c.heading(e, 3)
    }
  ],
  [
    { icon: "Bold", label: "Bold", run: (e) => c.bold(e) },
    { icon: "Italic", label: "Italic", run: (e) => c.italic(e) },
    {
      icon: "Underline",
      label: "Underline",
      run: (e) => c.underline(e)
    },
    {
      icon: "Strikethrough",
      label: "Strikethrough",
      run: (e) => c.strike(e)
    },
    {
      icon: "Code",
      label: "Inline code",
      run: (e) => c.inlineCode(e)
    },
    {
      icon: "Highlighter",
      label: "Highlight",
      run: (e) => c.highlight(e)
    }
  ],
  [
    {
      icon: "List",
      label: "Bullet list",
      run: (e) => c.bulletList(e)
    },
    {
      icon: "ListOrdered",
      label: "Numbered list",
      run: (e) => c.orderedList(e)
    },
    {
      icon: "ListChecks",
      label: "To-do list",
      run: (e) => c.taskList(e)
    },
    { icon: "TextQuote", label: "Quote", run: (e) => c.blockquote(e) }
  ],
  [
    // Inserts [text](url) inline and selects `url` to type over.
    { icon: "Link", label: "Link", run: (e) => c.link(e) },
    { icon: "Image", label: "Image", run: () => {
    }, upload: !0 },
    {
      icon: "Braces",
      label: "Code block",
      run: (e) => c.codeBlock(e)
    },
    { icon: "Table", label: "Table", run: (e) => c.table(e) },
    {
      icon: "Minus",
      label: "Divider",
      run: (e) => c.horizontalRule(e)
    }
  ]
], N = 3, W = B.slice(0, N), C = B.slice(N), R = "!h-6 !w-6 !min-w-0", v = 560, j = () => /* @__PURE__ */ r.jsx("div", { className: "w-[1px] h-4 vertical-divider mx-1" });
function X({
  view: e,
  onExit: n,
  ipfsImageUploadFn: s,
  onError: o
}) {
  const l = (i) => {
    const d = document.createElement("input");
    d.type = "file", d.accept = "image/*", d.onchange = async () => {
      var U;
      const h = (U = d.files) == null ? void 0 : U[0];
      if (!(!h || !h.type.includes("image/")))
        try {
          if (s) {
            const g = await s(h);
            G(i, {
              src: URL.createObjectURL(h),
              ipfsUrl: g.ipfsUrl,
              encryptionKey: g.encryptionKey,
              nonce: g.nonce,
              ipfsHash: g.ipfsHash,
              authTag: g.authTag,
              mimeType: h.type
            });
          } else {
            const g = await new Promise((H, $) => {
              const x = new FileReader();
              x.onload = () => H(x.result), x.onerror = $, x.readAsDataURL(h);
            });
            K(i, g);
          }
        } catch {
          o == null || o("Failed to upload image");
        }
    }, d.click();
  }, t = (i, d) => {
    if (i.upload) {
      l(d);
      return;
    }
    i.run(d);
  }, u = I(null), [a, m] = D(!1);
  E(() => {
    const i = u.current;
    if (!i || typeof ResizeObserver > "u") return;
    const d = () => m(i.clientWidth < v);
    d();
    const h = new ResizeObserver(d);
    return h.observe(i), () => h.disconnect();
  }, []);
  const b = (i) => /* @__PURE__ */ r.jsx(y, { text: i.label, children: /* @__PURE__ */ r.jsx(
    L,
    {
      variant: "ghost",
      size: "sm",
      className: R,
      icon: i.icon,
      disabled: !e,
      onClick: () => e && t(i, e)
    }
  ) }, i.label), T = (i, d) => /* @__PURE__ */ r.jsxs("div", { className: "flex items-center gap-0.5", children: [
    d && /* @__PURE__ */ r.jsx(j, {}),
    i.map(b)
  ] }, i[0].label);
  return /* @__PURE__ */ r.jsxs("div", { className: "flex items-center px-2 py-2 border-b color-border-default shrink-0", children: [
    /* @__PURE__ */ r.jsxs(
      "div",
      {
        ref: u,
        className: "flex items-center gap-0.5 flex-1 min-w-0 overflow-hidden",
        children: [
          W.map((i, d) => T(i, d > 0)),
          a ? /* @__PURE__ */ r.jsxs("div", { className: "flex items-center gap-0.5", children: [
            /* @__PURE__ */ r.jsx(j, {}),
            /* @__PURE__ */ r.jsx(
              P,
              {
                align: "start",
                sideOffset: 8,
                anchorTrigger: /* @__PURE__ */ r.jsx(y, { text: "More", children: /* @__PURE__ */ r.jsx(
                  L,
                  {
                    variant: "ghost",
                    size: "sm",
                    className: R,
                    icon: "Ellipsis",
                    disabled: !e
                  }
                ) }),
                content: /* @__PURE__ */ r.jsx("div", { className: "flex items-center gap-0.5 p-1", children: C.flat().map(b) })
              },
              "md-more-dropdown"
            )
          ] }) : C.map((i) => T(i, !0))
        ]
      }
    ),
    n && /* @__PURE__ */ r.jsxs("div", { className: "flex items-center pl-1 shrink-0", children: [
      /* @__PURE__ */ r.jsx(j, {}),
      /* @__PURE__ */ r.jsx(y, { text: "Back to editor", children: /* @__PURE__ */ r.jsx(
        L,
        {
          variant: "ghost",
          size: "sm",
          className: R,
          icon: "PenLine",
          onClick: n
        }
      ) })
    ] })
  ] });
}
export {
  X as default
};
