import React from "react";
import { createRoot } from "react-dom/client";
import { HelmetProvider } from 'react-helmet-async';
import "@/lib/i18n"; // Initialize i18n before App loads
import App from "./App.tsx";
import "./index.css";
import { registerPWA } from "@/lib/pwa/register";
import { installGlobalErrorHandlers } from "@/lib/observability/globalHandlers";

// M15-lite: install sanitized global error + promise-rejection capture
// before render so early-boot errors are covered. No network in dev or when
// VITE_OBSERVABILITY_ENABLED is not "true".
installGlobalErrorHandlers();

// Capacitor initialization - deferred to avoid React conflicts
const initializeCapacitor = async () => {
  // Only run in browser environment
  if (typeof window === 'undefined') return;
  
  // Check if running in Capacitor native app
  const isNative = !!(window as any).Capacitor?.isNativePlatform?.();
  if (!isNative) return;
  
  const platform = (window as any).Capacitor?.getPlatform?.() || 'web';
  
  // Set CSS variables for safe area insets
  const root = document.documentElement;
  root.style.setProperty('--sat', 'env(safe-area-inset-top, 0px)');
  root.style.setProperty('--sab', 'env(safe-area-inset-bottom, 0px)');
  root.style.setProperty('--sal', 'env(safe-area-inset-left, 0px)');
  root.style.setProperty('--sar', 'env(safe-area-inset-right, 0px)');
  root.style.setProperty('--keyboard-height', '0px');
  
  // Add capacitor class to body for conditional styling
  document.body.classList.add('capacitor-app');
  
  if (platform === 'ios') {
    document.body.classList.add('ios-app');
  } else if (platform === 'android') {
    document.body.classList.add('android-app');
  }
  
  console.log(`[Capacitor] Running on ${platform}`);
  
  // Initialize native plugins with dynamic imports
  try {
    const { StatusBar, Style } = await import('@capacitor/status-bar');
    await StatusBar.setStyle({ style: Style.Dark });
    await StatusBar.setBackgroundColor({ color: '#0F0F0F' });
  } catch (error) {
    console.debug('StatusBar setup skipped');
  }
  
  try {
    const { SplashScreen } = await import('@capacitor/splash-screen');
    setTimeout(() => SplashScreen.hide(), 500);
  } catch (error) {
    console.debug('SplashScreen hide skipped');
  }
  
  try {
    const { App: CapApp } = await import('@capacitor/app');
    CapApp.addListener('backButton', ({ canGoBack }) => {
      if (canGoBack) {
        window.history.back();
      } else {
        CapApp.minimizeApp();
      }
    });
  } catch (error) {
    console.debug('App plugin setup skipped');
  }
  
  try {
    const { Keyboard } = await import('@capacitor/keyboard');
    Keyboard.addListener('keyboardWillShow', (info) => {
      document.body.classList.add('keyboard-open');
      document.body.style.setProperty('--keyboard-height', `${info.keyboardHeight}px`);
    });
    Keyboard.addListener('keyboardWillHide', () => {
      document.body.classList.remove('keyboard-open');
      document.body.style.setProperty('--keyboard-height', '0px');
    });
  } catch (error) {
    console.debug('Keyboard handling setup skipped');
  }
};

// Web/PWA keyboard detection via visualViewport API
const initializeWebKeyboard = () => {
  if (typeof window === 'undefined') return;
  if ((window as any).Capacitor?.isNativePlatform?.()) return; // Skip for native apps
  
  const visualViewport = window.visualViewport;
  if (!visualViewport) return;
  
  let lastHeight = visualViewport.height;
  const threshold = 150; // Minimum height change to detect keyboard
  
  visualViewport.addEventListener('resize', () => {
    const heightDiff = lastHeight - visualViewport.height;
    
    if (heightDiff > threshold) {
      // Keyboard opened
      document.body.classList.add('keyboard-open');
      document.body.style.setProperty('--keyboard-height', `${heightDiff}px`);
    } else if (heightDiff < -threshold) {
      // Keyboard closed
      document.body.classList.remove('keyboard-open');
      document.body.style.setProperty('--keyboard-height', '0px');
    }
    
    lastHeight = visualViewport.height;
  });
};

// M10: Single guarded PWA registration point.
// Refuses to register in dev / iframe / Lovable preview / localhost /
// Capacitor / `?sw=off`, and cleans up any stale /sw.js in those contexts.
registerPWA();

// Render the app first, then initialize Capacitor
createRoot(document.getElementById("root")!).render(
  <HelmetProvider>
    <App />
  </HelmetProvider>
);

// Initialize Capacitor AFTER React is mounted
setTimeout(() => {
  initializeCapacitor();
  initializeWebKeyboard();
}, 0);
