<template>
  <component
    :is="linkable ? NuxtLink : 'div'"
    :to="linkable ? localePath(`/catalog/products/${product.uuid}`) : undefined"
    class="block"
    :class="{ 'cursor-pointer': selectable }"
    @click="selectable && $emit('select')"
  >
    <Card
      padding="sm"
      :interactive="linkable || selectable"
      class="relative overflow-hidden"
      :class="[
        isSelected && 'ring-2 ring-primary ring-offset-2'
      ]"
    >
      <!-- Sparkline background -->
      <div v-if="priceHistory && priceHistory.length > 1" class="absolute inset-0 opacity-15">
        <ClientOnly>
          <apexchart
            type="area"
            height="100%"
            :options="chartOptions"
            :series="chartSeries"
          />
        </ClientOnly>
      </div>

      <!-- Content -->
      <div class="relative z-10">
        <div class="flex items-center justify-between gap-2 mb-1">
          <Text size="base" weight="semibold" class="truncate">{{ product.name }}</Text>
          <span
            v-if="trend !== 0"
            class="text-xs font-medium shrink-0"
            :class="trend > 0 ? 'text-success' : 'text-error'"
          >
            {{ trend > 0 ? '↑' : '↓' }} {{ Math.abs(trend) }}%
          </span>
        </div>

        <div class="flex items-center justify-between gap-2">
          <Text v-if="product.offersCount" tone="muted" size="sm">
            {{ product.offersCount }} {{ t('catalog.offers', product.offersCount) }}
          </Text>
          <Text v-if="currentPrice" size="sm" class="text-primary font-bold shrink-0">
            {{ formattedPrice }}
          </Text>
        </div>

        <Text v-if="product.description && !compact" tone="muted" size="sm" class="mt-1">
          {{ product.description }}
        </Text>
      </div>
    </Card>
  </component>
</template>

<script setup lang="ts">
import { NuxtLink } from '#components'

interface Product {
  uuid?: string | null
  name?: string | null
  description?: string | null
  offersCount?: number | null
}

const props = withDefaults(defineProps<{
  product: Product
  selectable?: boolean
  isSelected?: boolean
  compact?: boolean
  priceHistory?: number[]
  currentPrice?: number | null
  currency?: string | null
}>(), {
  priceHistory: () => []
})

defineEmits<{
  (e: 'select'): void
}>()

const localePath = useLocalePath()
const { t } = useI18n()

const linkable = computed(() => !props.selectable && !!props.product.uuid)

// Price formatting
const formattedPrice = computed(() => {
  if (!props.currentPrice) return ''
  const symbol = getCurrencySymbol(props.currency)
  return `${symbol}${props.currentPrice.toLocaleString()}`
})

const getCurrencySymbol = (currency?: string | null) => {
  switch (currency?.toUpperCase()) {
    case 'USD': return '$'
    case 'EUR': return '€'
    case 'RUB': return '₽'
    case 'CNY': return '¥'
    default: return '$'
  }
}

// Calculate trend from price history
const trend = computed(() => {
  if (!props.priceHistory || props.priceHistory.length < 2) return 0
  const first = props.priceHistory[0]
  const last = props.priceHistory[props.priceHistory.length - 1]
  if (!first || first === 0 || !last) return 0
  return Math.round(((last - first) / first) * 100)
})

// Chart configuration
const chartOptions = computed(() => ({
  chart: {
    type: 'area',
    sparkline: { enabled: true },
    animations: { enabled: false }
  },
  stroke: {
    curve: 'smooth',
    width: 2
  },
  fill: {
    type: 'gradient',
    gradient: {
      shadeIntensity: 1,
      opacityFrom: 0.4,
      opacityTo: 0.1
    }
  },
  colors: [trend.value >= 0 ? '#22c55e' : '#ef4444'],
  tooltip: { enabled: false },
  xaxis: { labels: { show: false } },
  yaxis: { labels: { show: false } }
}))

const chartSeries = computed(() => [{
  name: 'Price',
  data: props.priceHistory && props.priceHistory.length > 0 ? props.priceHistory : [0]
}])
</script>
