import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst } from 'workbox-strategies';

// Precache all assets
precacheAndRoute(self.__WB_MANIFEST);

// Cache Google Fonts
registerRoute(
    /^https:\/\/fonts\.googleapis\.com\/.*/i,
    new CacheFirst({
        cacheName: 'google-fonts-cache',
    })
);

// ===== PUSH NOTIFICATION HANDLER =====
self.addEventListener('push', function (event) {
    console.log('[SW] Push event received');

    let notificationData = {
        title: 'snStatus 알림',
        body: '시스템 알림',
        vibrate: [200, 100, 200],
        requireInteraction: true,
        tag: 'snstatus-alert',
        data: {
            url: '/'
        }
    };

    if (event.data) {
        try {
            const data = event.data.json();
            console.log('[SW] Push data:', data);
            if (data.title) notificationData.title = data.title;
            if (data.body) notificationData.body = data.body;
        } catch (e) {
            console.error('[SW] Parse error:', e);
            notificationData.body = event.data.text();
        }
    }

    // ALWAYS show notification, regardless of page visibility
    event.waitUntil(
        self.registration.showNotification(notificationData.title, {
            body: notificationData.body,
            vibrate: notificationData.vibrate,
            requireInteraction: notificationData.requireInteraction,
            tag: notificationData.tag,
            data: notificationData.data,
            // Force notification to show even when page is visible
            silent: false
        }).then(() => {
            console.log('[SW] Notification displayed successfully');
        })
    );
});

self.addEventListener('notificationclick', function (event) {
    console.log('[SW] Notification clicked');
    event.notification.close();

    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true })
            .then(function (clientList) {
                // Focus existing window if available
                for (let i = 0; i < clientList.length; i++) {
                    const client = clientList[i];
                    if (client.url.includes('/') && 'focus' in client) {
                        return client.focus();
                    }
                }
                // Open new window
                if (clients.openWindow) {
                    return clients.openWindow('/');
                }
            })
    );
});

console.log('[SW] Service Worker with push notification support loaded');
