const TILE_CACHE = 'tile-cache-v1';
const TILE_PREFIX = 'https://osm.tecnosis.net/osm_tiles/';

self.addEventListener('install', event => {
    self.skipWaiting();
});

self.addEventListener('activate', event => {
    event.waitUntil(self.clients.claim());
});

self.addEventListener('fetch', event => {
    const req = event.request;
    const url = req.url;

    // Sólo tiles de tu servidor OSM
    if (!url.startsWith(TILE_PREFIX)) {
        return;
    }

    event.respondWith(
        caches.open(TILE_CACHE).then(async cache => {
            const cached = await cache.match(req);
            if (cached) {
                // 💾 Tile ya guardado -> no hay descarga nueva
                return cached;
            }

            const resp = await fetch(req);

            if (resp && (resp.status === 200 || resp.type === 'opaque')) {
                cache.put(req, resp.clone());
            }

            return resp;
        })
    );
});
