// service-worker.js
// Service Worker untuk Web Push Notification - Sistem Absensi

const CACHE_NAME = 'absensi-v2';
const STATIC_ASSETS = [
    '/',
    '/scan_wa_api.php',
    '/index.php',
    '/dashboard.php',
    '/assets/icon-192.png',
    '/assets/badge-72x72.png',
    '/assets/check.svg',
    '/assets/close.svg',
    '/assets/notification.mp3'
];

// ============================================
// INSTALL EVENT
// ============================================
self.addEventListener('install', function(event) {
    console.log('[Service Worker] Installing...');
    
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(function(cache) {
                console.log('[Service Worker] Caching assets...');
                return cache.addAll(STATIC_ASSETS)
                    .catch(function(error) {
                        console.log('[Service Worker] Cache error:', error);
                        // Skip failed assets
                        return Promise.resolve();
                    });
            })
            .then(function() {
                console.log('[Service Worker] Installation complete');
                return self.skipWaiting();
            })
    );
});

// ============================================
// ACTIVATE EVENT
// ============================================
self.addEventListener('activate', function(event) {
    console.log('[Service Worker] Activating...');
    
    event.waitUntil(
        caches.keys()
            .then(function(cacheNames) {
                return Promise.all(
                    cacheNames.map(function(cacheName) {
                        if (cacheName !== CACHE_NAME) {
                            console.log('[Service Worker] Deleting old cache:', cacheName);
                            return caches.delete(cacheName);
                        }
                    })
                );
            })
            .then(function() {
                console.log('[Service Worker] Activated');
                return self.clients.claim();
            })
    );
});

// ============================================
// FETCH EVENT - Network First Strategy
// ============================================
self.addEventListener('fetch', function(event) {
    // Skip cross-origin requests
    if (!event.request.url.startsWith(self.location.origin)) {
        return;
    }
    
    // Skip non-GET requests
    if (event.request.method !== 'GET') {
        return;
    }
    
    // Skip API requests
    if (event.request.url.includes('/api/') || 
        event.request.url.includes('rekam_absen') ||
        event.request.url.includes('push_notification')) {
        return;
    }
    
    event.respondWith(
        // Try network first
        fetch(event.request)
            .then(function(response) {
                // Cache successful responses
                if (response && response.status === 200 && response.type === 'basic') {
                    const responseToCache = response.clone();
                    caches.open(CACHE_NAME)
                        .then(function(cache) {
                            cache.put(event.request, responseToCache);
                        })
                        .catch(function(err) {
                            console.log('[Service Worker] Cache put error:', err);
                        });
                }
                return response;
            })
            .catch(function() {
                // If network fails, try cache
                return caches.match(event.request)
                    .then(function(response) {
                        if (response) {
                            return response;
                        }
                        // If not in cache, return offline page
                        return caches.match('/');
                    });
            })
    );
});

// ============================================
// PUSH EVENT - Handle incoming push notifications
// ============================================
self.addEventListener('push', function(event) {
    console.log('[Service Worker] Push Received');
    console.log('[Service Worker] Push data:', event.data ? event.data.text() : 'No data');
    
    // Default notification data
    let notificationData = {
        title: 'Sistem Absensi',
        body: 'Anda memiliki notifikasi baru',
        icon: '/assets/icon-192.png',
        badge: '/assets/badge-72x72.png',
        url: '/scan_wa_api.php',
        vibrate: [200, 100, 200],
        requireInteraction: true
    };
    
    // Parse push data if available
    if (event.data) {
        try {
            const parsedData = event.data.json();
            notificationData = { ...notificationData, ...parsedData };
        } catch (e) {
            // If not JSON, use as plain text body
            notificationData.body = event.data.text();
        }
    }
    
    // Prepare notification options
    const options = {
        body: notificationData.body,
        icon: notificationData.icon,
        badge: notificationData.badge,
        vibrate: notificationData.vibrate,
        sound: '/assets/notification.mp3',
        requireInteraction: notificationData.requireInteraction || false,
        data: {
            url: notificationData.url || '/scan_wa_api.php',
            timestamp: Date.now(),
            additionalData: notificationData.additionalData || {}
        },
        actions: [
            {
                action: 'open',
                title: '📋 Lihat Detail',
                icon: '/assets/check.svg'
            },
            {
                action: 'close',
                title: '❌ Tutup',
                icon: '/assets/close.svg'
            }
        ],
        // Android specific
        android_channel_id: 'absensi_channel',
        // iOS specific
        badge: 1
    };
    
    event.waitUntil(
        self.registration.showNotification(notificationData.title, options)
    );
});

