// Offline manager for PWA functionality
// Feature Registration Pattern implementation

import type { ReaderContext } from "../core/reader-context";

let context: ReaderContext;

export function init(readerContext: ReaderContext): void {
  context = readerContext;
  registerServiceWorker();

  window.addEventListener("online", () => {
    const isOnline = checkOnlineStatus();
    if (isOnline) {
      context.events.emit("offline:online", {});
      syncPendingChanges(context);
    }
  });

  window.addEventListener("offline", () => {
    context.events.emit("offline:offline", {});
  });

  context.events.on("offline:check", () => {
    const isOnline = checkOnlineStatus();
    context.events.emit("offline:status", { isOnline });
  });
}

export function registerServiceWorker(): void {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker
      .register("/static/service-worker.js")
      .then((registration) => {
        console.log("Service worker registered:", registration);
      })
      .catch((error) => {
        console.error("Service worker registration failed:", error);
      });
  }
}

export function checkOnlineStatus(): boolean {
  if (typeof navigator !== "undefined" && navigator.onLine) {
    return true;
  }
  return false;
}

function syncPendingChanges(context: ReaderContext): void {
  context.events.emit("offline:sync", {});
}
