const O = {
  latex: [
    { name: "Fraction", formula: "\\frac{a}{b}", description: "Simple fraction" },
    { name: "Square Root", formula: "\\sqrt{x}", description: "Square root" },
    { name: "Power", formula: "x^{2}", description: "Exponent/power" },
    { name: "Subscript", formula: "x_{sub}", description: "Subscript" },
    { name: "Integral", formula: "\\int_{a}^{b} f(x) \\, dx", description: "Definite integral" },
    { name: "Summation", formula: "\\sum_{i=1}^{n} x_{i}", description: "Summation" },
    { name: "Limit", formula: "\\lim_{x \\to 0} f(x)", description: "Limit" },
    { name: "Derivative", formula: "\\frac{d}{dx} f(x)", description: "Derivative" },
    { name: "Matrix 2x2", formula: "\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}", description: "2x2 matrix" },
    { name: "System", formula: "\\begin{cases} x + y = 1 \\\\ 2x - y = 0 \\end{cases}", description: "System of equations" }
  ],
  mathml: [
    { name: "Fraction", formula: "<mfrac><mi>a</mi><mi>b</mi></mfrac>", description: "Simple fraction" },
    { name: "Square Root", formula: "<msqrt><mi>x</mi></msqrt>", description: "Square root" },
    { name: "Power", formula: "<msup><mi>x</mi><mn>2</mn></msup>", description: "Exponent/power" },
    { name: "Subscript", formula: "<msub><mi>x</mi><mi>sub</mi></msub>", description: "Subscript" },
    { name: "Parentheses", formula: '<mfenced open="(" close=")"><mi>a</mi><mo>+</mo><mi>b</mi></mfenced>', description: "Grouped expression" }
  ]
};
let T = null, B = null, H = !1, y = null, m = null;
const k = '[data-theme="dark"], .dark, .editora-theme-dark', K = () => new Promise((e, t) => {
  if (window.katex) {
    e(window.katex);
    return;
  }
  if (H) {
    const s = setInterval(() => {
      window.katex && (clearInterval(s), e(window.katex));
    }, 100);
    return;
  }
  H = !0;
  const r = document.createElement("link");
  r.rel = "stylesheet", r.href = "https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css", document.head.appendChild(r);
  const l = document.createElement("script");
  l.src = "https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js", l.onload = () => e(window.katex), l.onerror = t, document.head.appendChild(l);
}), N = () => {
  const e = window.getSelection();
  if (!e || e.rangeCount === 0) return null;
  const t = e.getRangeAt(0).startContainer;
  return (t.nodeType === Node.ELEMENT_NODE ? t : t.parentElement)?.closest(".rte-content, .editora-content") || null;
}, U = (e) => e ? e.nodeType === Node.ELEMENT_NODE ? e : e.parentElement : null, R = (e) => U(e)?.closest('.rte-content, .editora-content, [contenteditable="true"]') || null, W = (e, t, r) => {
  if (t !== r) {
    if (typeof window.execEditorCommand == "function") {
      window.execEditorCommand("recordDomTransaction", e, t, r);
      return;
    }
    if (typeof window.executeEditorCommand == "function")
      try {
        window.executeEditorCommand("recordDomTransaction", { editor: e, beforeHTML: t, afterHTML: r });
      } catch {
      }
  }
}, G = (e) => {
  if (!(e instanceof Element)) return null;
  const t = e.closest(".math-formula, .math-block");
  return t instanceof HTMLElement ? t : null;
}, h = () => {
  m && (m.classList.remove("math-object-selected"), m.removeAttribute("data-rte-selected-object"), m = null);
}, X = (e) => {
  if (m === e) return;
  h(), m = e, e.classList.add("math-object-selected"), e.setAttribute("data-rte-selected-object", "true");
  const t = window.getSelection();
  if (!t) return;
  const r = document.createRange();
  r.selectNode(e), t.removeAllRanges(), t.addRange(r);
}, Z = (e, t) => {
  const r = window.getSelection();
  if (!r) return;
  const l = document.createRange();
  t && t.parentNode === e ? l.setStartBefore(t) : (l.selectNodeContents(e), l.collapse(!1)), l.collapse(!0), r.removeAllRanges(), r.addRange(l);
}, Q = (e) => {
  if (e.childNodes.length > 0) return;
  const t = document.createElement("p");
  t.appendChild(document.createElement("br")), e.appendChild(t);
}, J = () => {
  if (!m || !m.isConnected)
    return h(), !1;
  const e = m, t = R(e);
  if (!t)
    return h(), !1;
  const r = t.innerHTML, l = e.nextSibling;
  e.remove(), Q(t), h(), Z(t, l);
  const s = t.innerHTML;
  return W(t, r, s), t.dispatchEvent(new window.Event("input", { bubbles: !0 })), r !== s;
}, V = () => {
  if (document.getElementById("math-object-selection-styles")) return;
  const e = document.createElement("style");
  e.id = "math-object-selection-styles", e.textContent = `
    .math-object-selected {
      outline: 2px solid #2563eb !important;
      outline-offset: 2px;
      box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.18);
    }
  `, document.head.appendChild(e);
}, Y = () => {
  typeof window > "u" || window.__mathPluginObjectSelectionInitialized || (window.__mathPluginObjectSelectionInitialized = !0, V(), document.addEventListener("pointerdown", (e) => {
    const t = G(e.target);
    if (!t) {
      e.target?.closest?.(".math-dialog-overlay") || h();
      return;
    }
    e.preventDefault(), R(t)?.focus(), X(t);
  }, !0), document.addEventListener("keydown", (e) => {
    if (m) {
      if (e.key === "Escape") {
        h();
        return;
      }
      e.key !== "Backspace" && e.key !== "Delete" || (e.preventDefault(), e.stopPropagation(), J());
    }
  }, !0));
}, ee = (e) => {
  if ((e || N())?.closest(k)) return !0;
  const r = window.getSelection();
  if (r && r.rangeCount > 0) {
    const s = r.getRangeAt(0).startContainer;
    if ((s.nodeType === Node.ELEMENT_NODE ? s : s.parentElement)?.closest(k)) return !0;
  }
  return document.activeElement?.closest(k) ? !0 : document.body.matches(k) || document.documentElement.matches(k);
}, j = async (e, t) => {
  const r = t || B?.closest(".rte-content, .editora-content") || N() || y;
  y = r || null;
  const l = window.getSelection();
  if (l && l.rangeCount > 0) {
    const n = l.getRangeAt(0);
    T = r && r.contains(n.commonAncestorContainer) ? n.cloneRange() : null;
  }
  await K();
  const s = ee(r), o = s ? {
    overlay: "rgba(0, 0, 0, 0.62)",
    dialogBg: "#1f2937",
    border: "#3b4657",
    panelBg: "#222d3a",
    fieldBg: "#111827",
    fieldBorder: "#4b5563",
    text: "#e2e8f0",
    muted: "#94a3b8",
    templateBtnBg: "#273244",
    templateBtnHover: "#334155",
    templateBtnText: "#dbe7f7",
    templateSubText: "#9fb0c6",
    previewBg: "#111827",
    previewText: "#cbd5e1",
    cancelBg: "#334155",
    cancelText: "#e2e8f0",
    cancelBorder: "#4b5563",
    insertBg: "#3b82f6",
    insertHover: "#2563eb",
    invalid: "#f87171"
  } : {
    overlay: "rgba(0, 0, 0, 0.5)",
    dialogBg: "#ffffff",
    border: "#e1e5e9",
    panelBg: "#f8f9fa",
    fieldBg: "#ffffff",
    fieldBorder: "#ced4da",
    text: "#1f2937",
    muted: "#6c757d",
    templateBtnBg: "#ffffff",
    templateBtnHover: "#f8f9fa",
    templateBtnText: "#1f2937",
    templateSubText: "#6c757d",
    previewBg: "#f8f9fa",
    previewText: "#6c757d",
    cancelBg: "#ffffff",
    cancelText: "#1f2937",
    cancelBorder: "#ced4da",
    insertBg: "#007bff",
    insertHover: "#0069d9",
    invalid: "#cc0000"
  }, d = document.createElement("div");
  d.className = "math-dialog-overlay", d.style.cssText = `position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: ${o.overlay}; display: flex; align-items: center; justify-content: center; z-index: 99999;`;
  const c = document.createElement("div");
  c.style.cssText = `background: ${o.dialogBg}; border: 1px solid ${o.border}; border-radius: 8px; width: 90%; max-width: 600px; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2); color: ${o.text};`;
  let u = e?.format || "latex", S = e?.formula || "", _ = e?.inline !== !1, b = null, L = "";
  c.innerHTML = `
    <div style="display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-bottom: 1px solid ${o.border}; background: ${o.panelBg};">
      <h2 style="margin: 0; font-size: 18px; font-weight: 600; color: ${o.text};">${e ? "Edit" : "Insert"} Math Formula</h2>
      <button class="close-btn" style="background: none; border: none; font-size: 28px; cursor: pointer; color: ${o.muted}; padding: 0; width: 30px; height: 30px; line-height: 1;">×</button>
    </div>
    
    <div style="padding: 20px; overflow-y: auto; flex: 1;">
      <div style="margin-bottom: 20px;">
        <label style="display: block; font-weight: 600; margin-bottom: 8px; font-size: 14px; color: ${o.text};">Format:</label>
        <div style="display: flex; gap: 16px;">
          <label style="cursor: pointer; color: ${o.text};"><input type="radio" name="format" value="latex" ${u === "latex" ? "checked" : ""} style="margin-right: 6px;"> LaTeX</label>
          <label style="cursor: pointer; color: ${o.text};"><input type="radio" name="format" value="mathml" ${u === "mathml" ? "checked" : ""} style="margin-right: 6px;"> MathML</label>
        </div>
      </div>

      <div style="margin-bottom: 20px;">
        <label style="display: block; font-weight: 600; margin-bottom: 8px; font-size: 14px; color: ${o.text};">Quick Templates:</label>
        <div id="templates-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; max-height: 200px; overflow-y: auto;"></div>
      </div>

      <div style="margin-bottom: 20px;">
        <label style="cursor: pointer; color: ${o.text};"><input type="checkbox" id="inline-cb" ${_ ? "checked" : ""} style="margin-right: 8px;"> Inline math</label>
      </div>

      <div style="margin-bottom: 20px;">
        <label style="display: block; font-weight: 600; margin-bottom: 8px; font-size: 14px; color: ${o.text};">Formula:</label>
        <textarea id="formula-input" rows="4" style="width: 100%; min-height: 112px; padding: 10px 12px; border: 1px solid ${o.fieldBorder}; border-radius: 6px; font-family: 'Courier New', monospace; font-size: 14px; line-height: 1.45; background: ${o.fieldBg}; color: ${o.text}; box-sizing: border-box; overflow-x: hidden; overflow-y: auto; resize: vertical;">${S}</textarea>
      </div>

      <div style="margin-bottom: 20px;">
        <label style="display: block; font-weight: 600; margin-bottom: 8px; font-size: 14px; color: ${o.text};">Preview:</label>
        <div id="preview-area" style="min-height: 60px; padding: 15px; border: 1px solid ${o.fieldBorder}; border-radius: 4px; background: ${o.previewBg}; display: flex; align-items: center; justify-content: center; color: ${o.previewText};"></div>
      </div>
    </div>

    <div style="display: flex; justify-content: flex-end; gap: 10px; padding: 16px 20px; border-top: 1px solid ${o.border}; background: ${o.panelBg};">
      <button class="cancel-btn" style="padding: 10px 20px; background: ${o.cancelBg}; color: ${o.cancelText}; border: 1px solid ${o.cancelBorder}; border-radius: 4px; cursor: pointer; font-size: 14px;">Cancel</button>
      <button id="insert-btn" style="padding: 10px 20px; background: ${o.insertBg}; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;" disabled>${e ? "Update" : "Insert"}</button>
    </div>
  `, d.appendChild(c), document.body.appendChild(d);
  const p = c.querySelector("#formula-input"), v = c.querySelector("#preview-area"), $ = c.querySelector("#templates-grid"), z = c.querySelectorAll('input[name="format"]'), I = c.querySelector("#inline-cb"), f = c.querySelector("#insert-btn"), g = c.querySelector(".close-btn"), w = c.querySelector(".cancel-btn"), P = (n) => encodeURIComponent(n), q = (n) => {
    try {
      return decodeURIComponent(n);
    } catch {
      return n;
    }
  }, C = () => {
    const n = O[u];
    $.innerHTML = n.map((i) => `
      <button type="button" data-formula="${P(i.formula)}" title="${i.description}" style="padding: 8px; border: 1px solid ${o.fieldBorder}; border-radius: 4px; background: ${o.templateBtnBg}; cursor: pointer; text-align: left; transition: background-color 0.16s ease;">
        <div style="font-weight: 600; font-size: 12px; color: ${o.templateBtnText};">${i.name}</div>
        <div style="font-size: 10px; color: ${o.templateSubText}; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${i.formula.substring(0, 20)}...</div>
      </button>
    `).join("");
  }, F = () => {
    const n = p.value.trim(), i = `${u}:${n}`;
    if (i !== L) {
      if (L = i, !n) {
        v.innerHTML = `<span style="color: ${o.previewText};">Enter a formula to see preview</span>`, f.disabled = !0;
        return;
      }
      f.disabled = !1;
      try {
        if (u === "latex") {
          const a = window.katex;
          v.innerHTML = a.renderToString(n, { displayMode: !1, throwOnError: !1 });
        } else
          n.trim().startsWith("<math") ? v.innerHTML = n : v.innerHTML = `<math xmlns="http://www.w3.org/1998/Math/MathML" display="inline">${n}</math>`;
      } catch {
        v.innerHTML = `<span style="color: ${o.invalid};">Invalid formula</span>`;
      }
    }
  }, M = () => {
    b !== null && cancelAnimationFrame(b), b = requestAnimationFrame(() => {
      b = null, F();
    });
  }, A = (n) => {
    n.key === "Escape" && (n.preventDefault(), n.stopPropagation(), E());
  }, E = () => {
    document.removeEventListener("keydown", A, !0), b !== null && (cancelAnimationFrame(b), b = null), d.parentNode && d.parentNode.removeChild(d);
  };
  g.onmouseover = () => {
    g.style.color = "#f8fafc", g.style.background = s ? "#334155" : "#e5e7eb", g.style.borderRadius = "4px";
  }, g.onmouseout = () => {
    g.style.color = o.muted, g.style.background = "none";
  }, w.onmouseover = () => {
    w.style.background = s ? "#475569" : "#f3f4f6";
  }, w.onmouseout = () => {
    w.style.background = o.cancelBg;
  }, f.onmouseover = () => {
    f.disabled || (f.style.background = o.insertHover);
  }, f.onmouseout = () => {
    f.style.background = o.insertBg;
  }, $.addEventListener("mouseover", (n) => {
    const a = n.target.closest("button[data-formula]");
    a && (a.style.background = o.templateBtnHover);
  }), $.addEventListener("mouseout", (n) => {
    const a = n.target.closest("button[data-formula]");
    a && (a.style.background = o.templateBtnBg);
  }), $.addEventListener("click", (n) => {
    const a = n.target.closest("button[data-formula]");
    a && (p.value = q(a.getAttribute("data-formula") || ""), S = p.value, M());
  });
  const D = () => {
    const n = p.value.trim();
    if (!n) return;
    const i = { formula: n, format: u, inline: I.checked }, a = i.inline ? document.createElement("span") : document.createElement("div");
    if (a.className = i.inline ? "math-formula" : "math-block", a.setAttribute("data-math-formula", n), a.setAttribute("data-math-format", u), a.contentEditable = "false", a.style.cssText = i.inline ? "background: #f0f8ff; border: 1px solid #b8daff; border-radius: 4px; padding: 2px 6px; margin: 0 2px; color: #004085; display: inline-block; cursor: pointer;" : "background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px; padding: 12px; margin: 8px 0; text-align: center; display: block; cursor: pointer;", u === "latex") {
      const x = window.katex;
      try {
        a.innerHTML = x.renderToString(n, {
          displayMode: !i.inline,
          throwOnError: !1
        });
      } catch {
        a.textContent = i.inline ? `$${n}$` : `$$${n}$$`;
      }
    } else if (n.trim().startsWith("<math"))
      a.innerHTML = n;
    else {
      const x = `<math xmlns="http://www.w3.org/1998/Math/MathML" display="${i.inline ? "inline" : "block"}">${n}</math>`;
      a.innerHTML = x;
    }
    if (B)
      B.replaceWith(a);
    else if (T)
      T.deleteContents(), T.insertNode(a);
    else if (y && y.isConnected) {
      const x = document.createRange();
      x.selectNodeContents(y), x.collapse(!1), x.insertNode(a);
    }
    (a.closest(".rte-content, .editora-content") || y)?.dispatchEvent(new Event("input", { bubbles: !0 })), E();
  };
  g.addEventListener("click", E), w.addEventListener("click", E), f.addEventListener("click", D), d.addEventListener("click", (n) => {
    n.target === d && E();
  }), document.addEventListener("keydown", A, !0), z.forEach((n) => {
    n.addEventListener("change", (i) => {
      u = i.target.value, L = "", C(), M();
    });
  }), p.addEventListener("input", () => {
    S = p.value, M();
  }), p.addEventListener("keydown", (n) => {
    (n.ctrlKey || n.metaKey) && n.key === "Enter" && (n.preventDefault(), D());
  }), C(), M(), p.focus();
};
if (typeof window < "u" && !window.__mathPluginDoubleClickInitialized) {
  window.__mathPluginDoubleClickInitialized = !0;
  const e = (r) => {
    const s = r.target.closest(".math-formula, .math-block");
    if (s) {
      r.preventDefault(), r.stopPropagation(), r.stopImmediatePropagation(), h(), B = s;
      const o = s.getAttribute("data-math-formula") || "", d = s.getAttribute("data-math-format") || "latex", c = s.classList.contains("math-formula");
      j({ formula: o, format: d, inline: c });
    }
  }, t = () => {
    document.addEventListener("dblclick", e, { capture: !0 });
  };
  document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", t) : setTimeout(t, 100);
}
const ne = () => ({
  name: "math",
  init: Y,
  toolbar: [
    {
      label: "Insert Math",
      command: "insertMath",
      icon: '<svg width="24" height="24" focusable="false"><path fill-rule="evenodd" clip-rule="evenodd" d="M9 4.8c.1-.5.5-.8 1-.8h10a1 1 0 1 1 0 2h-9.2L8.3 19.2a1 1 0 0 1-1.7.4l-3.4-4.2a1 1 0 0 1 1.6-1.2l2 2.5L9 4.8Zm9.7 5.5c.4.4.4 1 0 1.4L17 13.5l1.8 1.8a1 1 0 0 1-1.4 1.4L15.5 15l-1.8 1.8a1 1 0 0 1-1.4-1.4l1.8-1.8-1.8-1.8a1 1 0 0 1 1.4-1.4l1.8 1.8 1.8-1.8a1 1 0 0 1 1.4 0Z"></path></svg>'
    }
  ],
  commands: {
    insertMath: (e, t) => {
      const r = t?.contentElement instanceof HTMLElement ? t.contentElement : null;
      return j(void 0, r), !0;
    }
  },
  keymap: {
    "Mod-Shift-m": "insertMath"
  }
});
export {
  ne as MathPlugin
};
