import './bootstrap';

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;
window.Echo = new Echo({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT,
    wssPort: import.meta.env.VITE_REVERB_PORT,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

// Register service worker for PWA
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js')
            .then(registration => {
                console.log('SW registered:', registration.scope);

                registration.addEventListener('updatefound', () => {
                    const newWorker = registration.installing;
                    newWorker.addEventListener('statechange', () => {
                        if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                            console.log('New version available!');
                            if (confirm('Hay una nueva versión disponible. ¿Recargar?')) {
                                window.location.reload();
                            }
                        }
                    });
                });
            })
            .catch(error => {
                console.log('SW registration failed:', error);
            });
    });
}

import localforage from 'localforage';

// Generic function to queue any offline action
window.queueOfflineAction = function(action, payload) {
    const pendingAction = { action, payload };
    if (navigator.onLine) {
        // Send immediately
        fetch('/offline/pending', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
            body: JSON.stringify(pendingAction)
        })
        .then(res => res.json())
        .then(data => {
            if (data.queued) {
                console.log('Action queued:', action);
                // Register background sync to process the queue
                if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
                    return navigator.serviceWorker.ready.then(registration => {
                        return registration.sync.register('offline-sync');
                    });
                }
            } else {
                console.error('Failed to queue action:', data);
            }
        })
        .catch(err => {
            console.error('Error queuing action:', err);
        });
    } else {
        // Store in IndexedDB (via localforage)
        localforage.getItem('pendingOffline').then(pending => {
            const list = pending || [];
            list.push(pendingAction);
            localforage.setItem('pendingOffline', list);
            console.log('Action stored offline:', action);
            // Register background sync for when we come back online
            if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
                return navigator.serviceWorker.ready.then(registration => {
                    return registration.sync.register('offline-sync');
                });
            }
        }).catch(err => {
            console.error('Error storing offline action:', err);
        });
    }
}

// Function to store offline progress update (for backward compatibility)
window.offlineProgressUpdate = function(phaseId, progress, comment, location) {
    const payload = { phase_id: phaseId, progress, comment, location };
    window.queueOfflineAction('progress_update', payload);
};

// Function to capture and store image for offline upload
window.captureAndStoreImage = async (file, phaseId, description = '') => {
    try {
        // Convert file to base64
        const base64 = await new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result.split(',')[1]); // Get just the base64 part
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
        
        const payload = {
            file: base64,
            path: `media/${new Date().getTime()}_${file.name}`, // Simple path, could be improved
            model_type: 'App\\Models\\Phase',
            model_id: phaseId,
            name: file.name,
            description: description,
            mime_type: file.type
        };
        
        window.queueOfflineAction('media_upload', payload);
        return true;
    } catch (error) {
        console.error('Error capturing image:', error);
        return false;
    }
};

// Sync pending actions when online
window.addEventListener('online', () => {
    // Trigger a sync attempt
    fetch('/offline/sync', { method: 'POST', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } })
        .then(res => res.json())
        .then(data => {
            console.log('Synced:', data);
        })
        .catch(err => {
            console.error('Error triggering sync:', err);
        });
});

// Also, we can listen for the service worker's message to update the UI if needed
// But for now, we'll rely on the service worker's notification and the online event.
