"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("./jsx-runtime-B6vEU3CM.js");
const React = require("react");
const iconsMaterial = require("@mui/icons-material");
const material = require("@mui/material");
const common = require("./common-B47boGYI.js");
const api = require("./api-BygscvSz.js");
const apiConfig = require("./api-config-DXwDMFn-.js");
;/* empty css                        */
const HANDLEBARS_PLACEHOLDER_PREFIX = "hbs-placeholder-";
let placeholderCounter = 0;
const BLOCK_HELPER_OPEN_PATTERN = /\{\{#(each|if|unless|with|let|inline|block|contentFor|extend|embed|log|lookup)\s+[^}]*\}\}/g;
const BLOCK_HELPER_CLOSE_PATTERN = /\{\{\/(each|if|unless|with|let|inline|block|contentFor|extend|embed|log|lookup)\}\}/g;
const BLOCK_HELPER_ELSE_PATTERN = /\{\{else\}\}/g;
function protectHandlebars(html) {
  const map = {};
  placeholderCounter = 0;
  let protectedHtml = html;
  protectedHtml = protectedHtml.replace(BLOCK_HELPER_OPEN_PATTERN, (match, p1, offset, string) => {
    const beforeMatch = string.substring(0, offset);
    const lastCommentStart = beforeMatch.lastIndexOf("<!--");
    const lastCommentEnd = beforeMatch.lastIndexOf("-->");
    if (lastCommentStart > lastCommentEnd) {
      return match;
    }
    return `<!--${match}-->`;
  });
  protectedHtml = protectedHtml.replace(BLOCK_HELPER_CLOSE_PATTERN, (match, p1, offset, string) => {
    const beforeMatch = string.substring(0, offset);
    const lastCommentStart = beforeMatch.lastIndexOf("<!--");
    const lastCommentEnd = beforeMatch.lastIndexOf("-->");
    if (lastCommentStart > lastCommentEnd) {
      return match;
    }
    return `<!--${match}-->`;
  });
  protectedHtml = protectedHtml.replace(BLOCK_HELPER_ELSE_PATTERN, (match, offset, string) => {
    const beforeMatch = string.substring(0, offset);
    const lastCommentStart = beforeMatch.lastIndexOf("<!--");
    const lastCommentEnd = beforeMatch.lastIndexOf("-->");
    if (lastCommentStart > lastCommentEnd) {
      return match;
    }
    return `<!--${match}-->`;
  });
  protectedHtml = protectedHtml.replace(/(\{\{[^}]*\}\})/g, (match, _p1, offset, string) => {
    const beforeMatch = string.substring(0, offset);
    const lastCommentStart = beforeMatch.lastIndexOf("<!--");
    const lastCommentEnd = beforeMatch.lastIndexOf("-->");
    if (lastCommentStart > lastCommentEnd) {
      return match;
    }
    const lastSpanStart = beforeMatch.lastIndexOf('<span class="hbs-placeholder"');
    const lastSpanEnd = beforeMatch.lastIndexOf("</span>");
    if (lastSpanStart > lastSpanEnd) {
      return match;
    }
    const lastTagOpen = beforeMatch.lastIndexOf("<");
    const lastTagClose = beforeMatch.lastIndexOf(">");
    if (lastTagOpen > lastTagClose) {
      return match;
    }
    const id = `${HANDLEBARS_PLACEHOLDER_PREFIX}${placeholderCounter++}`;
    map[id] = match;
    return `<span class="hbs-placeholder" data-hbs-id="${id}" contenteditable="false" >${match}</span>`;
  });
  return { html: protectedHtml, map };
}
function restoreHandlebars(html, map) {
  let restoredHtml = html;
  restoredHtml = restoredHtml.replace(/<!--(\{\{#(?:each|if|unless|with|let|inline|block|contentFor|extend|embed|log|lookup)\s+[^}]*\}\})-->/g, (match, captured) => {
    return captured;
  });
  restoredHtml = restoredHtml.replace(/<!--(\{\{\/(?:each|if|unless|with|let|inline|block|contentFor|extend|embed|log|lookup)\}\})-->/g, (match, captured) => {
    return captured;
  });
  restoredHtml = restoredHtml.replace(/<!--(\{\{else\}\})-->/g, (match, captured) => {
    return captured;
  });
  if (!map) {
    map = {};
    const regex = /<span[^>]*data-hbs-id="([^"]+)"[^>]*>([^<]+)<\/span>/g;
    let match;
    while ((match = regex.exec(restoredHtml)) !== null) {
      map[match[1]] = match[2];
    }
  }
  restoredHtml = restoredHtml.replace(
    /<span[^>]*class="hbs-placeholder"[^>]*data-hbs-id="([^"]+)"[^>]*>.*?<\/span>/g,
    (match, id) => {
      return map[id] || match;
    }
  );
  return restoredHtml;
}
function containsHandlebars(html) {
  return /\{\{[^}]*\}\}/.test(html);
}
function prepareForEditing(html) {
  if (containsHandlebars(html)) {
    return protectHandlebars(html);
  }
  return { html, map: {} };
}
function prepareForSaving(html, map) {
  return restoreHandlebars(html, map);
}
const FONT_FAMILIES = [
  "Arial",
  "Courier New",
  "Georgia",
  "Times New Roman",
  "Trebuchet MS",
  "Verdana"
];
const FONT_SIZES = ["10px", "12px", "14px", "16px", "18px", "20px", "24px", "28px", "32px"];
const HEADING_FORMATS = [
  { value: "p", label: "Paragraph" },
  { value: "h1", label: "Heading 1" },
  { value: "h2", label: "Heading 2" },
  { value: "h3", label: "Heading 3" },
  { value: "h4", label: "Heading 4" },
  { value: "h5", label: "Heading 5" },
  { value: "h6", label: "Heading 6" }
];
const PRESET_COLORS = [
  "#000000",
  "#434343",
  "#666666",
  "#999999",
  "#b7b7b7",
  "#cccccc",
  "#d9d9d9",
  "#ffffff",
  "#ff0000",
  "#ff9900",
  "#ffff00",
  "#00ff00",
  "#00ffff",
  "#4a86e8",
  "#9900ff",
  "#ff00ff",
  "#ea9999",
  "#f9cb9c",
  "#ffe599",
  "#b6d7a8",
  "#a2c4c9",
  "#9fc5e8",
  "#b4a7d6",
  "#d5a6bd",
  "#e06666",
  "#f6b26b",
  "#ffd966",
  "#93c47d",
  "#76a5af",
  "#6fa8dc",
  "#8e7cc3",
  "#c27ba0",
  "#cc0000",
  "#e69138",
  "#f1c232",
  "#6aa84f",
  "#45818e",
  "#3d85c8",
  "#674ea7",
  "#85200c"
];
const CustomEditor = React.forwardRef((props, ref) => {
  const {
    editorRef: editorRefProp,
    data = "",
    handleEditorReady,
    onError,
    config = {},
    ...rest
  } = props;
  const [error, setError] = React.useState(null);
  const [fontFamily, setFontFamily] = React.useState("Arial");
  const [fontSize, setFontSize] = React.useState("14px");
  const [headingFormat, setHeadingFormat] = React.useState("p");
  const [showSourceMode, setShowSourceMode] = React.useState(false);
  const [sourceCode, setSourceCode] = React.useState(data);
  const [history, setHistory] = React.useState([data]);
  const [historyIndex, setHistoryIndex] = React.useState(0);
  const [selectedElement, setSelectedElement] = React.useState(null);
  const [resizeHandles, setResizeHandles] = React.useState(null);
  const [showTablePicker, setShowTablePicker] = React.useState(false);
  const [tablePickerAnchor, setTablePickerAnchor] = React.useState(null);
  const [textSelectionAnchor, setTextSelectionAnchor] = React.useState(null);
  const [showTextToolbar, setShowTextToolbar] = React.useState(false);
  const [colorPickerState, setColorPickerState] = React.useState(null);
  const [selectedCell, setSelectedCell] = React.useState(null);
  const [showTableToolbar, setShowTableToolbar] = React.useState(false);
  const [tableToolbarPosition, setTableToolbarPosition] = React.useState(null);
  const [cellProperties, setCellProperties] = React.useState({
    borderStyle: "solid",
    borderColor: "#ddd",
    borderWidth: "1px",
    backgroundColor: "transparent",
    width: "auto",
    height: "auto",
    padding: "8px",
    textAlign: "left",
    verticalAlign: "middle"
  });
  const contentEditableRef = React.useRef(null);
  const sourceCodeRef = React.useRef(data);
  const onEditorChangeRef = React.useRef(props.onEditorChange);
  const handleEditorReadyRef = React.useRef(handleEditorReady);
  React.useEffect(() => {
    onEditorChangeRef.current = props.onEditorChange;
  });
  React.useEffect(() => {
    handleEditorReadyRef.current = handleEditorReady;
  });
  const sourceViewContentRef = React.useRef(data);
  const fileInputRef = React.useRef(null);
  const htmlFileInputRef = React.useRef(null);
  const replaceImageInputRef = React.useRef(null);
  const resizeStartRef = React.useRef(null);
  const handlebarsMapRef = React.useRef({});
  const apiConfig$1 = apiConfig.getApiConfig();
  React.useEffect(() => {
    if (!data) return;
    const { html: protectedHtml, map } = prepareForEditing(data);
    handlebarsMapRef.current = map;
    sourceCodeRef.current = data;
    if (contentEditableRef.current && contentEditableRef.current.innerHTML !== protectedHtml) {
      contentEditableRef.current.innerHTML = protectedHtml;
    }
  }, [data]);
  React.useEffect(() => {
    var _a;
    console.log("contentEditableRef.current...........", contentEditableRef.current);
    if (contentEditableRef.current) {
      try {
        const { html: protectedHtml, map } = prepareForEditing(data || "");
        handlebarsMapRef.current = map;
        contentEditableRef.current.innerHTML = protectedHtml;
        const adapter2 = {
          getData: () => {
            return prepareForSaving(sourceCodeRef.current, handlebarsMapRef.current);
          },
          setData: (newData) => {
            const { html: protectedHtml2, map: map2 } = prepareForEditing(newData);
            handlebarsMapRef.current = map2;
            sourceCodeRef.current = newData;
            if (contentEditableRef.current) {
              contentEditableRef.current.innerHTML = protectedHtml2;
            }
          },
          model: {
            insertContent: (fragment) => {
              execCommand("insertHTML", fragment);
            }
          },
          data: {
            processor: {
              toView: (html) => html
            },
            toModel: (html) => html
          }
        };
        (_a = handleEditorReadyRef.current) == null ? void 0 : _a.call(handleEditorReadyRef, adapter2);
      } catch (e) {
        console.error("[CustomEditor] init effect error:", e);
      }
    }
  }, []);
  const execCommand = React.useCallback((command, value) => {
    document.execCommand(command, false, value);
    if (contentEditableRef.current) {
      sourceCodeRef.current = contentEditableRef.current.innerHTML;
      saveToHistory();
    }
  }, []);
  const saveToHistory = React.useCallback(() => {
    if (contentEditableRef.current) {
      const newHistory = history.slice(0, historyIndex + 1);
      newHistory.push(contentEditableRef.current.innerHTML);
      setHistory(newHistory.slice(-50));
      setHistoryIndex(newHistory.length - 1);
    }
  }, [history, historyIndex]);
  const handleUndo = React.useCallback(() => {
    if (historyIndex > 0) {
      const newIndex = historyIndex - 1;
      setHistoryIndex(newIndex);
      if (contentEditableRef.current) {
        contentEditableRef.current.innerHTML = history[newIndex];
        sourceCodeRef.current = history[newIndex];
      }
    }
  }, [history, historyIndex]);
  const handleRedo = React.useCallback(() => {
    if (historyIndex < history.length - 1) {
      const newIndex = historyIndex + 1;
      setHistoryIndex(newIndex);
      if (contentEditableRef.current) {
        contentEditableRef.current.innerHTML = history[newIndex];
        sourceCodeRef.current = history[newIndex];
      }
    }
  }, [history, historyIndex]);
  const handleInput = React.useCallback(() => {
    var _a;
    if (contentEditableRef.current) {
      const visualHtml = contentEditableRef.current.innerHTML;
      sourceCodeRef.current = prepareForSaving(visualHtml, handlebarsMapRef.current);
      (_a = onEditorChangeRef.current) == null ? void 0 : _a.call(onEditorChangeRef, sourceCodeRef.current);
    }
  }, []);
  const sanitizePastedHtml = React.useCallback((html) => {
    const doc = new DOMParser().parseFromString(html, "text/html");
    doc.querySelectorAll("span").forEach((span) => {
      var _a;
      const frag = document.createDocumentFragment();
      while (span.firstChild) frag.appendChild(span.firstChild);
      (_a = span.parentNode) == null ? void 0 : _a.replaceChild(frag, span);
    });
    doc.querySelectorAll("a").forEach((a) => {
      var _a;
      const text = document.createTextNode(a.textContent || "");
      (_a = a.parentNode) == null ? void 0 : _a.replaceChild(text, a);
    });
    doc.querySelectorAll("[style], [class], [color], [bgcolor], [face]").forEach((el) => {
      el.removeAttribute("style");
      el.removeAttribute("class");
      el.removeAttribute("color");
      el.removeAttribute("bgcolor");
      el.removeAttribute("face");
    });
    return doc.body.innerHTML;
  }, []);
  const handlePaste = React.useCallback((e) => {
    e.preventDefault();
    const html = e.clipboardData.getData("text/html");
    const text = e.clipboardData.getData("text/plain");
    if (html) {
      execCommand("insertHTML", sanitizePastedHtml(html));
    } else {
      execCommand("insertText", text);
    }
  }, [execCommand, sanitizePastedHtml]);
  const handleImageUpload = React.useCallback(async (file) => {
    var _a;
    try {
      const uFiles = await common.uploadFiles([file], "document");
      const token = common.getToken();
      const payload = {
        ...token,
        "x-timezone": ((_a = token["x-timezone"]) == null ? void 0 : _a.toString()) || "",
        title: file == null ? void 0 : file.name.split(".")[0],
        path: "/",
        is_private: true,
        is_directory: false,
        file_size: file.size,
        is_child: false,
        file_extension: file == null ? void 0 : file.name.split(".")[1],
        type: "image",
        mime_type: file.type,
        url: `${apiConfig$1 == null ? void 0 : apiConfig$1.s3BucketUrl}${uFiles[0]}`
      };
      await api.postV1Drive(payload);
      execCommand("insertHTML", `<img src="${payload.url}" alt="${file.name}" style="max-width: 100%;" />`);
    } catch (error2) {
      console.error("Image upload failed:", error2);
      onError == null ? void 0 : onError(error2);
    }
  }, [apiConfig$1, execCommand, onError]);
  const handleFileChange = React.useCallback((e) => {
    var _a;
    const file = (_a = e.target.files) == null ? void 0 : _a[0];
    if (file) {
      handleImageUpload(file);
    }
  }, [handleImageUpload]);
  const handleInsertLink = React.useCallback(() => {
    const url = prompt("Enter URL:");
    if (url) {
      execCommand("createLink", url);
    }
  }, [execCommand]);
  React.useCallback(() => {
    const rows = prompt("Number of rows:", "3");
    const cols = prompt("Number of columns:", "3");
    if (rows && cols) {
      let tableHTML = '<table border="1" style="border-collapse: collapse; width: 100%;">';
      tableHTML += "<thead><tr>";
      for (let i = 0; i < parseInt(cols); i++) {
        tableHTML += '<th style="border: 1px solid #ddd; padding: 8px;">Header</th>';
      }
      tableHTML += "</tr></thead><tbody>";
      for (let i = 0; i < parseInt(rows); i++) {
        tableHTML += "<tr>";
        for (let j = 0; j < parseInt(cols); j++) {
          tableHTML += '<td style="border: 1px solid #ddd; padding: 8px;"></td>';
        }
        tableHTML += "</tr>";
      }
      tableHTML += "</tbody></table>";
      execCommand("insertHTML", tableHTML);
    }
  }, [execCommand]);
  const TablePicker = () => {
    const [hoverCell, setHoverCell] = React.useState(null);
    const maxRows = 10;
    const maxCols = 10;
    const buttonRect = tablePickerAnchor == null ? void 0 : tablePickerAnchor.getBoundingClientRect();
    const editorContainer = document.querySelector(".custom-editor-container");
    const containerRect = editorContainer == null ? void 0 : editorContainer.getBoundingClientRect();
    let top = 0;
    let left = 0;
    if (buttonRect && containerRect) {
      top = buttonRect.bottom - containerRect.top + 5;
      left = buttonRect.left - containerRect.left;
    }
    return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(
      material.Box,
      {
        sx: {
          position: "absolute",
          top: `${top}px`,
          left: `${left}px`,
          bgcolor: "white",
          border: "1px solid #ddd",
          borderRadius: 1,
          p: 2,
          boxShadow: 3,
          zIndex: 9999
        },
        children: [
          /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Box, { sx: { display: "grid", gridTemplateColumns: `repeat(${maxCols}, 20px)`, gap: "2px", mb: 1 }, children: Array.from({ length: maxRows }).map(
            (_, rowIndex) => Array.from({ length: maxCols }).map((_2, colIndex) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              material.Box,
              {
                onMouseEnter: () => setHoverCell({ row: rowIndex + 1, col: colIndex + 1 }),
                onClick: () => {
                  handleInsertTableFromPicker(rowIndex + 1, colIndex + 1);
                  setHoverCell(null);
                },
                sx: {
                  width: 20,
                  height: 20,
                  border: "1px solid #ddd",
                  bgcolor: hoverCell && rowIndex < hoverCell.row && colIndex < hoverCell.col ? "#1976d2" : "white",
                  cursor: "pointer",
                  "&:hover": {
                    bgcolor: "#1976d2"
                  }
                }
              },
              `${rowIndex}-${colIndex}`
            ))
          ) }),
          /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Box, { sx: { textAlign: "center", fontSize: "12px", color: "#666" }, children: hoverCell ? `${hoverCell.row} × ${hoverCell.col}` : "1 × 1" })
        ]
      }
    );
  };
  const handleFontFamilyChange = React.useCallback((e) => {
    const family = e.target.value;
    setFontFamily(family);
    execCommand("fontName", family);
  }, [execCommand]);
  const handleFontSizeChange = React.useCallback((e) => {
    var _a;
    const size = e.target.value;
    setFontSize(size);
    document.execCommand("fontSize", false, "7");
    if (contentEditableRef.current) {
      const fontTags = Array.from(
        contentEditableRef.current.querySelectorAll('font[size="7"]')
      );
      fontTags.forEach((tag) => {
        var _a2;
        const span = document.createElement("span");
        span.style.fontSize = size;
        while (tag.firstChild) span.appendChild(tag.firstChild);
        (_a2 = tag.parentNode) == null ? void 0 : _a2.replaceChild(span, tag);
      });
      sourceCodeRef.current = contentEditableRef.current.innerHTML;
      saveToHistory();
      (_a = onEditorChangeRef.current) == null ? void 0 : _a.call(onEditorChangeRef, sourceCodeRef.current);
    }
  }, [saveToHistory]);
  const handleHeadingFormatChange = React.useCallback((e) => {
    const format = e.target.value;
    setHeadingFormat(format);
    execCommand("formatBlock", `<${format}>`);
  }, [execCommand]);
  const handleToggleSource = React.useCallback(() => {
    var _a;
    if (!showSourceMode) {
      const visualHtml = ((_a = contentEditableRef.current) == null ? void 0 : _a.innerHTML) || sourceCodeRef.current || data;
      const restoredHtml = prepareForSaving(visualHtml, handlebarsMapRef.current);
      setSourceCode(restoredHtml);
      sourceViewContentRef.current = restoredHtml;
      sourceCodeRef.current = restoredHtml;
      setShowSourceMode(true);
    } else {
      const currentSource = sourceViewContentRef.current.trim();
      if (!currentSource) {
        const defaultHtml = "<p><br></p>";
        sourceCodeRef.current = defaultHtml;
        sourceViewContentRef.current = defaultHtml;
        setSourceCode(defaultHtml);
      } else {
        sourceCodeRef.current = currentSource;
      }
      setShowSourceMode(false);
    }
  }, [showSourceMode, data]);
  const hasProcessedModeSwitch = React.useRef(false);
  React.useEffect(() => {
    if (!showSourceMode && contentEditableRef.current && !hasProcessedModeSwitch.current) {
      hasProcessedModeSwitch.current = true;
      try {
        const currentSource = sourceCodeRef.current.trim();
        if (!currentSource) {
          const defaultHtml = "<p><br></p>";
          const { html: protectedHtml, map } = prepareForEditing(defaultHtml);
          handlebarsMapRef.current = map;
          contentEditableRef.current.innerHTML = protectedHtml;
        } else {
          const { html: protectedHtml, map } = prepareForEditing(currentSource);
          handlebarsMapRef.current = map;
          if (!protectedHtml || protectedHtml.trim() === "") {
            console.warn("Protected HTML is empty, using original source");
            contentEditableRef.current.innerHTML = currentSource;
          } else {
            contentEditableRef.current.innerHTML = protectedHtml;
          }
        }
        const newHistory = history.slice(0, historyIndex + 1);
        newHistory.push(contentEditableRef.current.innerHTML);
        setHistory(newHistory.slice(-50));
        setHistoryIndex(newHistory.length - 1);
      } catch (error2) {
        console.error("Error updating visual mode:", error2);
        if (contentEditableRef.current && sourceCodeRef.current) {
          try {
            contentEditableRef.current.innerHTML = sourceCodeRef.current;
          } catch (innerError) {
            console.error("Failed to render HTML:", innerError);
          }
        }
      }
    }
    if (showSourceMode) {
      hasProcessedModeSwitch.current = false;
    }
  }, [showSourceMode, history, historyIndex]);
  const handleHtmlFileUpload = React.useCallback((e) => {
    var _a;
    const file = (_a = e.target.files) == null ? void 0 : _a[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (event) => {
      var _a2;
      const htmlContent = (_a2 = event.target) == null ? void 0 : _a2.result;
      if (htmlContent) {
        setSourceCode(htmlContent);
        sourceViewContentRef.current = htmlContent;
        sourceCodeRef.current = htmlContent;
        if (!showSourceMode && contentEditableRef.current) {
          try {
            const { html: protectedHtml, map } = prepareForEditing(htmlContent);
            handlebarsMapRef.current = map;
            contentEditableRef.current.innerHTML = protectedHtml;
            saveToHistory();
          } catch (error2) {
            console.error("Error processing uploaded HTML:", error2);
            alert("There was an error processing the HTML file. Please check the file and try again.");
          }
        }
      }
    };
    reader.onerror = () => {
      alert("Failed to read HTML file. Please try again.");
    };
    reader.readAsText(file);
    e.target.value = "";
  }, [showSourceMode, saveToHistory]);
  const handleSourceCodeChange = React.useCallback((e) => {
    const newCode = e.target.value;
    setSourceCode(newCode);
    sourceViewContentRef.current = newCode;
  }, []);
  const handleContentClick = React.useCallback((e) => {
    var _a;
    const target = e.target;
    let elementToSelect = null;
    if (target.tagName === "IMG") {
      e.preventDefault();
      e.stopPropagation();
      elementToSelect = target;
    } else if (target.tagName === "TABLE") {
      e.preventDefault();
      e.stopPropagation();
      elementToSelect = target;
    } else if (target.tagName === "TD" || target.tagName === "TH" || target.tagName === "TR" || target.tagName === "TBODY" || target.tagName === "THEAD") {
      e.preventDefault();
      e.stopPropagation();
      elementToSelect = target.closest("table");
    }
    if (elementToSelect) {
      setSelectedElement(elementToSelect);
      const rect = elementToSelect.getBoundingClientRect();
      const containerRect = (_a = contentEditableRef.current) == null ? void 0 : _a.getBoundingClientRect();
      if (containerRect) {
        setResizeHandles({
          x: rect.left - containerRect.left,
          y: rect.top - containerRect.top,
          width: rect.width,
          height: rect.height
        });
      }
    } else {
      setSelectedElement(null);
      setResizeHandles(null);
    }
  }, []);
  const handleDeleteSelected = React.useCallback(() => {
    if (selectedElement) {
      selectedElement.remove();
      setSelectedElement(null);
      setResizeHandles(null);
      if (contentEditableRef.current) {
        sourceCodeRef.current = contentEditableRef.current.innerHTML;
        saveToHistory();
      }
    }
  }, [selectedElement, saveToHistory]);
  const handleReplaceImage = React.useCallback(async (file) => {
    var _a;
    if (!selectedElement || selectedElement.tagName !== "IMG") return;
    try {
      const uFiles = await common.uploadFiles([file], "document");
      const token = common.getToken();
      const payload = {
        ...token,
        "x-timezone": ((_a = token["x-timezone"]) == null ? void 0 : _a.toString()) || "",
        title: file == null ? void 0 : file.name.split(".")[0],
        path: "/",
        is_private: true,
        is_directory: false,
        file_size: file.size,
        is_child: false,
        file_extension: file == null ? void 0 : file.name.split(".")[1],
        type: "image",
        mime_type: file.type,
        url: `${apiConfig$1 == null ? void 0 : apiConfig$1.s3BucketUrl}${uFiles[0]}`
      };
      await api.postV1Drive(payload);
      selectedElement.src = payload.url;
      if (contentEditableRef.current) {
        sourceCodeRef.current = contentEditableRef.current.innerHTML;
        saveToHistory();
      }
    } catch (error2) {
      console.error("Image upload failed:", error2);
      onError == null ? void 0 : onError(error2);
    }
  }, [selectedElement, apiConfig$1, onError, saveToHistory]);
  const handleReplaceImageChange = React.useCallback((e) => {
    var _a;
    const file = (_a = e.target.files) == null ? void 0 : _a[0];
    if (file) {
      handleReplaceImage(file);
    }
  }, [handleReplaceImage]);
  const handleTextSelection = React.useCallback(() => {
    var _a;
    const selection = window.getSelection();
    if (selection && !selection.isCollapsed && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      const rect = range.getBoundingClientRect();
      const containerRect = (_a = contentEditableRef.current) == null ? void 0 : _a.getBoundingClientRect();
      if (containerRect && rect.width > 0) {
        setTextSelectionAnchor({
          x: rect.left + rect.width / 2,
          y: rect.top - 10
        });
        setShowTextToolbar(true);
      }
      let node = selection.anchorNode;
      if ((node == null ? void 0 : node.nodeType) === Node.TEXT_NODE) node = node.parentElement;
      let detectedSize = null;
      let current = node instanceof HTMLElement ? node : null;
      while (current && current !== contentEditableRef.current) {
        if (current.style.fontSize) {
          detectedSize = current.style.fontSize;
          break;
        }
        current = current.parentElement;
      }
      setFontSize(detectedSize ?? "14px");
    } else {
      setShowTextToolbar(false);
      setTextSelectionAnchor(null);
    }
  }, []);
  const handleResizeStart = React.useCallback((e, handle) => {
    e.preventDefault();
    e.stopPropagation();
    if (selectedElement && resizeHandles) {
      resizeStartRef.current = {
        x: e.clientX,
        y: e.clientY,
        width: resizeHandles.width,
        height: resizeHandles.height,
        handle
      };
      document.addEventListener("mousemove", handleResizeMove);
      document.addEventListener("mouseup", handleResizeEnd);
    }
  }, [selectedElement, resizeHandles]);
  const handleResizeMove = React.useCallback((e) => {
    var _a;
    if (!resizeStartRef.current || !selectedElement || !resizeHandles) return;
    const { x, y, width, height, handle } = resizeStartRef.current;
    const deltaX = e.clientX - x;
    const deltaY = e.clientY - y;
    let newWidth = width;
    let newHeight = height;
    if (handle.includes("e")) {
      newWidth = Math.max(50, width + deltaX);
    }
    if (handle.includes("w")) {
      newWidth = Math.max(50, width - deltaX);
    }
    if (handle.includes("s")) {
      newHeight = Math.max(50, height + deltaY);
    }
    if (handle.includes("n")) {
      newHeight = Math.max(50, height - deltaY);
    }
    if (handle.length === 2 && selectedElement.tagName === "IMG") {
      const aspectRatio = width / height;
      newHeight = newWidth / aspectRatio;
    }
    selectedElement.style.width = `${newWidth}px`;
    if (selectedElement.tagName === "IMG" || selectedElement.tagName === "TABLE") {
      selectedElement.style.height = `${newHeight}px`;
    }
    const rect = selectedElement.getBoundingClientRect();
    const containerRect = (_a = contentEditableRef.current) == null ? void 0 : _a.getBoundingClientRect();
    if (containerRect) {
      setResizeHandles({
        x: rect.left - containerRect.left,
        y: rect.top - containerRect.top,
        width: rect.width,
        height: rect.height
      });
    }
  }, [selectedElement, resizeHandles]);
  const handleResizeEnd = React.useCallback(() => {
    document.removeEventListener("mousemove", handleResizeMove);
    document.removeEventListener("mouseup", handleResizeEnd);
    resizeStartRef.current = null;
    if (contentEditableRef.current) {
      sourceCodeRef.current = contentEditableRef.current.innerHTML;
      saveToHistory();
    }
  }, [handleResizeMove, saveToHistory]);
  const handleShowTablePicker = React.useCallback((e) => {
    setTablePickerAnchor(e.currentTarget);
    setShowTablePicker(true);
  }, []);
  const handleInsertTableFromPicker = React.useCallback((rows, cols) => {
    if (contentEditableRef.current) {
      contentEditableRef.current.focus();
    }
    let tableHTML = '<table border="1" style="border-collapse: collapse; width: 100%; margin: 10px 0;">';
    tableHTML += "<tbody>";
    for (let i = 0; i < rows; i++) {
      tableHTML += "<tr>";
      for (let j = 0; j < cols; j++) {
        tableHTML += '<td style="border: 1px solid #ddd; padding: 8px; min-width: 50px;"></td>';
      }
      tableHTML += "</tr>";
    }
    tableHTML += "</tbody></table><p><br></p>";
    document.execCommand("insertHTML", false, tableHTML);
    if (contentEditableRef.current) {
      sourceCodeRef.current = contentEditableRef.current.innerHTML;
      saveToHistory();
    }
    setShowTablePicker(false);
    setTablePickerAnchor(null);
  }, [saveToHistory]);
  const adapter = {
    getData: () => {
      return prepareForSaving(sourceCodeRef.current, handlebarsMapRef.current);
    },
    setData: (newData) => {
      const { html: protectedHtml, map } = prepareForEditing(newData);
      handlebarsMapRef.current = map;
      sourceCodeRef.current = newData;
      if (contentEditableRef.current) {
        contentEditableRef.current.innerHTML = protectedHtml;
      }
    },
    model: {
      insertContent: (fragment) => {
        execCommand("insertHTML", fragment);
      }
    },
    data: {
      processor: {
        toView: (html) => html
      },
      toModel: (html) => html
    }
  };
  React.useImperativeHandle(ref, () => adapter, []);
  React.useEffect(() => {
    if (editorRefProp) {
      editorRefProp.current = adapter;
    }
  }, [editorRefProp]);
  const toolbarCmd = (command, value) => (e) => {
    e.preventDefault();
    execCommand(command, value);
  };
  if (error) {
    return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs("div", { className: "editor-error-container", children: [
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs("div", { className: "editor-error-message", children: [
        "Editor Error: ",
        error.message
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("button", { onClick: () => setError(null), className: "editor-retry-button", children: "Retry" })
    ] });
  }
  return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs("div", { className: "custom-editor-container", children: [
    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(material.Box, { sx: {
      display: "flex",
      alignItems: "center",
      gap: 2,
      px: 2,
      py: 0.5,
      borderBottom: "1px solid #ddd",
      bgcolor: "#f8f9fa",
      fontSize: "13px"
    }, children: [
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { cursor: "pointer", color: "#333" }, children: "Edit" }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { cursor: "pointer", color: "#333" }, children: "View" }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { cursor: "pointer", color: "#333" }, children: "Insert" }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { cursor: "pointer", color: "#333" }, children: "Format" }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { cursor: "pointer", color: "#333" }, children: "Help" })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(material.Box, { sx: {
      display: "flex",
      flexWrap: "wrap",
      gap: 0.5,
      p: 1,
      borderBottom: "1px solid #ddd",
      bgcolor: "#f5f5f5",
      alignItems: "center"
    }, children: [
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: showSourceMode ? "Switch to Visual" : "Switch to Source", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(
        material.Box,
        {
          onClick: handleToggleSource,
          sx: {
            display: "flex",
            alignItems: "center",
            gap: 0.5,
            px: 1,
            py: 0.5,
            cursor: "pointer",
            borderRadius: 1,
            border: "1px solid",
            borderColor: showSourceMode ? "primary.main" : "transparent",
            bgcolor: showSourceMode ? "primary.50" : "transparent",
            color: showSourceMode ? "primary.main" : "text.secondary",
            "&:hover": {
              bgcolor: showSourceMode ? "primary.100" : "grey.200"
            },
            transition: "all 0.15s ease",
            userSelect: "none"
          },
          children: [
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [
              /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("path", { d: "M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", fill: "none" }),
              /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("polyline", { points: "14,2 14,8 20,8", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", fill: "none" }),
              /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("path", { d: "M9 13L7 15L9 17", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" }),
              /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("path", { d: "M15 13L17 15L15 17", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" }),
              /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("line", { x1: "13", y1: "12", x2: "11", y2: "18", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round" })
            ] }),
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { fontSize: "13px", fontWeight: 500 }, children: "Source" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { mx: 0.5 } }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Undo", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onClick: handleUndo, disabled: historyIndex === 0, children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Undo, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Redo", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onClick: handleRedo, disabled: historyIndex === history.length - 1, children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Redo, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { mx: 0.5 } }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
        material.Select,
        {
          value: headingFormat,
          onChange: handleHeadingFormatChange,
          size: "small",
          sx: { minWidth: 100, height: 28, fontSize: "12px" },
          children: HEADING_FORMATS.map((format) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.MenuItem, { value: format.value, children: format.label }, format.value))
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
        material.Select,
        {
          value: fontFamily,
          onChange: handleFontFamilyChange,
          size: "small",
          sx: { minWidth: 120, height: 28, fontSize: "12px" },
          children: FONT_FAMILIES.map((font) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.MenuItem, { value: font, style: { fontFamily: font }, children: font }, font))
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
        material.Select,
        {
          value: fontSize,
          onChange: handleFontSizeChange,
          size: "small",
          sx: { minWidth: 70, height: 28, fontSize: "12px" },
          children: FONT_SIZES.map((size) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.MenuItem, { value: size, children: size }, size))
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { mx: 0.5 } }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Bold", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("bold"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatBold, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Italic", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("italic"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatItalic, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Underline", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("underline"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatUnderlined, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Strikethrough", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("strikeThrough"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatStrikethrough, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Subscript", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("subscript"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Subscript, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Superscript", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("superscript"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Superscript, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { mx: 0.5 } }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Text Color", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
        material.IconButton,
        {
          size: "small",
          onMouseDown: (e) => {
            e.preventDefault();
            setColorPickerState({ anchor: e.currentTarget, type: "text" });
          },
          style: { width: 32, height: 28, border: "1px solid #ddd", borderRadius: "4px", backgroundColor: "white" },
          children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { fontSize: "16px", fontWeight: "bold", color: "#000" }, children: "A" })
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Background Color", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
        material.IconButton,
        {
          size: "small",
          onMouseDown: (e) => {
            e.preventDefault();
            setColorPickerState({ anchor: e.currentTarget, type: "bg" });
          },
          style: { width: 32, height: 28, border: "1px solid #ddd", borderRadius: "4px", backgroundColor: "#fffde7" },
          children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { fontSize: "16px", fontWeight: "bold", color: "#000" }, children: "A" })
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { mx: 0.5 } }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Align Left", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("justifyLeft"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatAlignLeft, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Align Center", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("justifyCenter"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatAlignCenter, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Align Right", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("justifyRight"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatAlignRight, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Justify", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("justifyFull"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatAlignJustify, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { mx: 0.5 } }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Bullet List", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("insertUnorderedList"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatListBulleted, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Numbered List", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("insertOrderedList"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatListNumbered, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { mx: 0.5 } }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Insert Link", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onClick: handleInsertLink, children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Link, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Insert Image", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onClick: () => {
        var _a;
        return (_a = fileInputRef.current) == null ? void 0 : _a.click();
      }, children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Image, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Insert Table", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onClick: handleShowTablePicker, children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.TableChart, { fontSize: "small" }) }) }),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Code", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.IconButton, { size: "small", onMouseDown: toolbarCmd("formatBlock", "<pre>"), children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Code, { fontSize: "small" }) }) })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
      "input",
      {
        ref: fileInputRef,
        type: "file",
        accept: "image/*",
        style: { display: "none" },
        onChange: handleFileChange
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
      "input",
      {
        ref: htmlFileInputRef,
        type: "file",
        accept: ".html,.htm,text/html",
        style: { display: "none" },
        onChange: handleHtmlFileUpload
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
      "input",
      {
        ref: replaceImageInputRef,
        type: "file",
        accept: "image/*",
        style: { display: "none" },
        onChange: handleReplaceImageChange
      }
    ),
    showSourceMode ? /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
      "textarea",
      {
        value: sourceCode,
        onChange: handleSourceCodeChange,
        className: "custom-editor-source",
        style: {
          width: "100%",
          minHeight: "300px",
          padding: "16px",
          border: "none",
          outline: "none",
          fontFamily: "Courier New, monospace",
          fontSize: "13px",
          lineHeight: "1.5",
          resize: "vertical"
        }
      }
    ) : /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs("div", { style: { position: "relative" }, children: [
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
        "div",
        {
          ref: contentEditableRef,
          contentEditable: true,
          className: "editor-content",
          onInput: handleInput,
          onPaste: handlePaste,
          onClick: handleContentClick,
          onMouseUp: handleTextSelection,
          onKeyUp: handleTextSelection,
          style: {
            minHeight: "300px",
            padding: "16px",
            border: "1px solid #ddd",
            borderTop: "none",
            outline: "none",
            fontFamily: "inherit",
            fontSize: "inherit",
            lineHeight: "1.6",
            backgroundColor: "white"
          },
          ...rest
        }
      ),
      selectedElement && resizeHandles && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(
        "div",
        {
          style: {
            position: "absolute",
            left: resizeHandles.x,
            top: resizeHandles.y,
            width: resizeHandles.width,
            height: resizeHandles.height,
            border: "2px solid #1976d2",
            pointerEvents: "none",
            zIndex: 1e3
          },
          children: [
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(
              material.Box,
              {
                sx: {
                  position: "absolute",
                  top: -36,
                  left: 0,
                  display: "flex",
                  gap: 0.5,
                  bgcolor: "white",
                  border: "1px solid #ddd",
                  borderRadius: 1,
                  p: 0.25,
                  boxShadow: 2,
                  pointerEvents: "auto"
                },
                children: [
                  selectedElement.tagName === "IMG" && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Replace Image", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
                    material.IconButton,
                    {
                      size: "small",
                      onClick: () => {
                        var _a;
                        return (_a = replaceImageInputRef.current) == null ? void 0 : _a.click();
                      },
                      sx: { width: 22, height: 22 },
                      children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.SwapHoriz, { sx: { fontSize: 14 } })
                    }
                  ) }),
                  selectedElement.tagName === "TABLE" && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(jsxRuntime.jsxRuntimeExports.Fragment, { children: [
                    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Add Row", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
                      material.IconButton,
                      {
                        size: "small",
                        onClick: () => {
                          const tbody = selectedElement.querySelector("tbody");
                          if (tbody) {
                            const colCount = selectedElement.querySelectorAll("tr:first-child td, tr:first-child th").length || 1;
                            const tr = document.createElement("tr");
                            for (let i = 0; i < colCount; i++) {
                              const td = document.createElement("td");
                              td.style.cssText = "border: 1px solid #ddd; padding: 8px; min-width: 50px;";
                              tr.appendChild(td);
                            }
                            tbody.appendChild(tr);
                            if (contentEditableRef.current) sourceCodeRef.current = contentEditableRef.current.innerHTML;
                          }
                        },
                        sx: { width: 22, height: 22 },
                        children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.AddCircleOutline, { sx: { fontSize: 14 } })
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Delete Row", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
                      material.IconButton,
                      {
                        size: "small",
                        onClick: () => {
                          const rows = selectedElement.querySelectorAll("tbody tr");
                          if (rows.length > 1) {
                            rows[rows.length - 1].remove();
                            if (contentEditableRef.current) sourceCodeRef.current = contentEditableRef.current.innerHTML;
                          }
                        },
                        sx: { width: 22, height: 22 },
                        children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.RemoveCircleOutline, { sx: { fontSize: 14 } })
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Add Column", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
                      material.IconButton,
                      {
                        size: "small",
                        onClick: () => {
                          selectedElement.querySelectorAll("tr").forEach((tr) => {
                            const isHeader = tr.closest("thead") !== null;
                            const cell = document.createElement(isHeader ? "th" : "td");
                            cell.style.cssText = "border: 1px solid #ddd; padding: 8px; min-width: 50px;";
                            tr.appendChild(cell);
                          });
                          if (contentEditableRef.current) sourceCodeRef.current = contentEditableRef.current.innerHTML;
                        },
                        sx: { width: 22, height: 22 },
                        children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.AddCircleOutline, { sx: { fontSize: 14, transform: "rotate(90deg)" } })
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Delete Column", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
                      material.IconButton,
                      {
                        size: "small",
                        onClick: () => {
                          var _a;
                          const allRows = selectedElement.querySelectorAll("tr");
                          const colCount = ((_a = allRows[0]) == null ? void 0 : _a.children.length) || 0;
                          if (colCount > 1) {
                            allRows.forEach((tr) => {
                              if (tr.lastElementChild) tr.removeChild(tr.lastElementChild);
                            });
                            if (contentEditableRef.current) sourceCodeRef.current = contentEditableRef.current.innerHTML;
                          }
                        },
                        sx: { width: 22, height: 22 },
                        children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.RemoveCircleOutline, { sx: { fontSize: 14, transform: "rotate(90deg)" } })
                      }
                    ) })
                  ] }),
                  /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Delete", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
                    material.IconButton,
                    {
                      size: "small",
                      onClick: handleDeleteSelected,
                      sx: {
                        width: 22,
                        height: 22,
                        color: "#f44336",
                        "&:hover": { bgcolor: "#ffebee" }
                      },
                      children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.Close, { sx: { fontSize: 14 } })
                    }
                  ) })
                ]
              }
            ),
            ["nw", "n", "ne", "e", "se", "s", "sw", "w"].map((handle) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              "div",
              {
                onMouseDown: (e) => handleResizeStart(e, handle),
                style: {
                  position: "absolute",
                  width: 8,
                  height: 8,
                  backgroundColor: "#1976d2",
                  border: "1px solid white",
                  pointerEvents: "auto",
                  cursor: `${handle}-resize`,
                  ...handle === "nw" && { top: -4, left: -4 },
                  ...handle === "n" && { top: -4, left: "50%", transform: "translateX(-50%)" },
                  ...handle === "ne" && { top: -4, right: -4 },
                  ...handle === "e" && { top: "50%", right: -4, transform: "translateY(-50%)" },
                  ...handle === "se" && { bottom: -4, right: -4 },
                  ...handle === "s" && { bottom: -4, left: "50%", transform: "translateX(-50%)" },
                  ...handle === "sw" && { bottom: -4, left: -4 },
                  ...handle === "w" && { top: "50%", left: -4, transform: "translateY(-50%)" }
                }
              },
              handle
            ))
          ]
        }
      ),
      showTextToolbar && textSelectionAnchor && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(
        material.Box,
        {
          sx: {
            position: "fixed",
            left: textSelectionAnchor.x,
            top: textSelectionAnchor.y,
            transform: "translate(-50%, -100%)",
            display: "flex",
            gap: 0.5,
            bgcolor: "#333",
            color: "white",
            borderRadius: 1,
            p: 0.5,
            boxShadow: 3,
            zIndex: 1e4
          },
          children: [
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Bold", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              material.IconButton,
              {
                size: "small",
                onMouseDown: toolbarCmd("bold"),
                sx: { color: "white", width: 28, height: 28 },
                children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatBold, { fontSize: "small" })
              }
            ) }),
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Italic", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              material.IconButton,
              {
                size: "small",
                onMouseDown: toolbarCmd("italic"),
                sx: { color: "white", width: 28, height: 28 },
                children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatItalic, { fontSize: "small" })
              }
            ) }),
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Underline", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              material.IconButton,
              {
                size: "small",
                onMouseDown: toolbarCmd("underline"),
                sx: { color: "white", width: 28, height: 28 },
                children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(iconsMaterial.FormatUnderlined, { fontSize: "small" })
              }
            ) }),
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Divider, { orientation: "vertical", flexItem: true, sx: { bgcolor: "rgba(255,255,255,0.2)", mx: 0.5 } }),
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Text Color", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              material.IconButton,
              {
                size: "small",
                sx: { color: "white", width: 28, height: 28 },
                onMouseDown: (e) => {
                  e.preventDefault();
                  setColorPickerState({ anchor: e.currentTarget, type: "text" });
                },
                children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx("span", { style: { fontSize: "14px", fontWeight: "bold" }, children: "A" })
              }
            ) }),
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Tooltip, { title: "Font Size", children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              material.Select,
              {
                size: "small",
                defaultValue: "14px",
                onChange: handleFontSizeChange,
                sx: {
                  color: "white",
                  height: 28,
                  minWidth: 70,
                  "& .MuiOutlinedInput-notchedOutline": { border: "none" },
                  "& .MuiSvgIcon-root": { color: "white" }
                },
                children: FONT_SIZES.map((size) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.MenuItem, { value: size, children: size }, size))
              }
            ) })
          ]
        }
      )
    ] }),
    colorPickerState && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
      material.Popover,
      {
        open: true,
        anchorEl: colorPickerState.anchor,
        onClose: () => setColorPickerState(null),
        disableAutoFocus: true,
        disableEnforceFocus: true,
        anchorOrigin: { vertical: "bottom", horizontal: "left" },
        transformOrigin: { vertical: "top", horizontal: "left" },
        children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Box, { sx: { p: 1 }, children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Box, { sx: { display: "grid", gridTemplateColumns: "repeat(8, 20px)", gap: "3px" }, children: PRESET_COLORS.map((color) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
          material.Box,
          {
            onMouseDown: (e) => {
              e.preventDefault();
              if (colorPickerState.type === "text") {
                execCommand("foreColor", color);
              } else {
                execCommand("hiliteColor", color);
              }
              setColorPickerState(null);
            },
            sx: {
              width: 20,
              height: 20,
              bgcolor: color,
              cursor: "pointer",
              border: "1px solid rgba(0,0,0,0.15)",
              borderRadius: "2px",
              "&:hover": { transform: "scale(1.3)", zIndex: 1, position: "relative" }
            }
          },
          color
        )) }) })
      }
    ),
    showTablePicker && tablePickerAnchor && /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(jsxRuntime.jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
        material.Box,
        {
          onClick: () => {
            setShowTablePicker(false);
            setTablePickerAnchor(null);
          },
          sx: {
            position: "fixed",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            zIndex: 9998
          }
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(TablePicker, {})
    ] })
  ] });
});
CustomEditor.displayName = "CustomEditor";
exports.CustomEditor = CustomEditor;
exports.default = CustomEditor;
//# sourceMappingURL=custom-editor-D31nXWJC.js.map
