import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { initSentry } from './services/sentryService';
import { initAnalytics } from './services/analytics';

// Initialize error tracking and analytics early
initSentry();
initAnalytics();

// Clear chunk retry flag on successful load (so next deploy can retry)
sessionStorage.removeItem('loop_chunk_retry');

// Global chunk-load recovery — when the user has an old index.html cached
// from a prior deploy, dynamic imports for chunk hashes that no longer
// exist on Vercel fail with "TypeError: Importing a module script failed"
// (Safari/iOS) or "ChunkLoadError" (Chrome). The lazyRetry wrapper covers
// top-level page lazies, but inline await import('./services/...') calls
// inside handlers (handleCreateCard → crisisDetection, generateActionMoves,
// etc) don't go through it. Catch the failure here and force-reload once
// so the user lands on the fresh deploy automatically. Idempotent via
// sessionStorage so a genuinely-broken build can't put us in a reload loop.
const isStaleChunkError = (msg?: string) => {
  if (!msg) return false;
  const m = msg.toLowerCase();
  return (
    m.includes('importing a module script') ||  // Safari / iOS
    m.includes('failed to fetch dynamically imported module') ||  // Chrome
    m.includes('chunkloaderror') ||  // Webpack-style (older Vite)
    (m.includes('error loading') && m.includes('.js'))
  );
};
const tryReloadOnStaleChunk = (msg?: string) => {
  if (!isStaleChunkError(msg)) return;
  const KEY = 'loop_chunk_recover_v1';
  if (sessionStorage.getItem(KEY)) return; // already attempted this session
  sessionStorage.setItem(KEY, String(Date.now()));
  window.location.reload();
};
window.addEventListener('error', (ev) => {
  tryReloadOnStaleChunk(ev?.message || (ev?.error && ev.error.message));
});
window.addEventListener('unhandledrejection', (ev) => {
  const msg = (ev?.reason && (ev.reason.message || String(ev.reason))) || '';
  tryReloadOnStaleChunk(msg);
});

// Polyfill crypto.randomUUID for older iOS WebViews (< iOS 15.4)
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID !== 'function') {
  (crypto as any).randomUUID = function(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      const r = (crypto.getRandomValues(new Uint8Array(1))[0] & 15);
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  };
}
import './src/index.css';
import './src/ios.css';
import './src/responsive.css';

const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

try {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
} catch (e: any) {
  rootElement.innerHTML = `<div style="padding:2rem;font-family:monospace;color:red"><h2>App crashed on mount</h2><pre>${e?.message}\n${e?.stack}</pre></div>`;
}
