import { Suspense } from "react";
import Script from "next/script";
import OnlyOfficeClientPage from "./OnlyOfficeClientPage";

export const dynamic = "force-dynamic";

const ONLYOFFICE_EARLY_PATCH = `
(function () {
  try {
    if (window.__MNOTE_ONLYOFFICE_EARLYPATCHED__) return;
    window.__MNOTE_ONLYOFFICE_EARLYPATCHED__ = true;

    // 说明：ONLYOFFICE 在部分环境下会触发 DOMException(NotFoundError)，
    // 常见于 removeChild/insertBefore/replaceChild 等 DOM 操作。
    // 该异常会被 Next.js 视为“客户端异常”并白屏，但通常不影响编辑器继续使用。
    // 这里尽可能早地打补丁，避免异常冒泡导致整页崩溃。
    try {
      var origRemoveChild = Node.prototype.removeChild;
      Node.prototype.removeChild = function (child) {
        try {
          return origRemoveChild.call(this, child);
        } catch (e) {
          if (e && e.name === "NotFoundError") return child;
          throw e;
        }
      };
    } catch (e) {}

    try {
      var origInsertBefore = Node.prototype.insertBefore;
      Node.prototype.insertBefore = function (newNode, referenceNode) {
        try {
          return origInsertBefore.call(this, newNode, referenceNode);
        } catch (e) {
          if (e && e.name === "NotFoundError") return newNode;
          throw e;
        }
      };
    } catch (e) {}

    try {
      var origReplaceChild = Node.prototype.replaceChild;
      Node.prototype.replaceChild = function (newChild, oldChild) {
        try {
          return origReplaceChild.call(this, newChild, oldChild);
        } catch (e) {
          if (e && e.name === "NotFoundError") return oldChild;
          throw e;
        }
      };
    } catch (e) {}

    // 说明：记录错误，便于远程白屏时回溯（不会阻断页面）。
    try {
      window.__MNOTE_ONLYOFFICE_ERRLOG__ = window.__MNOTE_ONLYOFFICE_ERRLOG__ || [];
      var push = function (payload) {
        try {
          window.__MNOTE_ONLYOFFICE_ERRLOG__.push(payload);
          window.localStorage.setItem("mnote_onlyoffice_last_error", JSON.stringify(payload));
        } catch (e) {}
      };

      window.addEventListener(
        "error",
        function (e) {
          try {
            push({
              kind: "error",
              message: String(e.message || ""),
              filename: String(e.filename || ""),
              lineno: Number(e.lineno || 0),
              colno: Number(e.colno || 0),
              name: String((e.error && e.error.name) || ""),
            });
          } catch (err) {}
        },
        true
      );

      window.addEventListener(
        "unhandledrejection",
        function (e) {
          try {
            var r = e.reason;
            push({
              kind: "rejection",
              message: String((r && (r.message || r)) || ""),
              name: String((r && r.name) || ""),
            });
          } catch (err) {}
        },
        true
      );
    } catch (e) {}
  } catch (e) {}
})();
`.trim();

export default function OnlyOfficePage() {
  return (
    <Suspense
      fallback={
        <div className="flex h-screen items-center justify-center bg-slate-50 text-sm text-gray-600">
          正在加载 ONLYOFFICE…
        </div>
      }
    >
      <Script
        id="mnote-onlyoffice-earlypatch"
        strategy="beforeInteractive"
        dangerouslySetInnerHTML={{ __html: ONLYOFFICE_EARLY_PATCH }}
      />
      <OnlyOfficeClientPage />
    </Suspense>
  );
}
