import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ClerkProvider, ClerkLoaded } from '@clerk/clerk-react';
import { plPL } from '@clerk/localizations';
import App from './App';
import './styles/globals.css';
import './styles/dashboard.css';
import { ErrorBoundary } from './components/ErrorBoundary';

import * as Sentry from "@sentry/react";
import posthog from 'posthog-js';

const queryClient = new QueryClient();

if (import.meta.env.VITE_SENTRY_DSN) {
  Sentry.init({
    dsn: import.meta.env.VITE_SENTRY_DSN,
    integrations: [
      Sentry.browserTracingIntegration(),
      Sentry.replayIntegration(),
    ],
    tracesSampleRate: 1.0,
    tracePropagationTargets: ["localhost", /^https:\/\/grantforge-api\.onrender\.com/],
    replaysSessionSampleRate: 0.1,
    replaysOnErrorSampleRate: 1.0,
  });
}

const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY;
const POSTHOG_KEY = import.meta.env.VITE_POSTHOG_KEY;

if (!PUBLISHABLE_KEY) {
  console.warn("Wymagany jest VITE_CLERK_PUBLISHABLE_KEY w pliku .env");
}

if (POSTHOG_KEY) {
  posthog.init(POSTHOG_KEY, {
    api_host: 'https://eu.posthog.com',
    person_profiles: 'identified_only',
    autocapture: false,
    capture_pageview: true,
    loaded: function(ph) {
      if (window.location.hostname === 'localhost') ph.opt_out_capturing();
    }
  });
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <ErrorBoundary>
      <ClerkProvider publishableKey={PUBLISHABLE_KEY || "missing_key"} afterSignOutUrl="/" localization={plPL}>
        <QueryClientProvider client={queryClient}>
          <ClerkLoaded>
            <App />
          </ClerkLoaded>
        </QueryClientProvider>
      </ClerkProvider>
    </ErrorBoundary>
  </React.StrictMode>
);
