// A more intelligent Service Worker for the TTTEDDDEL Portal
const CACHE_NAME = 'tttedddel-portal-v2'; // Updated version
const urlsToCache = [
    '/homework_portal/login.php',
    '/homework_portal/student/dashboard.php',
    'https://cdn.tailwindcss.com', // Cache the CSS file
    '/homework_portal/assets/app-icon-192.png',
    '/homework_portal/assets/app-icon-512.png'
];

// Install the service worker and cache key assets
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log('Opened cache');
                return cache.addAll(urlsToCache);
            })
    );
});

// Clean up old caches when a new service worker is activated
self.addEventListener('activate', event => {
    const cacheWhitelist = [CACHE_NAME];
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames.map(cacheName => {
                    if (cacheWhitelist.indexOf(cacheName) === -1) {
                        console.log('Deleting old cache:', cacheName);
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
});

// The intelligent fetch handler
self.addEventListener('fetch', event => {
    // **CRITICAL FIX**: Only handle GET requests.
    // This ignores POST requests (like our login form) and lets the browser handle them normally.
    if (event.request.method !== 'GET') {
        console.log('Service Worker: Ignoring non-GET request', event.request.method, event.request.url);
        return;
    }

    event.respondWith(
        caches.open(CACHE_NAME).then(async (cache) => {
            // 1. Try to get the response from the network
            try {
                const networkResponse = await fetch(event.request);
                // If we get a valid response, put it in the cache and return it
                console.log('Service Worker: Caching new resource', event.request.url);
                cache.put(event.request, networkResponse.clone());
                return networkResponse;
            } catch (error) {
                // 2. If the network fails, try to get it from the cache
                console.log('Service Worker: Fetch failed, trying cache.', error);
                const cachedResponse = await cache.match(event.request);
                if (cachedResponse) {
                    console.log('Service Worker: Serving from cache', event.request.url);
                    return cachedResponse;
                }
                // If it's not in the cache either, it will result in a standard browser error.
                // You could optionally return a generic offline page here.
                return;
            }
        })
    );
});