"use client"

import { SWRConfiguration } from "swr"

// SWR configuration that works well with offline mode
export const swrConfig: SWRConfiguration = {
  // Revalidate on focus (when user returns to tab)
  revalidateOnFocus: true,
  
  // Revalidate when network reconnects
  revalidateOnReconnect: true,
  
  // Keep cached data when error occurs (important for offline)
  keepPreviousData: true,
  
  // Don't throw on errors - handle gracefully
  shouldRetryOnError: true,
  
  // Retry configuration
  errorRetryCount: 3,
  errorRetryInterval: 5000,
  
  // Custom fetcher that handles offline state
  fetcher: async (url: string) => {
    const isOnline = typeof navigator !== "undefined" ? navigator.onLine : true
    
    if (!isOnline) {
      // Try to get from localStorage cache
      const cacheKey = `swr-cache-${url}`
      const cached = localStorage.getItem(cacheKey)
      if (cached) {
        const { data, timestamp } = JSON.parse(cached)
        console.log("[SWR] Offline - returning cached data for:", url)
        return data
      }
      throw new Error("Offline and no cached data")
    }
    
    const res = await fetch(url)
    
    if (!res.ok) {
      // If error, try to return cached data
      const cacheKey = `swr-cache-${url}`
      const cached = localStorage.getItem(cacheKey)
      if (cached) {
        const { data } = JSON.parse(cached)
        console.warn("[SWR] Fetch error, returning cached data for:", url)
        return data
      }
      throw new Error(`API error: ${res.status}`)
    }
    
    const data = await res.json()
    
    // Cache successful responses
    const cacheKey = `swr-cache-${url}`
    try {
      localStorage.setItem(cacheKey, JSON.stringify({
        data,
        timestamp: Date.now(),
      }))
    } catch (e) {
      // localStorage might be full
      console.warn("[SWR] Failed to cache response:", e)
    }
    
    return data
  },
  
  // Use localStorage as provider for persistence
  provider: () => {
    // Initialize the provider with data from localStorage
    const map = new Map<string, any>()
    
    if (typeof window !== "undefined") {
      // Load cached data on init
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key?.startsWith("swr-cache-")) {
          try {
            const { data } = JSON.parse(localStorage.getItem(key) || "{}")
            const url = key.replace("swr-cache-", "")
            map.set(url, data)
          } catch (e) {
            // Invalid cache entry
          }
        }
      }
    }
    
    return map
  },
}

// Helper to clear SWR cache
export function clearSwrCache() {
  if (typeof window === "undefined") return
  
  const keysToRemove: string[] = []
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (key?.startsWith("swr-cache-")) {
      keysToRemove.push(key)
    }
  }
  
  keysToRemove.forEach(key => localStorage.removeItem(key))
  console.log("[SWR] Cleared", keysToRemove.length, "cached entries")
}

// Check if data is from cache
export function isDataFromCache(url: string): boolean {
  const cacheKey = `swr-cache-${url}`
  return !!localStorage.getItem(cacheKey)
}
