import { enforceHostRedirect } from '@/lib/host';

// MUST run before any other import-time side-effect so the marketplace UI
// never flashes on api.prebro.com. If a redirect is issued, halt boot.
const __redirecting = enforceHostRedirect();

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { installErrorTracking } from '@/lib/errorTracking';
import { initWebVitals } from '@/lib/webVitals';
import { runCacheBuster } from '@/lib/cacheBuster';
import { applyDynamicFavicon } from '@/lib/dynamicFavicon';
import { registerPwa } from '@/lib/pwaRegister';
import { ensureBingVerificationMeta } from '@/lib/seo/verificationMeta';

if (__redirecting) {
  // Stop here — the browser is mid-navigation, do not mount React.
  throw new Error('host-redirect:halt-boot');
}


// Apply admin-uploaded favicon if any (replaces static one)
applyDynamicFavicon();

// v345-C.1 — Inject Bing Webmaster meta if VITE_BING_VERIFICATION is set (no-op otherwise).
ensureBingVerificationMeta();

// F.1.1 — Install global error tracking
installErrorTracking();

// Phase 1.6 — Core Web Vitals tracking
initWebVitals();

// Clear stale React-Query / IDB caches once per version (no SW unregister anymore).
runCacheBuster();

// Register the PWA service worker (skipped inside Lovable preview iframe).
registerPwa();

const root = document.getElementById("root");
if (root) {
  ReactDOM.createRoot(root).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );

  // Once React has mounted and the first frame paints without crashing,
  // clear the error-boundary crash counters so transient errors don't
  // accumulate across sessions and trigger an unnecessary nuclear reset.
  requestAnimationFrame(() => {
    setTimeout(() => {
      try {
        sessionStorage.removeItem('prebro:eb_crash_count');
        sessionStorage.removeItem('prebro:eb_crash_last_at');
        sessionStorage.removeItem('prebro:geb_crash_count');
        sessionStorage.removeItem('prebro:geb_crash_last_at');
      } catch { /* ignore */ }
    }, 5000);
  });
}

