import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import * as Sentry from "@sentry/react";
import { router } from './routes';
import { Toaster } from './components/ui/toaster';
import { GoogleTagManager } from './components/analytics/GoogleTagManager';
import { RudderstackAnalytics } from './components/analytics/RudderstackAnalytics';
import './index.css';

// GTM ID - Substitua pelo seu ID real do GTM
const GTM_ID = import.meta.env.VITE_GTM_ID;

// Rudderstack Config
const RUDDERSTACK_WRITE_KEY = import.meta.env.VITE_RUDDERSTACK_WRITE_KEY;
const RUDDERSTACK_DATA_PLANE_URL = import.meta.env.VITE_RUDDERSTACK_DATA_PLANE_URL;

// Inicialização do Sentry
Sentry.init({
  dsn: "https://6c15876055bf4a860c1b63a8e4e7ca65@o544400.ingest.us.sentry.io/4508626073092096",
  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration(),
  ],
  // Configurações de ambiente
  environment: import.meta.env.MODE,
  // Tracing
  tracesSampleRate: import.meta.env.DEV ? 1.0 : 0.2, // 100% em dev, 20% em prod
  tracePropagationTargets: [
    "localhost",
    "historiasmagicas.netlify.app",
    "bsjlbnyslxzsdwxvkaap.supabase.co"
  ],
  // Session Replay
  replaysSessionSampleRate: import.meta.env.DEV ? 1.0 : 0.1, // 100% em dev, 10% em prod
  replaysOnErrorSampleRate: 1.0,
  // Configurações adicionais
  beforeSend(event) {
    // Não enviar eventos em desenvolvimento
    if (import.meta.env.DEV) {
      return null;
    }
    return event;
  },
});

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5,
      gcTime: 1000 * 60 * 30,
      refetchOnWindowFocus: false,
    },
  },
});

function Root() {
  return (
    <StrictMode>
      <GoogleTagManager gtmId={GTM_ID} />
      <RudderstackAnalytics 
        writeKey={RUDDERSTACK_WRITE_KEY} 
        dataPlaneUrl={RUDDERSTACK_DATA_PLANE_URL} 
      />
      <QueryClientProvider client={queryClient}>
        <RouterProvider router={router} />
        <Toaster />
      </QueryClientProvider>
    </StrictMode>
  );
}

createRoot(document.getElementById('root')!).render(<Root />);