// Polyfill for Promise.withResolvers (ES2024) - needed for Electron 22
if (!(Promise as any).withResolvers) {
  (Promise as any).withResolvers = function <T>() {
    let resolve!: (value: T | PromiseLike<T>) => void;
    let reject!: (reason?: any) => void;
    const promise = new Promise<T>((res, rej) => {
      resolve = res;
      reject = rej;
    });
    return { promise, resolve, reject };
  };
}

// Polyfill for URL.parse (Node.js url.parse compatibility) - needed for Electron 22
// This creates a global url object with parse method for pdfjs-dist compatibility
if (typeof URL !== "undefined" && !(URL as any).parse) {
  (URL as any).parse = function (urlString: string) {
    try {
      const urlObj = new URL(urlString, typeof window !== "undefined" ? window.location.href : undefined);
      const params: Record<string, string> = {};
      urlObj.searchParams.forEach((value, key) => {
        params[key] = value;
      });
      return {
        protocol: urlObj.protocol.replace(":", ""),
        slashes: true,
        auth: urlObj.username && urlObj.password ? `${urlObj.username}:${urlObj.password}` : null,
        host: urlObj.host,
        hostname: urlObj.hostname,
        hash: urlObj.hash || null,
        search: urlObj.search || null,
        query: params,
        pathname: urlObj.pathname,
        path: urlObj.pathname + urlObj.search,
        href: urlObj.href,
        port: urlObj.port || null,
      };
    } catch (_err) {
      const match = urlString.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
      if (!match) return null;
      const params: Record<string, string> = {};
      if (match[7]) {
        new URLSearchParams(match[7]).forEach((value, key) => {
          params[key] = value;
        });
      }
      return {
        protocol: match[2] || null,
        slashes: !!match[3],
        auth: null,
        host: match[4] || null,
        hostname: match[4] ? match[4].split(":")[0] : null,
        hash: match[8] || null,
        search: match[6] || null,
        query: params,
        pathname: match[5] || null,
        path: (match[5] || "") + (match[6] || ""),
        href: urlString,
        port: match[4] && match[4].includes(":") ? match[4].split(":")[1] : null,
      };
    }
  };
}

import React from "react";
import ReactDOM from "react-dom/client";
import { HashRouter } from "react-router-dom";
import App from "./App";
import { initPdfWorker } from "./utils/pdfWorker";

// 在应用启动时初始化 PDF Worker，确保只初始化一次
initPdfWorker();

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <HashRouter>
      <App />
    </HashRouter>
  </React.StrictMode>
);
