import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { AuthProvider } from './context/AuthContext.tsx';
import { BrowserRouter } from 'react-router-dom';

const AUTO_RELOAD_GUARD_KEY = 'app_auto_reload_done';

const extractModuleSrc = (html: string): string | null => {
  const moduleScriptFirst =
    /<script[^>]*type=["']module["'][^>]*src=["']([^"']+)["'][^>]*>/i;
  const srcFirstModule =
    /<script[^>]*src=["']([^"']+)["'][^>]*type=["']module["'][^>]*>/i;
  return html.match(moduleScriptFirst)?.[1] || html.match(srcFirstModule)?.[1] || null;
};

const forceFreshLoadIfUpdated = async (): Promise<boolean> => {
  try {
    const currentModuleScript = document.querySelector(
      'script[type="module"][src]'
    ) as HTMLScriptElement | null;

    if (!currentModuleScript?.src) return true;

    const currentPath = new URL(currentModuleScript.src, window.location.origin).pathname;
    const response = await fetch(`/index.html?_ts=${Date.now()}`, {
      cache: 'no-store',
      headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        Pragma: 'no-cache',
      },
    });

    if (!response.ok) return true;

    const latestHtml = await response.text();
    const latestModuleSrc = extractModuleSrc(latestHtml);
    if (!latestModuleSrc) return true;

    const latestPath = new URL(latestModuleSrc, window.location.origin).pathname;
    const hasReloaded = sessionStorage.getItem(AUTO_RELOAD_GUARD_KEY) === '1';

    if (latestPath !== currentPath && !hasReloaded) {
      sessionStorage.setItem(AUTO_RELOAD_GUARD_KEY, '1');

      if ('caches' in window) {
        const keys = await caches.keys();
        await Promise.all(keys.map((key) => caches.delete(key)));
      }

      const freshUrl = new URL(window.location.href);
      freshUrl.searchParams.set('_r', Date.now().toString());
      window.location.replace(freshUrl.toString());
      return false;
    }

    if (latestPath === currentPath) {
      sessionStorage.removeItem(AUTO_RELOAD_GUARD_KEY);
    }
  } catch (error) {
    console.warn('Falha ao verificar atualização da aplicação:', error);
  }

  return true;
};

const renderApp = () => {
  createRoot(document.getElementById('root')!).render(
    <StrictMode>
      <BrowserRouter>
        <AuthProvider>
          <App />
        </AuthProvider>
      </BrowserRouter>
    </StrictMode>
  );
};

forceFreshLoadIfUpdated().then((shouldRender) => {
  if (shouldRender) {
    renderApp();
  }
});
