import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import { ClerkProvider, useAuth } from '@clerk/clerk-react'
import { ConvexProviderWithClerk } from 'convex/react-clerk'
import * as Sentry from '@sentry/react'
import { convex } from './lib/convex.js'
import './index.css'

// ─── Sentry: arrancar solo si VITE_SENTRY_DSN está definido ──────────────────
// Para activar: agrega VITE_SENTRY_DSN=https://xxx@sentry.io/yyy en .env.local
// y sube source maps en producción con el Vite plugin de Sentry.
// Pendiente del usuario: obtener DSN en https://sentry.io → Project settings → Client Keys
if (import.meta.env.VITE_SENTRY_DSN) {
    Sentry.init({
        dsn: import.meta.env.VITE_SENTRY_DSN,
        environment: import.meta.env.MODE,
        tracesSampleRate: import.meta.env.PROD ? 0.2 : 1.0,
        // Source maps: configurar @sentry/vite-plugin en vite.config.js
        // (ver nota al pie en convex/email/send.ts)
    });
    console.log('[SENTRY] Inicializado en entorno:', import.meta.env.MODE);
}

// Providers
import { AuthProvider } from './contexts/AuthContext.jsx'
import { AppProvider } from './contexts/AppContext.jsx'
import { NotificationProvider } from './components/NotificationSystem.jsx'
import ErrorBoundary from './components/ErrorBoundary.jsx'

// Pages
import Landing from './views/Landing.jsx'
import SignIn from './views/SignIn.jsx'
import SignUp from './views/signup/SignUp.jsx'
import Onboarding from './views/Onboarding.jsx'
import App from './App.jsx'
import AuthGuard from './components/AuthGuard.jsx'
import InviteAccept from './views/InviteAccept.jsx'

// Get Clerk publishable key
const CLERK_PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY

if (!CLERK_PUBLISHABLE_KEY) {
    throw new Error("Missing Clerk Publishable Key")
}

// Hydrate the accent color the user picked during onboarding so the rest of
// the app uses it from the first paint.
try {
    const prefs = JSON.parse(localStorage.getItem('konty_workspace_prefs') || '{}');
    if (prefs.brandColor) {
        document.documentElement.dataset.accent = prefs.brandColor;
    }
} catch {}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
      <ClerkProvider
        publishableKey={CLERK_PUBLISHABLE_KEY}
        signInUrl="/sign-in"
        signUpUrl="/sign-up"
        signInFallbackRedirectUrl="/dashboard"
        signUpFallbackRedirectUrl="/dashboard"
        signInForceRedirectUrl="/dashboard"
        signUpForceRedirectUrl="/dashboard"
      >
       <ConvexProviderWithClerk client={convex} useAuth={useAuth}>
        <NotificationProvider>
          <AuthProvider>
            <AppProvider>
              <Router>
    <ErrorBoundary>
                <AuthGuard>
                  <Routes>
                    {/* Public Routes */}
                    <Route path="/" element={<Landing />} />
                    <Route path="/sign-in" element={<SignIn />} />
                    <Route path="/sign-up" element={<SignUp />} />
                  
                    {/* Onboarding Route */}
                    <Route path="/onboarding" element={<Onboarding />} />

                    {/* Invite accept — público (el componente maneja auth interno) */}
                    <Route path="/invite/:token" element={<InviteAccept />} />
                  
                    {/* Protected Routes */}
                    <Route path="/dashboard/*" element={<App />} />
                  
                    {/* Catch all route - redirect to landing */}
                    <Route path="*" element={<Navigate to="/" replace />} />
                  </Routes>
                </AuthGuard>
    </ErrorBoundary>
              </Router>
            </AppProvider>
          </AuthProvider>
        </NotificationProvider>
       </ConvexProviderWithClerk>
      </ClerkProvider>
  </React.StrictMode>,
)