<template>
  <Card class="overflow-hidden hover:shadow-lg transition-shadow duration-200">
    <!-- Product Image with Cycling and Progressive Loading -->
    <div class="relative group">
      <!-- Show actual image with progressive loading if available -->
      <ProgressiveImage
        v-if="currentImage"
        :src="currentImage"
        :alt="product.name"
        container-class="w-full h-48 bg-muted/50"
        image-class="w-full h-48 object-cover"
        :blur-radius="8"
        :transition-duration="400"
        loading="lazy"
        :show-loading-indicator="false"
        @error="handleImageError"
      />

      <!-- Show placeholder when no image -->
      <div v-else class="w-full h-48 bg-gradient-to-br from-muted/50 to-muted flex items-center justify-center">
        <div class="text-center">
          <Package class="w-12 h-12 mx-auto text-muted-foreground mb-2" />
          <span class="text-xs text-muted-foreground">No image available</span>
        </div>
      </div>

      <!-- Image Navigation Arrows (show on hover if multiple images) -->
      <div v-if="hasMultipleImages" class="opacity-0 group-hover:opacity-100 transition-opacity duration-200">
        <!-- Previous Image Button -->
        <Button
          @click="previousImage"
          type="button"
          size="sm"
          variant="secondary"
          class="absolute left-2 top-1/2 transform -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white border-0 h-8 w-8 p-0"
        >
          <ChevronLeft class="w-4 h-4" />
        </Button>

        <!-- Next Image Button -->
        <Button
          @click="nextImage"
          type="button"
          size="sm"
          variant="secondary"
          class="absolute right-2 top-1/2 transform -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white border-0 h-8 w-8 p-0"
        >
          <ChevronRight class="w-4 h-4" />
        </Button>
      </div>

      <!-- Image Indicators (dots) -->
      <div v-if="hasMultipleImages" class="absolute bottom-2 left-1/2 transform -translate-x-1/2 flex gap-1">
        <div
          v-for="(_, index) in productImages"
          :key="index"
          @click="setCurrentImage(index)"
          class="w-2 h-2 rounded-full cursor-pointer transition-colors duration-200"
          :class="currentImageIndex === index ? 'bg-white' : 'bg-white/50 hover:bg-white/70'"
        />
      </div>

      <!-- Add to Cart Button -->
      <Button
        @click="addToCart"
        :disabled="product.quantity < 1"
        size="sm"
        class="absolute top-2 right-2 bg-blue-600 hover:bg-blue-700 text-white"
      >
        <ShoppingCart class="w-4 h-4" />
      </Button>

      <!-- Out of Stock Badge -->
      <Badge
        v-if="product.quantity < 1"
        variant="destructive"
        class="absolute top-2 left-2"
      >
        Out of Stock
      </Badge>
    </div>
    
    <CardContent class="p-4">
      <!-- Product Name -->
      <CardTitle class="text-lg font-semibold mb-2 line-clamp-2">
        {{ product.name }}
      </CardTitle>
      
      <!-- Product Description -->
      <p v-if="product.description" class="text-gray-600 text-sm mb-3 line-clamp-2">
        {{ product.description }}
      </p>
      
      <!-- Price and Quantity -->
      <div class="flex items-center justify-between mb-3">
        <span class="text-xl font-bold text-green-600">
          {{ formatPrice(product.price, product.currency) }}
        </span>
        <span class="text-sm text-gray-500">
          {{ product.quantity }} left
        </span>
      </div>
      
      <!-- Categories -->
      <div v-if="product.categories && product.categories.length > 0" class="mb-3">
        <div class="flex flex-wrap gap-1">
          <Badge
            v-for="category in product.categories.slice(0, 3)"
            :key="category"
            variant="secondary"
            class="text-xs"
          >
            {{ category }}
          </Badge>
          <Badge
            v-if="product.categories.length > 3"
            variant="outline"
            class="text-xs"
          >
            +{{ product.categories.length - 3 }} more
          </Badge>
        </div>
      </div>
      
      <!-- Stall Name -->
      <div class="text-sm text-gray-500 mb-3">
        {{ product.stallName }}
      </div>
    </CardContent>
    
    <CardFooter class="p-4 pt-0">
      <div class="flex w-full space-x-2">
        <Button
          variant="outline"
          size="sm"
          class="flex-1"
          @click="$emit('view-stall', product.stall_id)"
        >
          Visit Stall
        </Button>
        <Button
          size="sm"
          class="flex-1"
          @click="$emit('view-details', product)"
        >
          View Details
        </Button>
      </div>
    </CardFooter>
  </Card>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Card, CardContent, CardFooter, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import ProgressiveImage from '@/components/ui/image/ProgressiveImage.vue'
import { ShoppingCart, Package, ChevronLeft, ChevronRight } from 'lucide-vue-next'
import type { Product } from '@/modules/market/stores/market'

interface Props {
  product: Product
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'add-to-cart': [product: Product]
  'view-details': [product: Product]
  'view-stall': [stallId: string]
}>()

const imageError = ref(false)
const currentImageIndex = ref(0)

// Computed properties for image cycling
const productImages = computed(() => {
  if (!props.product.images || props.product.images.length === 0) {
    return []
  }
  return props.product.images.filter(img => img && img.trim() !== '')
})

const hasMultipleImages = computed(() => productImages.value.length > 1)

const currentImage = computed(() => {
  if (productImages.value.length === 0) {
    return null
  }
  return productImages.value[currentImageIndex.value]
})

// Image cycling methods
const nextImage = (event?: Event) => {
  event?.stopPropagation()
  if (productImages.value.length > 0) {
    currentImageIndex.value = (currentImageIndex.value + 1) % productImages.value.length
  }
}

const previousImage = (event?: Event) => {
  event?.stopPropagation()
  if (productImages.value.length > 0) {
    currentImageIndex.value = currentImageIndex.value === 0
      ? productImages.value.length - 1
      : currentImageIndex.value - 1
  }
}

const setCurrentImage = (index: number, event?: Event) => {
  event?.stopPropagation()
  if (index >= 0 && index < productImages.value.length) {
    currentImageIndex.value = index
  }
}

// Reset image index when product changes
watch(() => props.product.id, () => {
  currentImageIndex.value = 0
})

const addToCart = () => {
  emit('add-to-cart', props.product)
}

const handleImageError = () => {
  imageError.value = true
}

const formatPrice = (price: number, currency: string) => {
  if (currency === 'sat' || currency === 'sats') {
    return `${price.toLocaleString('en-US')} sats`
  }
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currency.toUpperCase()
  }).format(price)
}
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style> 