
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import '@/lib/setupLogging'
import '@/services/rum/webVitalsInit'
import { supabase } from '@/lib/supabase';
import { productionMonitor } from '@/utils/productionMonitoring'
import { getCurrentDatabaseTarget } from '@/utils/supabaseApi'
import { debugLog } from '@/utils/debug'

// Debug: Show current database target
const currentDatabase = getCurrentDatabaseTarget();
debugLog('🎯 Application initialized with database target:', currentDatabase);

// Note: We intentionally do NOT expose the supabase client on window.
// Doing so would let any XSS payload or browser extension steal the user's
// JWT or make authenticated calls. Import from '@/lib/supabase' instead.
if (typeof window !== 'undefined') {
  debugLog('🔍 Production monitoring initialized');
}

// Track API request timing for production monitoring
const trackFetch = (url: string, options: RequestInit | undefined, originalFetch: typeof fetch) => {
  const start = performance.now();
  return originalFetch(url, options)
    .then((res) => {
      const duration = performance.now() - start;
      try {
        const endpoint = new URL(url, window.location.origin).pathname;
        productionMonitor.trackApiRequest(endpoint, duration, res.ok, {
          status: res.status,
          method: options?.method || 'GET'
        });
      } catch (_e) { /* monitoring best-effort */ }
      return res;
    })
    .catch((err) => {
      const duration = performance.now() - start;
      try {
        const endpoint = new URL(url, window.location.origin).pathname;
        productionMonitor.trackApiRequest(endpoint, duration, false, {
          error: err?.message || String(err),
          method: options?.method || 'GET'
        });
      } catch (_e) { /* monitoring best-effort */ }
      throw err;
    });
};

// API-only mode: block direct database access, allow auth/functions/rpc
if (typeof window !== 'undefined') {
  const originalFetch = window.fetch;
  const BLOCKED_PATTERN = '/rest/v1/';
  const ALLOWED_PATTERNS = ['/auth/v1/', '/functions/v1/', '/rest/v1/rpc/'];
  const isProduction = window.location.hostname.endsWith('.lovable.app') && !window.location.hostname.includes('-preview--');

  window.fetch = (url, options) => {
    if (typeof url === 'string') {
      const isAllowed = ALLOWED_PATTERNS.some(p => url.includes(p));

      if (!isAllowed && url.includes(BLOCKED_PATTERN)) {
        // Silent throw — exposing the message in console reveals architecture details.
        // The thrown error is still caught by the calling code for debugging.
        throw new Error('Use API endpoints only');
      }

      // Only add performance tracking overhead in production
      if (isAllowed && isProduction) {
        return trackFetch(url, options as RequestInit, originalFetch);
      }
    }
    return originalFetch(url, options);
  };
  debugLog('🔒 API-only mode enforced: All database access must go through Edge Functions');
}

// Warm the active-language translation chunk during idle time so t() is ready
// before any route renders. We pick the language up-front from URL/localStorage
// to avoid loading both — single-language architecture means we never need both.
if (typeof window !== 'undefined') {
  const warm = () => {
    try {
      const urlLang = new URLSearchParams(window.location.search).get('lang')
        || new URLSearchParams(window.location.search).get('lan');
      const stored = localStorage.getItem('preferred-language');
      const lang = (urlLang === 'es' || urlLang === 'en') ? urlLang
        : (stored === 'es' || stored === 'en') ? stored
        : (navigator.language?.toLowerCase().startsWith('es') ? 'es' : 'en');
      if (lang === 'es') import('@/constants/translations.es').catch(() => {});
      else import('@/constants/translations.en').catch(() => {});
    } catch { /* best-effort */ }
  };
  if ('requestIdleCallback' in window) {
    (window as any).requestIdleCallback(warm, { timeout: 2000 });
  } else {
    setTimeout(warm, 200);
  }
}

// Register service worker for production menu caching
if (typeof window !== 'undefined' && 'serviceWorker' in navigator) {
  const isProduction = window.location.hostname.endsWith('.lovable.app') || window.location.hostname.endsWith('.vercel.app');
  if (isProduction) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js').catch(() => {});
    });
  }
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)
