import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

/**
 * Recover from a stale deploy: when a lazy chunk fails to load (its hashed name
 * changed after a rebuild and the cached index.html still points at the old
 * one), force a one-time hard reload to fetch the fresh index + chunks.
 */
function isChunkLoadError(reason: unknown): boolean {
  const msg = String((reason as { message?: string })?.message ?? reason ?? '');
  return /dynamically imported module|ChunkLoadError|Loading chunk|Importing a module script failed/i.test(msg);
}
function reloadOnce(): void {
  if (!sessionStorage.getItem('bms_chunk_reloaded')) {
    sessionStorage.setItem('bms_chunk_reloaded', '1');
    location.reload();
  }
}
window.addEventListener('unhandledrejection', (e) => { if (isChunkLoadError(e.reason)) { reloadOnce(); } });
window.addEventListener('error', (e) => { if (isChunkLoadError((e as ErrorEvent).message)) { reloadOnce(); } });

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));
