// CRITICAL: This MUST be the first import to intercept fetch BEFORE Supabase captures it
import { setLogger } from '@/utils/logger/apiLoggerBootstrap';
import '@/utils/logger/globalLogger';
import { isOrgAccessError } from '@/utils/orgErrorHandler';


import React from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { HelmetProvider } from 'react-helmet-async'
import App from './App.tsx'
import './index.css'

// Initialize additional loggers
import { initClickLogger } from '@/utils/logger';
import { initPerformanceLogger } from '@/utils/logger/performanceLogger';
import { logger } from '@/utils/logger/standardLogger';
import { initLoggingCategoryConfig, isLoggingCategoryEnabled } from '@/utils/logger/loggingCategoryConfig';

// Connect API logger to standard logger for SigNoz forwarding
setLogger(logger);

// Load the admin-configurable logging category toggles (Logging Settings
// page, system_settings-backed), then only attach the click/performance
// listeners if their category is actually enabled. Even when disabled,
// standardLogger.ts's central gate already blocks any resulting log from
// reaching SigNoz -- but attaching a document-wide click listener and
// PerformanceObservers unconditionally still costs real browser overhead
// for no benefit when the category is off. Deferring attachment until the
// config resolves avoids that cost entirely for the common (disabled)
// case, rather than just suppressing the log after the fact.
initLoggingCategoryConfig().then(() => {
  if (isLoggingCategoryEnabled('clicks')) {
    initClickLogger();
  }
  if (isLoggingCategoryEnabled('performance')) {
    initPerformanceLogger();
  }
});

// Global error handlers - Only capture REAL errors, not developer console.error() calls
// 1. Runtime errors (uncaught exceptions)
window.onerror = (message, source, lineno, colno, error) => {
  logger.runtimeError(error ?? new Error(String(message)), source, lineno, colno);
  return false; // Don't prevent default error handling
};

// 2. Unhandled promise rejections
window.onunhandledrejection = (event) => {
  logger.unhandledRejection(event.reason);
};

// Note: We do NOT intercept console.error/console.warn because those are
// used by developers for debugging and would flood the logging system.
// 
// Valid errors are captured through:
// - window.onerror (uncaught runtime errors)
// - window.onunhandledrejection (unhandled promise rejections)
// - ErrorBoundary component (React component crashes)
// - Explicit logger.error() / logger.dbError() / logger.rpcError() calls
// - API interceptor (fetch failures with 4xx/5xx status codes)
// - Auth service (login failures with proper error codes)

// Log app startup

// App mounted on current build successfully — clear the stale-chunk
// auto-reload guard so a future genuine deploy can trigger one again.
sessionStorage.removeItem('stale-chunk-reload-attempted');

const root = document.getElementById('root')
if (!root) {
  throw new Error('Root element not found')
}

createRoot(root).render(
  <React.StrictMode>
    <HelmetProvider>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </HelmetProvider>
  </React.StrictMode>
);
