import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './styles/matteline-foundation.css'
import './styles/pwa-runtime.css'
import App from './App.jsx'

const CHUNK_RECOVERY_KEY = 'matte-line-chunk-recovery-v1';

window.addEventListener('vite:preloadError', (event) => {
  event.preventDefault();

  const currentBundle = document.querySelector('script[type="module"][src]')?.src || 'unknown';
  const marker = `${window.location.pathname}|${currentBundle}`;

  try {
    if (window.sessionStorage.getItem(CHUNK_RECOVERY_KEY) === marker) return;
    window.sessionStorage.setItem(CHUNK_RECOVERY_KEY, marker);
  } catch {
    // A reload is still safer than leaving the SPA on a stale chunk error.
  }

  window.location.reload();
});

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