// A stale index.html can reference a hashed bundle removed by a newer deploy.
// This file is served only when an /assets/* path does not exist. Because it is
// valid JavaScript, it can recover the page instead of failing on HTML's '<'.
(async () => {
  const retryKey = 'pnleprep-stale-asset-retry';
  const lastRetry = Number(sessionStorage.getItem(retryKey) || 0);

  // Avoid a reload loop if the deployment itself is incomplete.
  if (Date.now() - lastRetry < 15000) {
    document.body.innerHTML =
      '<main style="font:16px system-ui;padding:32px;max-width:560px;margin:auto">' +
      '<h1>Update still in progress</h1>' +
      '<p>Please wait a moment, then reload this page.</p></main>';
    return;
  }

  sessionStorage.setItem(retryKey, String(Date.now()));

  try {
    const names = await caches.keys();
    await Promise.all(
      names.filter((name) => name.startsWith('pnleprep-')).map((name) => caches.delete(name))
    );
    const registration = await navigator.serviceWorker?.getRegistration('/');
    await registration?.update();
  } catch {
    // Cache/SW APIs may be unavailable in private mode; reload still helps.
  }

  window.location.reload();
})();
