const CACHE_NAME = 'wassili-static-v19';
const ASSETS_TO_CACHE = [
    '/',
    '/index.html',
    '/client-login.html',
    '/client-my-orders.html',
    '/notifications.html',
    '/admin-complaints.html',
    '/captain-login.html',
    '/css/mobile-overrides.css',
    '/css/enhanced-styles.css',
    '/css/dark-mode.css',
    '/js/app-core.js',
    '/js/config.js',
    '/notification-toast.js',
    '/js/native-notifications.js',
    '/js/home.js',
    '/js/order-feature.js',
    '/js/auth-helper.js',
    '/js/input-validator.js',
    '/js/theme-manager.js',
    '/js/onboarding.js',
    '/js/saved-locations.js',
    '/js/native-dialogs.js',
    '/sounds/wassili-bell.wav',
    '/logo.png',
    '/logo-transparent.png',
    '/icons/icon-192x192.png',
    '/icons/icon-512x512.png',
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css',
    'https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css',
    'https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap'
];

// Install Event: Cache Core Assets
self.addEventListener('install', (event) => {
    self.skipWaiting();
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            console.log('[ServiceWorker] Caching core assets');
            // Cache each asset individually so one failure doesn't break everything
            return Promise.allSettled(
                ASSETS_TO_CACHE.map(url =>
                    cache.add(url).catch(err => console.warn('[ServiceWorker] Failed to cache:', url, err.message))
                )
            );
        })
    );
});

// Activate Event: Cleanup Old Caches
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cache) => {
                    if (cache !== CACHE_NAME) {
                        console.log('[ServiceWorker] Clearing old cache', cache);
                        return caches.delete(cache);
                    }
                })
            );
        }).then(() => self.clients.claim())
    );
});

// Fetch Event: Network-First for HTML, Cache-First for assets
self.addEventListener('fetch', (event) => {
    const url = new URL(event.request.url);

    // CRITICAL EXCLUSIONS — bypass service worker entirely for these:
    if (url.pathname.startsWith('/api/') ||
        url.pathname.startsWith('/uploads/') || // Images uploaded by admin — always fetch fresh
        url.pathname.includes('socket.io') ||
        event.request.method !== 'GET') {
        return; // Go directly to network, no caching
    }

    // ✅ Network-First for HTML pages (so admins always get the latest page)
    const isHtml = url.pathname.endsWith('.html') ||
                   url.pathname === '/' ||
                   event.request.headers.get('accept')?.includes('text/html');

    if (isHtml) {
        event.respondWith(
            fetch(event.request).then((response) => {
                // Update cache with fresh copy
                if (response && response.status === 200 && response.type === 'basic') {
                    const responseToCache = response.clone();
                    caches.open(CACHE_NAME).then((cache) => cache.put(event.request, responseToCache));
                }
                return response;
            }).catch(() => {
                // Offline fallback — serve cached copy if network fails
                return caches.match(event.request).then(cached => cached || Response.error());
            })
        );
        return;
    }

    // Cache-First for static assets (CSS, JS, images, fonts)
    event.respondWith(
        caches.match(event.request).then((cachedResponse) => {
            if (cachedResponse) {
                return cachedResponse;
            }

            return fetch(event.request).then((response) => {
                if (!response || response.status !== 200 || response.type !== 'basic') {
                    return response;
                }

                const responseToCache = response.clone();
                caches.open(CACHE_NAME).then((cache) => {
                    cache.put(event.request, responseToCache);
                });

                return response;
            }).catch((error) => {
                console.error('[ServiceWorker] Fetch failed:', error);
                return Response.error();
            });
        })
    );
});

// =====================================================
// 🔔 PUSH NOTIFICATION — Rich display with Wassili logo
// =====================================================
self.addEventListener('push', (event) => {
    let payload = {
        title: 'وصل-لي 🚀',
        body: 'لديك إشعار جديد',
        type: 'general',
        url: '/'
    };

    if (event.data) {
        try {
            const raw = event.data.json();
            payload = {
                title: (raw.notification && raw.notification.title) || raw.title || payload.title,
                body: (raw.notification && raw.notification.body) || raw.body || payload.body,
                type: (raw.data && raw.data.type) || raw.type || 'general',
                url: (raw.data && raw.data.url) || raw.url || '/'
            };
        } catch (_) {
            payload.body = event.data.text();
        }
    }

    const options = {
        body: payload.body,

        // ✅ App logo as the notification icon (large circle)
        icon: '/icons/icon-192x192.png',

        data: {
            url: payload.url || '/',
            type: payload.type || 'general'
        },

        // Brand vibration pattern
        vibrate: [200, 100, 200],

        requireInteraction: false,

        // Action buttons in notification shade
        actions: [
            { action: 'open', title: '📲 فتح التطبيق' },
            { action: 'dismiss', title: '✕ إغلاق' }
        ],

        // Tag prevents duplicate notifications of same type
        tag: 'wassili-' + (payload.type || 'general'),
        renotify: true
    };

    event.waitUntil(
        self.registration.showNotification(payload.title, options)
    );
});

// =====================================================
// 👆 NOTIFICATION CLICK — Deep link to correct page
// =====================================================
self.addEventListener('notificationclick', (event) => {
    event.notification.close();

    if (event.action === 'dismiss') return;

    const data = event.notification.data || {};
    let targetUrl = '/';

    // Explicit URL always wins
    if (data.url && data.url !== '/') {
        targetUrl = data.url;
    }
    // 🏍️ Captain — new order → captain-orders.html (details visible there)
    else if (data.type === 'new_order' || data.type === 'shop_order') {
        targetUrl = '/captain-orders.html' + (data.orderId ? `?highlight=${data.orderId}` : '');
    }
    // 🏍️ Captain — mission accepted/assigned → missions
    else if (data.type === 'order_assigned' || data.type === 'negotiation_accepted') {
        targetUrl = '/captain-missions.html';
    }
    // 👨‍💼 Admin alert → dashboard
    else if (data.type === 'admin_order_alert' || data.type === 'admin_alert') {
        targetUrl = '/admin.html';
    }
    // 💬 Chat → chat page
    else if (data.type === 'chat' || data.type === 'chat_message') {
        const orderId = data.orderId || data.order;
        targetUrl = orderId ? `/chat.html?orderId=${orderId}&receiverId=${data.senderId || ''}` : '/conversations.html';
    }
    // 📦 Client → my orders
    else if (data.type === 'order_accepted' || data.type === 'order_update' || data.type === 'order_delivered') {
        targetUrl = '/client-my-orders.html';
    }

    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (clientList) {
            for (var i = 0; i < clientList.length; i++) {
                var client = clientList[i];
                if (client.url.includes(self.location.origin) && 'focus' in client) {
                    if (client.navigate) client.navigate(targetUrl);
                    return client.focus();
                }
            }
            if (clients.openWindow) {
                return clients.openWindow(targetUrl);
            }
        })
    );
});
