import React from 'react'
import ReactDOM from 'react-dom/client'
import { inject as injectVercelAnalytics } from '@vercel/analytics'
import App from './App'
import './index.css'

// Vercel Analytics — automatic page views, web vitals, no config needed
injectVercelAnalytics()

// PostHog — lazy-loaded after first paint to avoid blocking initial render (~50KB gzipped)
if (typeof window !== 'undefined' && import.meta.env.VITE_POSTHOG_KEY) {
  // Defer PostHog init until after React mounts + idle time
  const initPostHog = () => {
    import('posthog-js').then(({ default: posthog }) => {
      posthog.init(import.meta.env.VITE_POSTHOG_KEY, {
        api_host: import.meta.env.VITE_POSTHOG_HOST || 'https://us.i.posthog.com',
        person_profiles: 'identified_only',
        capture_pageview: true,
        capture_pageleave: true,
        autocapture: true,
        session_recording: {
          maskAllInputs: false,
          maskInputOptions: { password: true },
        },
      })
      window.__posthog = posthog
    }).catch(() => {}) // silently fail if blocked by ad-blocker
  }
  if ('requestIdleCallback' in window) {
    requestIdleCallback(initPostHog, { timeout: 3000 })
  } else {
    setTimeout(initPostHog, 2000)
  }
}

// Auto-reload on stale chunk errors after deploy — Vite changes asset hashes on each build,
// so users with cached HTML will fail to fetch the new chunks. This silently reloads once.
window.addEventListener('vite:preloadError', (e) => {
  e.preventDefault();
  // Prevent infinite reload loops — only reload once per session
  if (!sessionStorage.getItem('mywrap_chunk_reload')) {
    sessionStorage.setItem('mywrap_chunk_reload', '1');
    window.location.reload();
  }
});

// Also catch unhandled dynamic import errors (covers cases vite:preloadError doesn't)
window.addEventListener('unhandledrejection', (e) => {
  if (e.reason?.message?.includes('Failed to fetch dynamically imported module') ||
      e.reason?.message?.includes('Importing a module script failed')) {
    e.preventDefault();
    if (!sessionStorage.getItem('mywrap_chunk_reload')) {
      sessionStorage.setItem('mywrap_chunk_reload', '1');
      window.location.reload();
    }
  }
});

// Error boundary — catches render crashes so users see a message instead of infinite loading spinner
class AppErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { hasError: false, error: null }; }
  static getDerivedStateFromError(error) { return { hasError: true, error }; }
  componentDidCatch(error, info) {
    console.error('[MyWrap] Fatal render error:', error, info?.componentStack);
    // Auto-reload on chunk load failures (stale deploy)
    const msg = error?.message || '';
    if ((msg.includes('Failed to fetch dynamically imported module') || msg.includes('Loading chunk') || msg.includes('Importing a module script failed')) && !sessionStorage.getItem('mywrap_chunk_reload')) {
      sessionStorage.setItem('mywrap_chunk_reload', '1');
      window.location.reload();
    }
  }
  render() {
    if (this.state.hasError) {
      const p = document.getElementById('preload');
      if (p) { p.classList.add('hidden'); setTimeout(() => p.remove(), 300); }
      const errMsg = this.state.error ? `${this.state.error.name}: ${this.state.error.message}` : '';
      return React.createElement('div', {
        style: { minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', background: '#FAF9F7', fontFamily: 'Outfit, system-ui, sans-serif', padding: 24, textAlign: 'center' }
      },
        React.createElement('img', { src: '/logo colorful no bkgrd.png', alt: 'MyWrap', style: { height: 64, marginBottom: 20, opacity: 0.7, objectFit: 'contain' } }),
        React.createElement('p', { style: { color: '#666', fontSize: 15, maxWidth: 320, lineHeight: 1.6, marginBottom: 20 } }, 'Something went wrong loading MyWrap. This is usually fixed by refreshing.'),
        errMsg && React.createElement('p', { style: { color: '#aaa', fontSize: 11, maxWidth: 400, lineHeight: 1.4, marginBottom: 16, wordBreak: 'break-word', fontFamily: 'monospace' } }, errMsg),
        React.createElement('button', { onClick: () => window.location.reload(), style: { background: '#222', color: '#fff', border: 'none', borderRadius: 999, padding: '10px 28px', fontSize: 14, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit' } }, 'Refresh')
      );
    }
    return this.props.children;
  }
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>
  </React.StrictMode>,
)
