import { createRoot } from "react-dom/client";
import { HelmetProvider } from "react-helmet-async";
import { registerSW } from 'virtual:pwa-register';
import App from "./App.tsx";
import "./index.css";
import { BUILD_HASH, FULL_VERSION, APP_ENV } from "./config/version";
import { addVersionToHistory } from "./utils/versionHistory";
import { trackPerformanceMetrics } from "./utils/performanceAnalytics";
import { setupGlobalErrorHandler } from "./utils/errorReporting";
import { initActivityTracking } from "./utils/activityTracker";
import { cleanupOldAnalytics } from "./utils/localStorageCleanup";
import { initServerAnalytics } from "./utils/serverAnalytics";
import { migrateStorageKeys, shouldMigrate, cleanupOrphanedKeys, shouldRunCleanup } from "./utils/storageMigration";

// Setup global error handler for uncaught errors
setupGlobalErrorHandler();

// Run storage migration FIRST (before any other localStorage access)
if (shouldMigrate()) {
  migrateStorageKeys();
}

// Run cleanup pass to catch any orphaned wormble- keys from old code
if (shouldRunCleanup()) {
  cleanupOrphanedKeys();
}

// Initialize activity tracking (local)
initActivityTracking();

// Initialize server-side analytics
initServerAnalytics();

// Cleanup old analytics data on startup
cleanupOldAnalytics();

// Version change detection
const STORED_BUILD_HASH_KEY = 'wordpop-build-hash';
const storedHash = localStorage.getItem(STORED_BUILD_HASH_KEY);

if (storedHash && storedHash !== BUILD_HASH) {
  // Check if debug mode is enabled
  const debugEnabled = localStorage.getItem('wordpop-debug-enabled') === 'true' || 
                      new URLSearchParams(window.location.search).get('debug') === 'true';
  
  if (debugEnabled) {
    console.log(`🔄 Version updated: ${storedHash} → ${BUILD_HASH}`);
    console.log(`📦 New version: ${FULL_VERSION}`);
  }
  
  // Force stats re-check on version update
  localStorage.removeItem("wordpop-stats-last-check");
  localStorage.removeItem("wordpop-stats-recalculated-v2"); // Clear old flag
}
localStorage.setItem(STORED_BUILD_HASH_KEY, BUILD_HASH);

// Clear old permanent flag for all users on app startup
localStorage.removeItem("wordpop-stats-recalculated-v2");

// Track version in history
addVersionToHistory({
  hash: BUILD_HASH,
  timestamp: new Date().toISOString(),
  fullVersion: FULL_VERSION,
  environment: APP_ENV,
});

// Register service worker with aggressive update checking
const updateSW = registerSW({
  onNeedRefresh() {
    console.log('New version available');
    (window as any).__WORDPOP_UPDATE_AVAILABLE__ = true;
    window.dispatchEvent(new CustomEvent('wordpop-update-available'));
  },
  onOfflineReady() {
    console.log('App ready to work offline!');
  },
  // Force immediate update check on registration
  immediate: true,
  // Check for a new version when the app comes back to the screen and every hour,
  // so an installed app that stays open still updates itself.
  onRegisteredSW(_swUrl, registration) {
    if (!registration) return;
    const check = () => { registration.update().catch(() => {}); };
    setInterval(check, 60 * 60 * 1000);
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') check();
    });
  },
});

// Force service worker update check on version mismatch
if (storedHash && storedHash !== BUILD_HASH) {
  // Aggressively update service worker when version changes
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistration().then(registration => {
      if (registration) {
        console.log('🔄 Version mismatch detected, forcing SW update check');
        registration.update();
      }
    });
  }
}

// Export for controlled updates
(window as any).__WORDPOP_UPDATE_SW__ = updateSW;

createRoot(document.getElementById("root")!).render(
  <HelmetProvider>
    <App />
  </HelmetProvider>
);

// Track performance metrics after page load
if (typeof window !== 'undefined') {
  window.addEventListener('load', () => {
    // Delay slightly to ensure LCP is captured
    setTimeout(() => {
      trackPerformanceMetrics();
    }, 1000);
  });
}
