import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import './i18n/config';
import App from './App';
import './styles/index.css';

// CRITICAL: Make React globally available for AG Grid cellRenderers
// Must be set BEFORE any AG Grid rendering occurs!
if (typeof window !== 'undefined') {
  (window as any).React = React;
}

// TanStack Query setup
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30000, // 30 sec
      gcTime: 300000, // 5 min (formerly cacheTime)
      refetchOnWindowFocus: false,
      retry: 1,
    },
  },
});

// WordPress config from window object
declare global {
  interface Window {
    varihuConfig: {
      restUrl: string;
      nonce: string;
      locale: string;
      ajaxUrl: string; // ✅ SECURITY FIX: Dynamic admin-ajax.php URL from WordPress
      pluginUrl: string;
      version: string;
      currentUser: {
        id: number;
        name: string;
        email: string;
      };
    };
    // WordPress Media Library
    wp: {
      media: (options?: any) => any;
    };
    // Underscore.js
    _: any;
  }
}

const rootElement = document.getElementById('variation-hub-app');

if (rootElement) {
  ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
      <QueryClientProvider client={queryClient}>
        <App />
        <ReactQueryDevtools initialIsOpen={false} />
      </QueryClientProvider>
    </React.StrictMode>
  );
}
