(function () {
    'use strict';

    const CACHE_NAME = 'tls-extension-cache-v1';
    const CACHE_EXPIRY_DAYS = 7; // Cache for 7 days

    // Patterns to cache
    const CACHE_PATTERNS = [
        'tlscontact.com',
    ];

    console.log('[Static Cache] Interceptor loaded (using Cache API)');

    // Helper to check expiry
    // Since Cache API doesn't natively support expiry, we'll store a companion entry or just rely on Date header if consistent.
    // Simpler: Store a custom header 'x-extension-cached-at' and check it.

    // Override fetch
    const originalFetch = window.fetch;
    window.fetch = async function (...args) {
        const [resource] = args;
        let url;

        try {
            if (typeof resource === 'string') {
                url = resource;
            } else if (resource instanceof URL) {
                url = resource.href;
            } else if (resource && typeof resource === 'object' && 'url' in resource) {
                url = resource.url;
            }
        } catch (e) {
            console.warn('[Static Cache] Error extracting URL:', e);
        }

        if (!url || typeof url !== 'string') {
            return originalFetch(...args);
        }

        // Check if this URL should be cached
        const shouldCache = CACHE_PATTERNS.some(pattern => url.includes(pattern) && !url.includes('appointment-booking') && !url.includes('order-summary') && !url.includes('auth/realms/atlas/'));

        if (shouldCache) {
            try {
                const cache = await window.caches.open(CACHE_NAME);
                const cachedResponse = await cache.match(url);

                if (cachedResponse) {
                    // Check expiry if we added a strict timestamp, or just trust it.
                    // Let's implement a simple expiry check via a custom header we inject.
                    const cachedAt = cachedResponse.headers.get('x-extension-cached-at');
                    if (cachedAt) {
                        const age = Date.now() - parseInt(cachedAt, 10);
                        if (age > CACHE_EXPIRY_DAYS * 24 * 60 * 60 * 1000) {
                            console.log('[Static Cache] Cache expired, deleting:', url);
                            await cache.delete(url);
                        } else {
                            console.log('[Static Cache] Serving from cache:', url);
                            return cachedResponse;
                        }
                    } else {
                        // Legacy cache item or missing header, use it but maybe update it next time?
                        // Prefer serving it to be safe.
                        console.log('[Static Cache] Serving from cache (no timestamp):', url);
                        return cachedResponse;
                    }
                }

                // Not in cache, fetch and cache
                console.log('[Static Cache] Fetching network:', url);
                const response = await originalFetch(...args);

                if (response.ok) {
                    const cloned = response.clone();

                    // We need to inject our custom header for tracking/expiry.
                    // Response headers are immutable, so we must reconstruct the Response.
                    const headers = new Headers(cloned.headers);
                    headers.set('x-extension-cached', 'true');
                    headers.set('x-extension-cached-at', Date.now().toString());
                    headers.set('cache-control', 'public, max-age=604800, immutable'); // Force long cache control

                    const responseToCache = new Response(await cloned.blob(), {
                        status: cloned.status,
                        statusText: cloned.statusText,
                        headers: headers
                    });

                    cache.put(url, responseToCache);
                    console.log('[Static Cache] Cached response:', url);
                }

                return response;

            } catch (err) {
                console.error('[Static Cache] Error in interceptor:', err);
                return originalFetch(...args);
            }
        }

        return originalFetch(...args);
    };

})();
