<template>
  <div class="container mx-auto px-4 py-8">
    <!-- Loading State -->
    <div v-if="marketStore.isLoading || market.isLoading" class="flex justify-center items-center min-h-64">
      <div class="flex flex-col items-center space-y-4">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        <p class="text-gray-600">Loading market...</p>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="market.error" class="flex justify-center items-center min-h-64">
      <div class="text-center">
        <h2 class="text-2xl font-bold text-red-600 mb-4">Failed to load market</h2>
        <p class="text-gray-600 mb-4">{{ market.error }}</p>
        <Button @click="retryLoadMarket" variant="outline">
          Try Again
        </Button>
      </div>
    </div>

    <!-- Market Content -->
    <div v-else>
      <!-- Market Header -->
      <div class="flex items-center justify-between mb-8">
        <div class="flex items-center space-x-4">
          <Avatar v-if="marketStore.activeMarket?.opts?.logo">
            <AvatarImage :src="marketStore.activeMarket.opts.logo" />
            <AvatarFallback>M</AvatarFallback>
          </Avatar>
          <div>
            <h1 class="text-3xl font-bold">
              {{ marketStore.activeMarket?.opts?.name || 'Market' }}
            </h1>
            <p v-if="marketStore.activeMarket?.opts?.description" class="text-gray-600">
              {{ marketStore.activeMarket.opts.description }}
            </p>
          </div>
        </div>
        
        <!-- Search Bar -->
        <div class="flex-1 max-w-md ml-8">
          <Input
            v-model="marketStore.searchText"
            type="text"
            placeholder="Search products..."
            class="w-full"
          />
        </div>
      </div>

      <!-- Category Filters -->
      <div v-if="marketStore.allCategories.length > 0" class="mb-6">
        <div class="flex flex-wrap gap-2">
          <Badge
            v-for="category in marketStore.allCategories"
            :key="category.category"
            :variant="category.selected ? 'default' : 'secondary'"
            class="cursor-pointer hover:bg-blue-100"
            @click="marketStore.toggleCategoryFilter(category.category)"
          >
            {{ category.category }}
            <span class="ml-1 text-xs">({{ category.count }})</span>
          </Badge>
        </div>
      </div>

      <!-- No Products State -->
      <div v-if="marketStore.filteredProducts.length === 0 && !marketStore.isLoading" class="text-center py-12">
        <h3 class="text-xl font-semibold text-gray-600 mb-2">No products found</h3>
        <p class="text-gray-500">Try adjusting your search or filters</p>
      </div>

      <!-- Product Grid -->
      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <ProductCard
          v-for="product in marketStore.filteredProducts"
          :key="product.id"
          :product="product"
          @add-to-cart="addToCart"
          @view-details="viewProduct"
        />
      </div>

      <!-- Cart Summary -->
      <div v-if="marketStore.cartItemCount > 0" class="fixed bottom-4 right-4">
        <Button @click="viewCart" class="shadow-lg">
          <ShoppingCart class="w-5 h-5 mr-2" />
          Cart ({{ marketStore.cartItemCount }})
        </Button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { useMarketStore } from '@/stores/market'
import { useMarket } from '@/composables/useMarket'
import { config } from '@/lib/config'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { ShoppingCart } from 'lucide-vue-next'
import ProductCard from '@/components/market/ProductCard.vue'

const marketStore = useMarketStore()
const market = useMarket()

let unsubscribe: (() => void) | null = null

const loadMarket = async () => {
  try {
    const naddr = config.market.defaultNaddr
    if (!naddr) {
      throw new Error('No market naddr configured')
    }

    await market.connectToMarket()
    await market.loadMarket(naddr)
    
    // Subscribe to real-time updates
    unsubscribe = market.subscribeToMarketUpdates()
    
  } catch (error) {
    console.error('Failed to load market:', error)
  }
}

const retryLoadMarket = () => {
  loadMarket()
}

const addToCart = (product: any) => {
  marketStore.addToCart(product)
}

const viewProduct = (product: any) => {
  // TODO: Navigate to product detail page
  console.log('View product:', product)
}

const viewCart = () => {
  // TODO: Navigate to cart page
  console.log('View cart')
}

onMounted(() => {
  loadMarket()
})

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe()
  }
  market.disconnectFromMarket()
})
</script> 