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

// 🔥 BUILD MARKER v8 - This WILL show (not stripped by terser)
(window as any).__KAZASWAP_BUILD__ = "v8-" + Date.now();
// Use console.warn which is NOT stripped
console.warn("🚀 KAZASWAP BUILD v8 DEPLOYED - Chat debug + Cache bust");

// 🔥 CRITICAL: Handle chunk loading failures (cache invalidation issues)
// When chunk hashes change after deployment, old cached HTML tries to load old chunks
// This catches those errors and forces a hard reload to get fresh HTML
window.addEventListener('error', (event) => {
  const isChunkLoadError =
    event.message?.includes('Failed to fetch dynamically imported module') ||
    event.message?.includes('Importing a module script failed') ||
    event.message?.includes('error loading dynamically imported module');

  if (isChunkLoadError) {
    console.warn('🔄 Chunk loading failed - forcing page reload to clear cache');
    // Use sessionStorage to prevent infinite reload loops
    const reloadKey = 'chunk-reload-attempted';
    if (!sessionStorage.getItem(reloadKey)) {
      sessionStorage.setItem(reloadKey, 'true');
      window.location.reload();
    } else {
      // Clear the flag after 10 seconds to allow retry later
      setTimeout(() => sessionStorage.removeItem(reloadKey), 10000);
    }
  }
});

// 🚀 PERFORMANCE: Disable console.logs in development for smoother animations
// Comment out the next 3 lines to re-enable console logs
// if (import.meta.env.DEV) {
//   console.log = () => {};
// }

// Debug in development only
if (import.meta.env.DEV) {
  console.log('1. Main.tsx is running');
  
  // Debug visibility tracking
  document.addEventListener('visibilitychange', () => {
    console.log('👁️ Tab visibility:', document.visibilityState);
  });
}

// 🧹 CRITICAL: Cache/SW cleanup - Run immediately in development to prevent InvalidStateError
// Service Workers can cause translation sync issues and white screen crashes
const isDevEnvironment = location.hostname.includes('lovableproject.com') || import.meta.env.DEV || location.hostname === 'localhost';

// 📱 NATIVE: SW must never run in the Capacitor iOS/Android app — assets are
// bundled and any SW just serves stale code in WKWebView, blocking new builds
// from showing up after `npx cap sync`. Unregister any leftover SW from prior
// installs and wipe its caches on every native boot.
// window.Capacitor is injected by the native shell — checking it directly
// avoids bundling @capacitor/core (~23KB) into the web entry chunk.
const isNativeApp = Boolean((window as any).Capacitor?.isNativePlatform?.());
if (isNativeApp && 'serviceWorker' in navigator) {
  navigator.serviceWorker.getRegistrations()
    .then((registrations) => {
      registrations.forEach((reg) => reg.unregister());
    })
    .catch(() => {});
  if (typeof caches !== 'undefined' && caches.keys) {
    caches.keys().then((names) => names.forEach((name) => caches.delete(name)));
  }
}

// 🔥 CACHE BUST: Check if build version changed and force clear
const lastBuild = localStorage.getItem('kazaswap-build');
const currentBuild = (window as any).__KAZASWAP_BUILD__;
if (lastBuild !== currentBuild) {
  console.warn('🔥 NEW BUILD DETECTED - Clearing caches:', { lastBuild, currentBuild });
  localStorage.setItem('kazaswap-build', currentBuild);
  // Clear all caches on build update
  if (typeof caches !== 'undefined' && caches.keys) {
    caches.keys().then((names) => {
      names.forEach((name) => {
        console.log('🧹 Deleting cache:', name);
        caches.delete(name);
      });
    });
  }
}

if (isDevEnvironment) {
  // Run immediately for critical cleanup
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations()
      .then((registrations) => {
        registrations.forEach((reg) => {
          console.log('🧹 Unregistering Service Worker:', reg.scope);
          reg.unregister();
        });
      })
      .catch((error) => {
        console.warn('⚠️ Service Worker unregister failed:', error);
      });
  }

  // Clear caches on idle to avoid blocking render
  if (typeof requestIdleCallback !== 'undefined') {
    requestIdleCallback(() => {
      if (typeof caches !== 'undefined' && caches.keys) {
        caches.keys().then((names) => {
          names.forEach((name) => {
            console.log('🧹 Deleting cache:', name);
            caches.delete(name);
          });
        });
      }
    }, { timeout: 2000 });
  }
}

function showFallbackUI(message: string) {
  const root = document.getElementById('root');
  if (root) {
    root.innerHTML = `
      <div style="padding: 20px; font-family: sans-serif;">
        <h1>Error Loading Application</h1>
        <p>${message}</p>
        <button onclick="window.location.reload()">Reload Page</button>
      </div>
    `;
  }
}

try {
  const rootElement = document.getElementById('root');
  if (!rootElement) {
    throw new Error('Root element not found');
  }
  
  const root = createRoot(rootElement);
  root.render(
    <HelmetProvider>
      <App />
    </HelmetProvider>
  );
} catch (error) {
  console.error('❌ Render error:', error);
  showFallbackUI(error instanceof Error ? error.message : 'Unknown error occurred');
}
