const CACHE_NAME = 'josie-share-v1';
const ASSETS = [
    'share.html',
    'share.js',
    'style.css'
];

self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => cache.addAll(ASSETS))
            .then(() => self.skipWaiting())
    );
});

self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys()
            .then(keys => Promise.all(
                keys.filter(key => key !== CACHE_NAME)
                    .map(key => caches.delete(key))
            ))
            .then(() => self.clients.claim())
    );
});

self.addEventListener('fetch', (event) => {
    if (event.request.method !== 'GET') return;

    event.respondWith(
        caches.match(event.request)
            .then(cached => {
                const fetched = fetch(event.request)
                    .then(response => {
                        if (response.ok) {
                            const clone = response.clone();
                            caches.open(CACHE_NAME)
                                .then(cache => cache.put(event.request, clone));
                        }
                        return response;
                    })
                    .catch(() => cached);

                return cached || fetched;
            })
    );
});

// Background sync for location updates
self.addEventListener('sync', (event) => {
    if (event.tag === 'location-sync') {
        event.waitUntil(syncLocation());
    }
});

async function syncLocation() {
    // Background sync is limited - mainly used for retrying failed sends
    // Real-time location still relies on foreground watchPosition
    console.log('Background sync triggered');
}

// Periodic background sync (where supported)
self.addEventListener('periodicsync', (event) => {
    if (event.tag === 'location-update') {
        event.waitUntil(syncLocation());
    }
});
