import { MutationCache, QueryCache, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";

import { App } from "./app";
import { ErrorBoundary } from "./shared/components/ErrorBoundary";
import { createConsoleLogger } from "./shared/utils/logger";
import "./styles.css";

const logger = createConsoleLogger();

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: true,
      retry: 1,
      staleTime: 5000,
    },
  },
  mutationCache: new MutationCache({
    onError: (error: Error, _variables, _context, mutation) => {
      logger.error("mutation failed", {
        error: error.message,
        mutationKey: mutation.options.mutationKey,
      });
    },
  }),
  queryCache: new QueryCache({
    onError: (error: Error, query) => {
      logger.error("query failed", { error: error.message, queryKey: query.queryKey });
    },
  }),
});

const rootElement = document.getElementById("root");

if (!rootElement) {
  throw new Error("找不到前端挂载节点 #root");
}

createRoot(rootElement).render(
  <StrictMode>
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
        {import.meta.env["DEV"] && <ReactQueryDevtools initialIsOpen={false} />}
      </QueryClientProvider>
    </ErrorBoundary>
  </StrictMode>,
);

window.onerror = (message, source, lineno, colno, error) => {
  logger.error("未处理的异常", {
    colno,
    error: error instanceof Error ? error.message : String(error),
    lineno,
    message,
    source,
  });
};

window.addEventListener("unhandledrejection", (event: PromiseRejectionEvent) => {
  const msg = event.reason instanceof Error ? event.reason.message : String(event.reason);
  logger.error("unhandled rejection", { reason: msg });
});
