import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { isNativePlatform, isAndroid, isIOS } from "@/lib/capacitor-utils";
import { initGlobalErrorLogger } from "@/lib/global-error-logger";

// Initialize global error logger BEFORE anything else (captures JS Eval errors)
initGlobalErrorLogger();

import { prefetchComplete } from "@/lib/prefetch-signals";
import { setupRealtimeCacheInvalidation } from "@/lib/realtime-cache-invalidation";

// Start the global realtime cache invalidation listener exactly once for the
// app lifecycle. The function has an internal `isSubscribed` guard, so even if
// React StrictMode double-invokes effects this remains a single subscription.
setupRealtimeCacheInvalidation();

async function initializeApp() {
  // Configure native platform basics (non-blocking)
  if (isNativePlatform()) {
    const [
      nativeImageUtils,
      iosWebpDebug,
      splashScreenModule,
      statusBarModule,
    ] = await Promise.all([
      import("@/lib/native-image-utils"),
      import("@/lib/ios-webp-debug"),
      import("@capacitor/splash-screen"),
      import("@capacitor/status-bar"),
    ]);

    const { purgeImageCacheIfNeeded, installNativeImageRewriteGuards } = nativeImageUtils;
    const { installIOSWebpDebugHook } = iosWebpDebug;
    const { SplashScreen } = splashScreenModule;
    const { StatusBar, Style } = statusBarModule;

    document.body.classList.add('native-app');
    if (isAndroid()) {
      document.body.classList.add('android');
    }
    if (isIOS()) {
      document.body.classList.add('ios');
    }

    // Install native iOS image URL rewrite guards early
    installNativeImageRewriteGuards();
    installIOSWebpDebugHook();
    // Show splash screen on both platforms
    try {
      await SplashScreen.show({
        showDuration: 0,  // Don't auto-hide
        autoHide: false,
      });
      console.log('[Init] SplashScreen shown manually');
    } catch (error) {
      console.warn('[Init] Failed to show SplashScreen:', error);
    }
    
    // Configure Status Bar (platform-specific)
    try {
      if (isIOS()) {
        await StatusBar.setOverlaysWebView({ overlay: false });
        await StatusBar.setStyle({ style: Style.Light });
        console.log('[Init] iOS Status bar configured (overlay: false)');
      }
      // Android status bar is handled natively in MainActivity.java
    } catch (error) {
      console.warn('[Init] Status bar config failed:', error);
    }
  }

  // Purge stale cached images (WEBP cleanup) - non-blocking, native only
  if (isNativePlatform()) {
    const { purgeImageCacheIfNeeded } = await import("@/lib/native-image-utils");
    purgeImageCacheIfNeeded().catch(() => {});
  }
  
  // Render the app immediately
  createRoot(document.getElementById("root")!).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );

  queueMicrotask(() => {
    console.log('[GlobalError] POST-BOOT marker');
  });
  
  // Hide splash screen AFTER prefetch is complete (with minimum display time and timeout fallback)
  if (isNativePlatform()) {
    const [{ SplashScreen }] = await Promise.all([
      import("@capacitor/splash-screen"),
    ]);

    const minDisplayTime = new Promise(resolve => setTimeout(resolve, 1000));
    
    // Track if prefetch completed to suppress spurious timeout warning
    let prefetchCompleted = false;
    prefetchComplete.then(() => { prefetchCompleted = true; });
    
    const timeoutFallback = new Promise(resolve => setTimeout(() => {
      if (!prefetchCompleted) {
        console.warn('[Splash] Timeout reached (6s), proceeding without full prefetch');
      }
      resolve(undefined);
    }, 6000));
    
    console.log('[Splash] Waiting for prefetch and minimum display time...');
    
    // Wait for both prefetch AND minimum time, OR timeout fallback
    await Promise.race([
      Promise.all([prefetchComplete, minDisplayTime]),
      timeoutFallback
    ]);
    
    // Wait for safe area insets (critical for layout)
    let attempts = 0;
    while (attempts < 50) {
      const top = getComputedStyle(document.documentElement)
        .getPropertyValue('--safe-area-inset-top');
      
      if (top && top !== '0px' && !top.includes('undefined')) {
        console.log('[Init] Safe area ready:', top);
        break;
      }
      
      await new Promise(resolve => setTimeout(resolve, 20));
      attempts++;
    }
    
    // Hide splash screen with fade
    await SplashScreen.hide({ fadeOutDuration: 300 });
    console.log('[Splash] Hidden after prefetch complete');
    
    // Background verification tasks (non-blocking)
    setTimeout(async () => {
      // Verify layout
      const topBar = document.querySelector('[data-layout="top-bar"]');
      const bottomNav = document.querySelector('[data-layout="bottom-nav"]');
      const fixedElements = Array.from(document.querySelectorAll('*'))
        .filter(el => {
          const s = getComputedStyle(el as HTMLElement);
          if (!s || s.position !== 'fixed') return false;
          const top = s.top || '';
          const isTopZero = top === '0px' || top.startsWith('0');
          const hasBackground = s.backgroundColor !== 'rgba(0, 0, 0, 0)';
          const z = parseInt(s.zIndex || '0', 10);
          return isTopZero && hasBackground && z >= 0;
        });

      if (topBar && bottomNav) {
        const topRect = (topBar as HTMLElement).getBoundingClientRect();
        const bottomRect = (bottomNav as HTMLElement).getBoundingClientRect();
        
        console.log('[Init] Layout verification:', {
          topBar: { top: topRect.top, height: topRect.height },
          bottomNav: { bottom: window.innerHeight - bottomRect.bottom, height: bottomRect.height },
          windowHeight: window.innerHeight
        });
      }
      
      // Scan for unwanted fixed elements with visible backgrounds (skip intentional layout elements)
      const fixedTopElements = fixedElements.filter(el => {
        const htmlEl = el as HTMLElement;
        // Skip our intentional layout elements
        if (htmlEl.dataset.layout) return false;
        const s = getComputedStyle(htmlEl);
        const top = s.top || '';
        const isTopZero = top === '0px' || top.startsWith('0');
        return isTopZero;
      });

      if (fixedTopElements.length > 0) {
        console.warn('[Layout Scan] Found unexpected fixed@top elements:');
        fixedTopElements.forEach(el => {
          const s = getComputedStyle(el as HTMLElement);
          console.log(' - Element:', {
            tag: el.tagName,
            class: (el as HTMLElement).className,
            id: (el as HTMLElement).id,
            top: s.top,
            z: s.zIndex,
          });
        });
      }
    }, 100);
  }
}

// Start initialization
initializeApp();
