import React from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import { Toaster } from "@/components/ui";
import "./styles/main.css";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      retry: 1,
    },
  },
});

/**
 * Initialize the React app in the WordPress admin container.
 * Wrapped in try-catch to prevent breaking other WordPress scripts.
 */
function initApp(): void {
  try {
    const container = document.getElementById("opus-price-builder-app");

    // Only initialize if our container exists (we're on the right page)
    if (!container) {
      return;
    }

    const root = createRoot(container);

    root.render(
      <React.StrictMode>
        <QueryClientProvider client={queryClient}>
          <App />
          <Toaster />
        </QueryClientProvider>
      </React.StrictMode>
    );
  } catch (error) {
    console.error("[Opus Price Builder] Failed to initialize:", error);
  }
}

// Wait for DOM to be ready, with error boundary
try {
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initApp);
  } else {
    initApp();
  }
} catch (error) {
  console.error("[Opus Price Builder] Initialization error:", error);
}
