import { precacheAndRoute } from "workbox-precaching";

// Precaching configuration for PWA assets
precacheAndRoute(self.__WB_MANIFEST);

const VERSION = "1.0.4";

// Only enable skipWaiting and claim in production
const isProduction = process.env.NODE_ENV === "production";

self.addEventListener("install", (event) => {
    if (isProduction) {
        self.skipWaiting();
    }
});

self.addEventListener("activate", (event) => {
    event.waitUntil(
        (async () => {
            if (isProduction) {
                const clients = await self.clients.matchAll({ type: "window" });
                clients.forEach((client) =>
                    client.postMessage({
                        type: "VERSION_CHECK",
                        version: VERSION,
                    })
                );
                self.clients.claim();
            }
            console.log("Service Worker Activated (Version: " + VERSION + ")");
        })()
    );
});

// Rest of your existing handlers remain the same...
self.addEventListener("push", (event) => {
    try {
        const payload = event.data?.json() || {
            title: "New Notification",
            body: "You have a new message",
            icon: "/logo-192x192.png",
            data: { url: "/" },
        };

        event.waitUntil(
            self.registration.showNotification(payload.title, {
                body: payload.body,
                icon: payload.icon || "/logo-192x192.png",
                data: payload.data,
            })
        );
    } catch (error) {
        console.error("Push handling failed:", error);
    }
});

self.addEventListener("notificationclick", (event) => {
    event.notification.close();
    event.waitUntil(clients.openWindow(event.notification.data?.url || "/"));
});

self.addEventListener("message", (event) => {
    if (event.data === "SKIP_WAITING") {
        self.skipWaiting();
    }
});
