import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import '@/monitoring/init'
import { initTelemetry } from '@/lib/telemetry'
import { Capacitor } from '@capacitor/core';
import { installExternalLinkInterceptor } from '@/lib/openExternal';
import { initNativeAppInfo } from '@/lib/appMeta';
import { captureAttributionOnce } from '@/lib/attribution';
import { registerAppShellServiceWorker, isAppShellServiceWorkerEnabled } from '@/lib/registerServiceWorker';

initTelemetry();
// Meta/UTM click attribution: capture before anything can strip the URL params.
// Write-once — a stored value is never overwritten by a later organic visit.
captureAttributionOnce();
installExternalLinkInterceptor();
// Fire-and-forget: populates native build/version for telemetry enrichment.
// Events before this resolves fall back to the APP_BUILD/APP_VERSION constants.
initNativeAppInfo();

// Defensive shim: some GTM tags reference a global `clearClarity` symbol that
// doesn't exist (Microsoft Clarity is not loaded here). Without this stub,
// Safari throws `Can't find variable: clearClarity` during post-signup
// bootstrap and blanks the app. Safe no-op.
if (typeof (window as any).clearClarity !== 'function') {
  (window as any).clearClarity = () => {};
}

/**
 * Cold start = navigation start → first meaningful render. Reported once per
 * launch so the US-latency work can be measured instead of inferred from a
 * handful of Clarity sessions.
 */
function reportColdStart() {
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      const ms = Math.round(performance.now());
      const firstPaintMs = (window as any).__calgemFirstPaintMs as number | undefined;
      // Non-blocking: after paint, and after the third-party tags are queued.
      setTimeout(() => {
        void import('@/lib/track')
          .then(({ track }) => {
            track('app.cold_start_ms', {
              ms,
              platform: Capacitor.isNativePlatform() ? 'native' : 'web',
              // Whether this launch was served by the precached shell. While
              // the SW flag is off this is always false — that's the baseline.
              from_sw:
                isAppShellServiceWorkerEnabled &&
                typeof navigator !== 'undefined' &&
                !!navigator.serviceWorker?.controller,

            });
            // Separate metric: navigationStart -> inline boot block visible.
            // Our cold_start_ms measures React's first render, which is why it
            // read 1.8s while Clarity reported 2.8–5s LCP for the same window.
            if (typeof firstPaintMs === 'number') {
              track('app.first_paint_ms', {
                ms: firstPaintMs,
                react_ms: ms,
                platform: Capacitor.isNativePlatform() ? 'native' : 'web',
              });
            }
          })
          .catch(() => {});
        try {
          (window as any).clarity?.('set', 'cold_start_ms', String(ms));
        } catch {}
      }, 0);
    });
  });
}

/**
 * Remove the inline boot splash once React has painted. It is position:fixed,
 * so removing it cannot shift any layout underneath (CLS stays 0) — the app is
 * already laid out behind it before the fade starts.
 */
function dismissBootSplash() {
  const el = document.getElementById('boot-splash');
  if (!el) return;
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      el.setAttribute('data-hiding', 'true');
      window.setTimeout(() => el.remove(), 220);
    });
  });
}


/**
 * Third-party tags must never sit on the critical path. GTM (and anything it
 * loads) is injected after the first render instead of blocking <head>.
 */
function loadDeferredThirdParty() {
  const w = window as any;
  if (w.__calgemGtmLoaded) return;
  w.__calgemGtmLoaded = true;
  w.dataLayer = w.dataLayer || [];
  w.dataLayer.push({ 'gtm.start': Date.now(), event: 'gtm.js' });
  const s = document.createElement('script');
  s.async = true;
  s.src = 'https://www.googletagmanager.com/gtm.js?id=GTM-WTBJ5S72';
  document.head.appendChild(s);
}

const root = createRoot(document.getElementById("root")!);
root.render(<App />);
reportColdStart();
dismissBootSplash();


// Everything below is post-first-paint only.
const afterPaint = () => {
  loadDeferredThirdParty();
  registerAppShellServiceWorker();
};
if ('requestIdleCallback' in window) {
  (window as any).requestIdleCallback(afterPaint, { timeout: 3000 });
} else {
  setTimeout(afterPaint, 1200);
}

// Hide the native Capacitor splash screen once the React app has rendered
if (Capacitor.isNativePlatform()) {
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      import('@capacitor/splash-screen').then(({ SplashScreen }) => {
        SplashScreen.hide().catch(() => {});
      }).catch(() => {});
    });
  });
}

