import { ref, readonly } from 'vue'
import { useMarket } from './useMarket'
import { useMarketStore } from '../stores/market'
import { config } from '@/lib/config'

export function useMarketPreloader() {
  const isPreloading = ref(false)
  const isPreloaded = ref(false)
  const preloadError = ref<string | null>(null)
  
  const market = useMarket()
  const marketStore = useMarketStore()
  
  const preloadMarket = async () => {
    // Don't preload if already done or currently preloading
    if (isPreloaded.value || isPreloading.value) {
      console.log('🛒 Market preload skipped - already loaded or in progress')
      return
    }
    
    console.log('🛒 Starting market preload...')
    
    try {
      isPreloading.value = true
      preloadError.value = null
      
      const naddr = config.market.defaultNaddr
      if (!naddr) {
        console.warn('🛒 No market naddr configured, skipping preload')
        return
      }
      
      console.log('🛒 Using market naddr:', naddr.slice(0, 20) + '...')
      
      // Add timeout protection to prevent hanging
      const timeoutMs = 30000 // 30 seconds
      
      const connectWithTimeout = async () => {
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('Market connection timeout after 30 seconds')), timeoutMs)
        })
        
        return Promise.race([
          market.connectToMarket(),
          timeoutPromise
        ])
      }
      
      const loadWithTimeout = async () => {
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('Market loading timeout after 30 seconds')), timeoutMs)
        })
        
        return Promise.race([
          market.loadMarket(naddr),
          timeoutPromise
        ])
      }
      
      // Connect to market
      console.log('🛒 Connecting to market...')
      await connectWithTimeout()
      
      // Load market data  
      console.log('🛒 Loading market data...')
      await loadWithTimeout()
      
      // Clear any error state since preloading succeeded
      marketStore.setError(null)
      
      isPreloaded.value = true
      console.log('🛒 Market preload completed successfully')
      
    } catch (error) {
      console.error('🛒 Market preload failed:', error)
      console.log('🛒 Attempting fallback with sample data...')
      
      try {
        // Create a basic market with sample data as fallback
        const fallbackMarket = {
          d: 'demo-market',
          pubkey: 'demo',
          relays: ['ws://localhost:5006/nostrrelay/test1'],
          selected: true,
          opts: {
            name: 'Demo Market',
            description: 'Demo market with sample products',
            merchants: [],
            ui: {}
          }
        }
        
        marketStore.addMarket(fallbackMarket)
        marketStore.setActiveMarket(fallbackMarket)
        
        isPreloaded.value = true
        console.log('🛒 Market preload completed with fallback data')
        
      } catch (fallbackError) {
        console.error('🛒 Fallback also failed:', fallbackError)
        preloadError.value = error instanceof Error ? error.message : 'Failed to preload market'
      }
    } finally {
      isPreloading.value = false
    }
  }
  
  const resetPreload = () => {
    isPreloaded.value = false
    preloadError.value = null
  }
  
  return {
    isPreloading: readonly(isPreloading),
    isPreloaded: readonly(isPreloaded),
    preloadError: readonly(preloadError),
    preloadMarket,
    resetPreload
  }
} 