import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import { performanceMonitor } from './utils/performanceMonitor'
import { productionOptimizations } from './utils/productionOptimizations'
import { logger } from "./utils/logger";
import { activateGlobalMonitoring, trackPerformanceMetrics } from './utils/monitoringActivation';
import { performStartupValidation } from './utils/apiKeyValidator';
import posthog from 'posthog-js';

// Preview and loop safety guards
try {
  const path = window.location.pathname;
  const inPreview = (() => { try { return window.self !== window.top; } catch { return true; } })();

  // Lightweight loop detector per-path
  const key = `__loop_guard_${path}`;
  const blockKey = `__loop_block_${path}`;
  const now = Date.now();
  let state = { last: 0, count: 0 } as any;
  try { state = JSON.parse(sessionStorage.getItem(key) || 'null') || { last: 0, count: 0 }; } catch {}
  if (now - state.last < 1500) state.count += 1; else state.count = 1;
  state.last = now;
  sessionStorage.setItem(key, JSON.stringify(state));
  if (state.count >= 6) sessionStorage.setItem(blockKey, '1');

  // Patch navigation churn on /snapshot
  if (path === '/snapshot') {
    const origPush = history.pushState.bind(history);
    const origReplace = history.replaceState.bind(history);
    history.pushState = function (data: any, title: string, url?: string | URL | null) {
      try {
        const target = url ? new URL(url as any, window.location.href) : null;
        if (!target || target.href === window.location.href) {
          logger.warn('[LoopGuard] Ignored pushState to same URL');
          return;
        }
      } catch {}
      return origPush(data as any, title, url as any);
    } as any;
    history.replaceState = function (data: any, title: string, url?: string | URL | null) {
      try {
        const target = url ? new URL(url as any, window.location.href) : null;
        if (!target || target.href === window.location.href) {
          logger.warn('[LoopGuard] Ignored replaceState to same URL');
          return;
        }
      } catch {}
      return origReplace(data as any, title, url as any);
    } as any;

    const loc: any = window.location as any;
    const origAssign = loc.assign?.bind(window.location);
    const origReplaceLoc = loc.replace?.bind(window.location);
    loc.assign = (url: string) => {
      try { if (new URL(url, window.location.href).href === window.location.href) { logger.warn('[LoopGuard] Ignored location.assign to same URL'); return; } } catch {}
      return origAssign(url);
    };
    loc.replace = (url: string) => {
      try { if (new URL(url, window.location.href).href === window.location.href) { logger.warn('[LoopGuard] Ignored location.replace to same URL'); return; } } catch {}
      return origReplaceLoc(url);
    };
  }

  if (inPreview) {
  // Block programmatic reloads inside preview
  const origReload = window.location.reload.bind(window.location);
  (window as { [key: string]: any })['__reload_patched'] = true;
  window.location.reload = () => {
    logger.warn('[PreviewGuard] Reload blocked in preview');
    // Optionally: debounce to single reload
    // setTimeout(() => origReload(), 1500)
  };
}

(window as { [key: string]: any })['__LOOP_BLOCK_ACTIVE__'] = sessionStorage.getItem(blockKey) === '1' && path === '/snapshot';
} catch {}

// Initialize PostHog with client-side key (PostHog keys are public/publishable)
// PostHog client keys starting with 'phc_' are designed for browser use
const POSTHOG_KEY = import.meta.env.VITE_POSTHOG_KEY;

function initializePostHog() {
  // Skip PostHog initialization if key is not configured
  if (!POSTHOG_KEY) {
    logger.warn('PostHog disabled - VITE_POSTHOG_KEY not configured. Analytics will not be collected.');
    // Expose a no-op posthog for code that expects window.posthog
    window.posthog = {
      capture: () => {},
      identify: () => {},
      reset: () => {},
      onFeatureFlags: () => {},
      isFeatureEnabled: () => false,
      getFeatureFlag: () => null,
    } as any;
    return;
  }

  try {
    posthog.init(POSTHOG_KEY, {
      api_host: 'https://app.posthog.com',
      loaded: () => {
        if (import.meta.env.DEV) {
          logger.info('PostHog initialized successfully');
        }
      },
      autocapture: true,
      capture_pageview: true,
      capture_pageleave: true
    });
    
    // Make posthog available globally
    window.posthog = posthog;
    
    // Confirm initialization
    setTimeout(() => {
      if (window.posthog?.capture) {
        window.posthog.capture('posthog_initialized', {
          timestamp: Date.now()
        });
      }
    }, 1000);
    
  } catch (error) {
    logger.warn('PostHog initialization failed:', error);
  }
}

// Initialize PostHog synchronously (no longer async - key is build-time)
initializePostHog();

if ((window as { [key: string]: any })['__LOOP_BLOCK_ACTIVE__']) {
  const root = document.getElementById('root')!;
  root.innerHTML = '<div style="min-height:100vh;display:flex;align-items:center;justify-content:center;font-family:system-ui,sans-serif;padding:24px;text-align:center">\
  <div>\
    <div style="font-size:20px;font-weight:600;margin-bottom:8px">Preview stabilized</div>\
    <div style="opacity:0.7;margin-bottom:16px">We paused auto-reloads on this page to prevent a loop. Continue when ready.</div>\
    <button id="loop-continue" style="padding:10px 14px;border-radius:8px;border:1px solid #e5e7eb;background:#111827;color:#fff;cursor:pointer">Continue</button>\
  </div>\
</div>';
  document.getElementById('loop-continue')?.addEventListener('click', () => {
    try { sessionStorage.removeItem(`__loop_block_${window.location.pathname}`); } catch {}
    window.location.reload();
  });
} else {
  // Initialize performance monitoring (critical for timing)
  const endRender = performanceMonitor.markComponentRender('App');
  
  // Render app first (critical path)
  createRoot(document.getElementById("root")!).render(<App />);
  
  // Complete render timing
  endRender();
  
  // Defer non-critical startup tasks to break dependency chains
  // Uses requestIdleCallback when available, falls back to setTimeout
  const deferNonCritical = (callback: () => void) => {
    if ('requestIdleCallback' in window) {
      requestIdleCallback(callback, { timeout: 2000 });
    } else {
      setTimeout(callback, 100);
    }
  };

  // Defer startup validation and monitoring to after initial render
  deferNonCritical(() => {
    performStartupValidation();
    activateGlobalMonitoring();
    trackPerformanceMetrics();
    productionOptimizations.getOptimizationStatus();
  });
  
  // Import audit runner for global access (already deferred via dynamic import)
  import('./utils/auditRunner');
  
  // Enable corporate language detection in development
  if (import.meta.env.DEV) {
    import('./utils/corporateLanguageDetector').then(({ enableCorporateLanguageDetection }) => {
      enableCorporateLanguageDetection();
    });
  }
  
  // Expose CAI verification service to window for console testing
  import('./services/cai').then(({ caiVerificationService }) => {
    (window as any).caiVerificationService = caiVerificationService;
  });
}

