import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { persistQueryClient } from '@tanstack/react-query-persist-client';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import './index.css';
import App from './App';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      gcTime: 24 * 60 * 60 * 1000, // 24 hours for persistence
      retry: 3,
      refetchOnWindowFocus: false,
    },
    mutations: {
      retry: 1,
    },
  },
});

// Enable query persistence with localStorage using modern approach
persistQueryClient({
  queryClient,
  persister: {
    persistClient: client => {
      try {
        const clientState = JSON.stringify({
          timestamp: Date.now(),
          clientState: client,
        });
        localStorage.setItem('advisorvoice-query-cache', clientState);
      } catch {
        // Failed to persist query cache - continue without caching
      }
    },
    restoreClient: () => {
      try {
        const cached = localStorage.getItem('advisorvoice-query-cache');
        if (!cached) return;

        const { timestamp, clientState } = JSON.parse(cached);
        const isExpired = Date.now() - timestamp > 24 * 60 * 60 * 1000; // 24 hours

        return isExpired ? undefined : clientState;
      } catch {
        // Failed to restore cache - clear it and continue
        localStorage.removeItem('advisorvoice-query-cache');
        return undefined;
      }
    },
    removeClient: () => {
      localStorage.removeItem('advisorvoice-query-cache');
    },
  },
});

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  </StrictMode>
);