// ============================================
// NOTIFICATION CLICK EVENT
// ============================================
self.addEventListener('notificationclick', function(event) {
    console.log('[Service Worker] Notification click:', event.action);
    event.notification.close();
    
    // Get URL from notification data
    const urlToOpen = event.notification.data && event.notification.data.url 
        ? event.notification.data.url 
        : '/scan_wa_api.php';
    
    // Handle different actions
    if (event.action === 'open') {
        // Open detail page
        event.waitUntil(
            openOrFocusWindow(urlToOpen)
        );
    } else if (event.action === 'close') {
        // Just close notification
        return;
    } else {
        // Default: open URL
        event.waitUntil(
            openOrFocusWindow(urlToOpen)
        );
    }
});

// ============================================
// NOTIFICATION CLOSE EVENT
// ============================================
self.addEventListener('notificationclose', function(event) {
    console.log('[Service Worker] Notification closed');
    // Optional: Send analytics or log
});

// ============================================
// HELPER FUNCTIONS
// ============================================

/**
 * Open or focus an existing window with the given URL
 */
function openOrFocusWindow(url) {
    return clients.matchAll({
        type: 'window',
        includeUncontrolled: true
    }).then(function(windowClients) {
        // Check if there's already a window with this URL
        for (let client of windowClients) {
            if (client.url === url && 'focus' in client) {
                return client.focus();
            }
        }
        // If not, open a new window
        if (clients.openWindow) {
            return clients.openWindow(url);
        }
        return null;
    });
}

/**
 * Get all clients and send a message
 */
function sendMessageToAllClients(message) {
    return clients.matchAll({
        type: 'window',
        includeUncontrolled: true
    }).then(function(clients) {
        clients.forEach(function(client) {
            client.postMessage(message);
        });
    });
}

/**
 * Update badge count
 */
function updateBadgeCount(count) {
    if (navigator.setAppBadge) {
        navigator.setAppBadge(count);
    } else if (navigator.setExperimentalAppBadge) {
        navigator.setExperimentalAppBadge(count);
    }
}

// ============================================
// MESSAGE EVENT - Handle messages from client
// ============================================
self.addEventListener('message', function(event) {
    console.log('[Service Worker] Message received:', event.data);
    
    if (event.data && event.data.action) {
        switch (event.data.action) {
            case 'updateBadge':
                if (event.data.count !== undefined) {
                    updateBadgeCount(event.data.count);
                }
                break;
            case 'skipWaiting':
                self.skipWaiting();
                break;
            case 'clearCache':
                caches.delete(CACHE_NAME);
                break;
            default:
                console.log('[Service Worker] Unknown action:', event.data.action);
        }
    }
});

// ============================================
// PERIODIC SYNC - Optional for background sync
// ============================================
self.addEventListener('periodicsync', function(event) {
    console.log('[Service Worker] Periodic sync:', event.tag);
    
    if (event.tag === 'update-data') {
        // Refresh data periodically
        event.waitUntil(
            fetch('/api/check_updates')
                .then(function(response) {
                    return response.json();
                })
                .then(function(data) {
                    if (data.hasUpdates) {
                        // Send notification about updates
                        self.registration.showNotification('Data Terbaru', {
                            body: 'Ada data baru yang perlu dilihat',
                            icon: '/assets/icon-192.png'
                        });
                    }
                })
                .catch(function(error) {
                    console.log('[Service Worker] Periodic sync error:', error);
                })
        );
    }
});

// ============================================
// BACKGROUND FETCH - For large file downloads
// ============================================
self.addEventListener('backgroundfetchsuccess', function(event) {
    console.log('[Service Worker] Background fetch success:', event);
    // Process downloaded files
});

self.addEventListener('backgroundfetchfail', function(event) {
    console.log('[Service Worker] Background fetch fail:', event);
});

// ============================================
// LOGGING
// ============================================
console.log('[Service Worker] Loaded successfully');
console.log('[Service Worker] Cache name:', CACHE_NAME);
console.log('[Service Worker] Static assets:', STATIC_ASSETS);

// ============================================
// EXPOSE VERSION FOR DEBUGGING
// ============================================
self.__SW_VERSION = '1.0.0';
self.__SW_CACHE = CACHE_NAME;