export async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {
  if (typeof window === "undefined" || !("serviceWorker" in navigator)) {
    return null
  }

  // Check if we're in a preview or development environment
  const isPreview =
    window.location.hostname.includes("vusercontent.net") ||
    window.location.hostname.includes("v0.app") ||
    window.location.hostname === "localhost"

  if (isPreview) {
    console.log("[v0] Service worker registration skipped in preview environment")
    return null
  }

  try {
    const registration = await navigator.serviceWorker.register("/sw.js", {
      scope: "/",
    })

    registration.addEventListener("updatefound", () => {
      const newWorker = registration.installing
      if (newWorker) {
        newWorker.addEventListener("statechange", () => {
          if (newWorker.state === "installed" && navigator.serviceWorker.controller) {
            // New content available, notify user
            window.dispatchEvent(new CustomEvent("sw-update-available"))
          }
        })
      }
    })

    return registration
  } catch (error) {
    console.error("Service worker registration failed:", error)
    return null
  }
}

export function unregisterServiceWorker(): Promise<boolean> {
  if (typeof window === "undefined" || !("serviceWorker" in navigator)) {
    return Promise.resolve(false)
  }

  return navigator.serviceWorker.ready.then((registration) => {
    return registration.unregister()
  })
}
