/**
 * Pomodoro Timer - Service Worker
 * 
 * Developer: Molla Samser (Founder, RSK World)
 * Designer: Rima Khatun (Designer & Tester, RSK World)
 * Website: https://rskworld.in/
 * Contact: +91 93305 39277 | hello@rskworld.in | support@rskworld.in
 * Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
 * Year: 2026
 * 
 * Description: Service Worker for Pomodoro Timer PWA functionality
 */

const CACHE_NAME = 'pomodoro-timer-v1.0.0';
const urlsToCache = [
    '/',
    '/index.html',
    '/styles.css',
    '/script.js',
    '/README.md',
    'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Roboto+Mono:wght@400;500&display=swap',
    'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
    'https://cdn.jsdelivr.net/npm/chart.js'
];

// Install Event
self.addEventListener('install', (event) => {
    console.log('Service Worker: Installing...');
    
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then((cache) => {
                console.log('Service Worker: Caching files');
                // Cache local files first
                return cache.addAll([
                    '/',
                    '/index.html',
                    '/styles.css',
                    '/script.js',
                    '/config.js',
                    '/tasks.js',
                    '/themes.js',
                    '/data-manager.js',
                    '/ai-assistant.js',
                    '/focus-music.js',
                    '/gamification.js',
                    '/voice-controller.js',
                    '/analytics.js',
                    '/README.md',
                    '/LICENSE',
                    '/LICENSE.md',
                    '/COPYING',
                    '/LEGAL',
                    '/NOTICE',
                    '/PATENTS'
                ]);
            })
            .then(() => {
                console.log('Service Worker: Installation complete');
                return self.skipWaiting();
            })
            .catch((error) => {
                console.log('Service Worker: Cache installation failed:', error);
                // Still proceed with installation even if caching fails
                return self.skipWaiting();
            })
    );
});

// Activate Event
self.addEventListener('activate', (event) => {
    console.log('Service Worker: Activating...');
    
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheName !== CACHE_NAME) {
                        console.log('Service Worker: Clearing old cache');
                        return caches.delete(cacheName);
                    }
                })
            );
        }).then(() => {
            console.log('Service Worker: Activation complete');
            return self.clients.claim();
        })
    );
});

// Fetch Event
self.addEventListener('fetch', (event) => {
    const url = new URL(event.request.url);
    
    // Skip caching for external resources (Google Fonts, CDN, etc.)
    if (url.origin !== location.origin) {
        event.respondWith(fetch(event.request));
        return;
    }
    
    event.respondWith(
        caches.match(event.request)
            .then((response) => {
                // Return cached version or fetch from network
                if (response) {
                    return response;
                }
                
                return fetch(event.request)
                    .then((response) => {
                        // Check if valid response
                        if (!response || response.status !== 200 || response.type !== 'basic') {
                            return response;
                        }
                        
                        // Clone the response
                        const responseToCache = response.clone();
                        
                        caches.open(CACHE_NAME)
                            .then((cache) => {
                                cache.put(event.request, responseToCache);
                            });
                        
                        return response;
                    })
                    .catch(() => {
                        // Offline fallback
                        if (event.request.destination === 'document') {
                            return caches.match('/index.html');
                        }
                    });
            })
    );
});

// Background Sync (for future features)
self.addEventListener('sync', (event) => {
    if (event.tag === 'background-sync') {
        event.waitUntil(doBackgroundSync());
    }
});

// Push Notifications (for future features)
self.addEventListener('push', (event) => {
    const options = {
        body: event.data ? event.data.text() : 'Pomodoro Timer notification',
        icon: '/favicon.png',
        badge: '/favicon.png',
        vibrate: [100, 50, 100],
        data: {
            dateOfArrival: Date.now(),
            primaryKey: 1
        },
        actions: [
            {
                action: 'explore',
                title: 'Open Timer',
                icon: '/favicon.png'
            },
            {
                action: 'close',
                title: 'Close',
                icon: '/favicon.png'
            }
        ]
    };
    
    event.waitUntil(
        self.registration.showNotification('Pomodoro Timer', options)
    );
});

// Notification Click
self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    
    if (event.action === 'explore') {
        event.waitUntil(
            clients.openWindow('/')
        );
    }
});

// Background Sync Function
function doBackgroundSync() {
    // Future: Sync statistics data when online
    return Promise.resolve();
}

// Cleanup on message
self.addEventListener('message', (event) => {
    if (event.data === 'skipWaiting') {
        self.skipWaiting();
    }
});

console.log('Service Worker: Loaded - RSK World (2026)');
