import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { initI18n } from "@/i18n";
import '@/utils/verboseLogger'; // Initialize verbose logger controls
// SplashScreen removed - HTML splash stays visible until data ready
import { logger } from '@/utils/logger';
import { BUILD_HASH } from '@/config/buildVersion';
import { setupGlobalAvatarRefresh } from '@/hooks/useAvatarPreloader';
import { preloadStaticAssets } from '@/utils/preloadStaticAssets';
import { markPwaBootStart, pwaLog, maybeDumpPwaBootLog } from '@/utils/pwaBootLog';
import { initBackdropTheme } from '@/utils/backdropTheme';

// Resolve backdrop theme from ?theme= / piq_theme cookie BEFORE React mounts
// so the desktop shell paints correctly on first frame. Does NOT affect the
// in-app theme — that stays controlled by the app's own Zustand state.
initBackdropTheme();

markPwaBootStart();
pwaLog('main:start');
maybeDumpPwaBootLog();


// Install global avatar cache revalidation on tab foreground
setupGlobalAvatarRefresh();

// Logo preload is handled via <link rel="preload"> in index.html (splash PNG
// is shared by HTML splash, React SplashScreen, Login, and ResetPassword).

// Preload + pin small static brand assets (DUPR logo, etc.) so they are
// paint-ready the first time any view renders them — no flash on /profile.
preloadStaticAssets();

// Use build-time hash for cache busting (constant until next deployment)
export const APP_VERSION = BUILD_HASH;
logger.info('🚀 App starting - Build:', APP_VERSION);

// Boot marker for diagnostics - set immediately so index.html can check if React started
(window as any).__appBootStarted = Date.now();

// Make debug function globally available (dev only)
if (import.meta.env.DEV) {
  import('@/utils/gameSelection/partnerRotation').then(({ debugFormationState }) => {
    (window as any).debugPartnerState = debugFormationState;
  });
}
(window as any).APP_VERSION = APP_VERSION;

const rootElement = document.getElementById("root");

if (!rootElement) {
  logger.error('💥 Main: Root element not found!');
  throw new Error('Root element not found');
}

const root = createRoot(rootElement);

/**
 * Desktop phone-frame shell.
 *
 * If the window is wide enough to be "desktop" AND we are NOT already inside
 * the embed iframe, render only <DesktopFrame /> — which mounts an iframe
 * pointing at the same URL with ?frame=embed appended. The iframe re-enters
 * main.tsx, the embed check passes, and the real <App /> renders inside the
 * iframe. From the app's perspective the viewport is a real 390x844 phone.
 *
 * See src/DesktopFrame.tsx for the full rationale.
 */
const isEmbed = new URLSearchParams(window.location.search).get('frame') === 'embed';
const isDesktopShell = !isEmbed && window.matchMedia('(min-width: 431px) and (hover: hover) and (pointer: fine)').matches;

if (isDesktopShell) {
  logger.info('🖥️ Desktop shell — rendering phone-frame iframe');
  // Reload when crossing the desktop/mobile boundary so the right shell mounts.
  const mq = window.matchMedia('(min-width: 431px) and (hover: hover) and (pointer: fine)');
  mq.addEventListener('change', (e) => {
    if (!e.matches) window.location.reload();
  });
  import('./DesktopFrame').then(({ default: DesktopFrame }) => {
    root.render(<DesktopFrame />);
  });
  // Skip the full app boot (i18n, avatar refresh, preloads) — the iframe
  // will do all of that inside the embedded document.
}

if (!isDesktopShell) {

// Reload when crossing into desktop so <DesktopFrame /> can mount.
if (!isEmbed) {
  const mq = window.matchMedia('(min-width: 431px) and (hover: hover) and (pointer: fine)');
  mq.addEventListener('change', (e) => {
    if (e.matches) window.location.reload();
  });
}


// Best-effort: lock screen orientation to portrait where supported (Android PWA
// standalone). No-op / rejected on iOS Safari and most desktop browsers — the
// LandscapeBlocker overlay handles those cases at the UX layer.
try {
  const so = (screen as Screen & { orientation?: { lock?: (o: string) => Promise<void> } }).orientation;
  so?.lock?.('portrait').catch(() => { /* unsupported — handled by overlay */ });
} catch { /* unsupported */ }


// Performance Mark: Start initialization
performance.mark('app-init-start');

// Language detection now handled natively by i18n querystring detector

// Initialize i18n with timeout - don't block app for slow translation loads
const I18N_TIMEOUT_MS = 4000;

const initI18nWithTimeout = async (): Promise<void> => {
  const timeoutPromise = new Promise<never>((_, reject) => 
    setTimeout(() => reject(new Error('i18n-timeout')), I18N_TIMEOUT_MS)
  );
  
  try {
    await Promise.race([initI18n(), timeoutPromise]);
  } catch (error) {
    if ((error as Error).message === 'i18n-timeout') {
      logger.warn('⏰ i18n timeout - proceeding with bundled English, translations will load in background');
      // Don't throw - let app render with bundled English
      return;
    }
    throw error; // Re-throw actual errors
  }
};

(async () => {
  logger.info('🚀 Initializing i18n...');
  try {
    const i18nStart = performance.now();
    await initI18nWithTimeout();
    const i18nDuration = performance.now() - i18nStart;
    performance.mark('i18n-init-complete');
    logger.info(`✅ i18n initialized in ${i18nDuration.toFixed(2)}ms`);
  } catch (error) {
    logger.error('💥 Failed to initialize i18n:', error);
    // Continue anyway with bundled English - don't block app
    logger.warn('⚠️ Continuing with bundled English due to i18n error');
  }

  // Performance Mark: Start render
  performance.mark('app-render-start');

  // No outer Suspense with null fallback - App.tsx handles all Suspense with visible fallbacks
  root.render(
    <App />
  );

  // Track first render completion
  requestAnimationFrame(() => {
    performance.mark('app-first-render-complete');
    
    // Measure performance
    try {
      performance.measure('app-init', 'app-init-start', 'i18n-init-complete');
      performance.measure('app-render', 'app-render-start', 'app-first-render-complete');
      
      const initMeasure = performance.getEntriesByName('app-init')[0];
      const renderMeasure = performance.getEntriesByName('app-render')[0];
      
      logger.info('⚡ Performance Metrics:', {
        init: `${initMeasure?.duration.toFixed(2)}ms`,
        render: `${renderMeasure?.duration.toFixed(2)}ms`,
        total: `${((initMeasure?.duration || 0) + (renderMeasure?.duration || 0)).toFixed(2)}ms`
      });
    } catch (e) {
      // Performance measurement not critical
    }
  });
})();
}

