import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { HelmetProvider } from 'react-helmet-async';
import App from './App.tsx';
import './index.css';

// #region agent log
// DEBUG: Instrumentação para verificar ambiente e Service Worker
(function debugAppInit() {
  const isProd = import.meta.env.PROD;
  const mode = import.meta.env.MODE;
  const swController = navigator?.serviceWorker?.controller ? 'active' : 'none';
  const agentLogUrl = import.meta.env.VITE_AGENT_LOG_URL as string | undefined;
  if (import.meta.env.DEV && agentLogUrl) {
    fetch(agentLogUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        location: 'main.tsx:init',
        message: 'App init check',
        data: { isProd, mode, swController, hostname: window?.location?.hostname, href: window?.location?.href },
        timestamp: Date.now(),
        sessionId: 'debug-session',
        hypothesisId: 'H3',
      }),
    }).catch(() => {});
  }
})();
// #endregion

// Registrar Service Worker para cache de imagens
if ('serviceWorker' in navigator && import.meta.env.PROD) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then((registration) => {
        console.log('[App] Service Worker registered:', registration.scope);
        // #region agent log
        const agentLogUrl = import.meta.env.VITE_AGENT_LOG_URL as string | undefined;
        if (import.meta.env.DEV && agentLogUrl) {
          fetch(agentLogUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              location: 'main.tsx:sw-registered',
              message: 'SW registered',
              data: { scope: registration.scope, waiting: !!registration.waiting, active: !!registration.active },
              timestamp: Date.now(),
              sessionId: 'debug-session',
              hypothesisId: 'H3',
            }),
          }).catch(() => {});
        }
        // #endregion
      })
      .catch((error) => {
        console.warn('[App] Service Worker registration failed:', error);
      });
  });
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <HelmetProvider>
      <App />
    </HelmetProvider>
  </StrictMode>
);
