/**
 * PWA wiring (web.dev → council; see reference/principles/web-dev.md).
 *
 * Two startup concerns, both browser-only and called once from `main.tsx`:
 *
 *  - **Service-worker update prompt.** The build uses `registerType: 'prompt'`
 *    (vite.config), so a freshly-installed service worker parks in the *waiting*
 *    state and never takes over until the app explicitly reloads. Without
 *    consuming the registration that posture silently means "never update", so we
 *    surface `onNeedRefresh` as a **durable** info toast with a **Reload** action
 *    that calls `updateSW()` (web.dev "update" flow via vite-plugin-pwa).
 *  - **Persistent storage.** Request it once at startup so the local-first
 *    workspace is not evicted under pressure (see `infrastructure/storage-persist`).
 *
 * The `virtual:pwa-register` import is provided by vite-plugin-pwa at build time;
 * it is only imported here (not in tested modules) so the test runner never has
 * to resolve the virtual module.
 */

import { registerSW } from 'virtual:pwa-register';
import { notify } from '../stores/NotificationStore';
import { requestPersistentStorage } from '../infrastructure/storage-persist';

/** Register the service worker and prompt the user when an update is ready. */
export function registerServiceWorker(): void {
  const updateSW = registerSW({
    onNeedRefresh() {
      notify({
        kind: 'info',
        title: 'Update available',
        message: 'A new version of Astrolabe is ready.',
        durable: true, // wait for the user — don't time out an update offer
        action: { label: 'Reload', onClick: () => void updateSW(true) },
      });
    },
    onOfflineReady() {
      notify({
        kind: 'success',
        title: 'Ready to work offline',
        message: 'Astrolabe is cached and will work without a connection.',
      });
    },
  });
}

/** Ask the browser to keep our storage from being evicted (fire-and-forget). */
export function initPersistentStorage(): void {
  void requestPersistentStorage();
}
