// Service Worker v2.0 - ISP Bypass & Offline Support
const CACHE_NAME = 'crs-cache-v2';
const OFFLINE_URL = '/offline.html';

// Files to cache
const urlsToCache = [
  '/',
  '/home.php',
  '/index.php',
  '/general-public.php',
  '/register.php',
  '/forgot-password.php',
  '/access-help.php',
  '/offline.html',
  '/manifest.json',
  '/assets/CSS/main.css',
  '/assets/JS/trans.js',
  'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css',
  'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css',
  'https://dc.crsorgi.gov.in/assets/logo/crs-logo.png',
  'https://dc.crsorgi.gov.in/assets/logo/crs-logo-light.png',
  'https://dc.crsorgi.gov.in/assets/images/emblem.png',
  'https://dc.crsorgi.gov.in/assets/images/flag.svg'
];

// Install event - cache resources
self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache.map(url => {
          return new Request(url, { mode: 'no-cors' });
        })).catch(err => console.log('Cache addAll error:', err));
      })
  );
  self.skipWaiting();
});

// Activate event - clean old caches
self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheName) {
          return cacheName !== CACHE_NAME;
        }).map(function(cacheName) {
          return caches.delete(cacheName);
        })
      );
    })
  );
  self.clients.claim();
});

// Fetch event - serve from cache if blocked
self.addEventListener('fetch', function(event) {
  // Skip non-GET requests
  if (event.request.method !== 'GET') {
    return;
  }

  event.respondWith(
    // Try network first
    fetch(event.request, {
      mode: 'cors',
      credentials: 'same-origin'
    })
    .then(function(response) {
      // Check if valid response
      if (!response || response.status !== 200) {
        // Try cache if network fails
        return caches.match(event.request).then(function(cachedResponse) {
          return cachedResponse || response;
        });
      }

      // Clone response for caching
      var responseToCache = response.clone();

      caches.open(CACHE_NAME)
        .then(function(cache) {
          // Only cache same-origin or CORS-enabled requests
          if (event.request.url.startsWith(self.location.origin) || 
              response.type === 'cors') {
            cache.put(event.request, responseToCache);
          }
        });

      return response;
    })
    .catch(function(error) {
      // Network failed - try cache
      console.log('Fetch failed, trying cache:', error);
      
      return caches.match(event.request)
        .then(function(cachedResponse) {
          if (cachedResponse) {
            return cachedResponse;
          }
          
          // If no cache, try with different fetch options (bypass ISP)
          return fetch(event.request, {
            mode: 'no-cors',
            cache: 'force-cache'
          }).catch(function() {
            // Serve offline page for navigation requests
            if (event.request.mode === 'navigate') {
              return caches.match(OFFLINE_URL);
            }
            return new Response('Offline', { status: 503 });
          });
        });
    })
  );
});

// Background sync for blocked requests
self.addEventListener('sync', function(event) {
  if (event.tag === 'retry-fetch') {
    event.waitUntil(retryFailedRequests());
  }
});

// Store failed requests for retry
const failedRequests = [];

function retryFailedRequests() {
  return Promise.all(
    failedRequests.map(function(request) {
      return fetch(request)
        .then(function(response) {
          if (response.ok) {
            // Remove from failed list
            const index = failedRequests.indexOf(request);
            if (index > -1) {
              failedRequests.splice(index, 1);
            }
          }
          return response;
        })
        .catch(function() {
          // Still failing, keep in list
          return null;
        });
    })
  );
}

// Message handler for cache management
self.addEventListener('message', function(event) {
  if (event.data.action === 'skipWaiting') {
    self.skipWaiting();
  }
  
  if (event.data.action === 'clearCache') {
    caches.delete(CACHE_NAME);
  }
  
  if (event.data.action === 'cacheUrl') {
    caches.open(CACHE_NAME).then(function(cache) {
      cache.add(event.data.url);
    });
  }
});

console.log('Service Worker loaded - ISP bypass enabled');
