// Offline support
export class OfflineHandler {
  private offlineQueue: Array<{ url: string; options: any; resolve: any; reject: any; timestamp: number }> = []
  private isOnline: boolean
  
  constructor() {
    // Default to online for Node.js/Bun environments
    // Only use navigator.onLine in browser environments where it's reliable
    if (typeof window !== 'undefined' && typeof navigator !== 'undefined' && 'onLine' in navigator) {
      this.isOnline = navigator.onLine
      
      window.addEventListener('online', () => {
        this.isOnline = true
        this.flushQueue()
      })
      window.addEventListener('offline', () => {
        this.isOnline = false
      })
    } else {
      // In Node.js/Bun, always assume online
      this.isOnline = true
    }
  }
  
  async handleRequest<T>(url: string, options: any, executor: () => Promise<T>): Promise<T> {
    if (this.isOnline) {
      return executor()
    }
    
    // Queue for when back online
    return new Promise((resolve, reject) => {
      this.offlineQueue.push({ 
        url, 
        options, 
        resolve, 
        reject, 
        timestamp: Date.now() 
      })
    })
  }
  
  private async flushQueue(): Promise<void> {
    const queue = [...this.offlineQueue]
    this.offlineQueue = []
    
    for (const item of queue) {
      try {
        // Check if request is still relevant (not older than 5 minutes)
        if (Date.now() - item.timestamp < 5 * 60 * 1000) {
          const response = await fetch(item.url, item.options)
          const data = await response.json()
          item.resolve({ data, response })
        } else {
          item.reject(new Error('Request expired while offline'))
        }
      } catch (error) {
        item.reject(error)
      }
    }
  }
}