'use client'

import { useState } from 'react'
import Link from 'next/link'
import { ShoppingCart, Plus, Minus, Package, Check, Star, Tag, Eye, ExternalLink } from 'lucide-react'
import { useCart } from '@/lib/cart'
import { formatCurrency } from '@/lib/types'
import type { StoreTemplate } from '@/lib/storefront/templates'
import { PublicProductLite, RADIUS_CLASS, RADIUS_BTN, headingClass, bodyClass } from './sections'

function hashForDiscount(s: string) {
  let h = 0
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) % 100
  return h
}

// Shared image component with elegant fallbacks
function ProductImage({ 
  product, 
  businessSlug, 
  template, 
  aspect = 'aspect-square',
  contain = false,
  isOutOfStock,
  btnRadius,
}: {
  product: PublicProductLite
  businessSlug: string
  template: StoreTemplate
  aspect?: string
  contain?: boolean
  isOutOfStock: boolean
  btnRadius: string
}) {
  const treatment = template.tokens.imageTreatment
  const radius = RADIUS_CLASS[template.tokens.radius]
  
  const treatmentClasses = {
    sharp: radius,
    soft: radius === 'rounded-none' ? 'rounded-xl' : radius === 'rounded-md' ? 'rounded-2xl' : radius,
    masked: `${radius} overflow-hidden`,
    framed: `${radius} ring-4 ring-[var(--store-surface)] ring-offset-2 ring-offset-[var(--store-background)]`,
    bleed: '-mx-4 -my-4 rounded-none',
    floating: `${radius} shadow-xl`,
  }
  
  // Generate elegant fallback based on product name/category
  const fallbackColors = [
    'from-blue-500 to-blue-700',
    'from-emerald-500 to-emerald-700',
    'from-amber-500 to-amber-700',
    'from-rose-500 to-rose-700',
    'from-violet-500 to-violet-700',
    'from-orange-500 to-orange-700',
    'from-cyan-500 to-cyan-700',
    'from-indigo-500 to-indigo-700',
  ]
  const colorIndex = product.name.charCodeAt(0) % fallbackColors.length
  const fallbackGradient = fallbackColors[colorIndex]
  const initial = product.name.trim().charAt(0).toUpperCase()
  const categoryInitial = product.category.trim().charAt(0).toUpperCase()
  
  return (
    <Link
      href={`/shop/${businessSlug}/product/${product.public_slug}`}
      className={`relative block overflow-hidden group ${aspect} ${treatmentClasses[treatment] || radius}`}
      style={{ backgroundColor: 'var(--store-surface)' }}
      aria-label={product.name}
    >
      {product.image_url ? (
        <img
          src={product.image_url}
          alt={product.name}
          loading="lazy"
          className={`w-full h-full transition-all duration-700 ${contain ? 'object-contain p-4' : 'object-cover'} ${treatment === 'floating' ? 'group-hover:scale-105' : treatment === 'sharp' ? 'group-hover:scale-[1.02]' : ''}`}
        />
      ) : (
        <div className="w-full h-full flex items-center justify-center relative overflow-hidden" style={{ background: `linear-gradient(135deg, ${fallbackGradient})` }}>
          <div className="relative z-10 flex flex-col items-center justify-center gap-2 px-4">
            <span className="text-4xl md:text-6xl font-bold text-white/30">{initial}</span>
            <span className="text-xs font-semibold text-white/40 uppercase tracking-wider">{categoryInitial} {product.category}</span>
          </div>
          <div className="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent" aria-hidden />
          <div className="absolute bottom-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity">
            <span className="text-white/30 text-xs uppercase tracking-wider">No image</span>
          </div>
        </div>
      )}
      {isOutOfStock && (
        <div className="absolute inset-0 bg-black/50 flex items-center justify-center z-10">
          <span className={`px-4 py-2 text-white text-sm font-semibold ${btnRadius}`} style={{ backgroundColor: 'var(--store-secondary)' }}>Out of Stock</span>
        </div>
      )}
    </Link>
  )
}

export function StoreProductCard({
  product, businessSlug, template, currency = 'USD',
}: {
  product: PublicProductLite
  businessSlug: string
  template: StoreTemplate
  currency?: string
}) {
  const { addItem } = useCart()
  const [quantity, setQuantity] = useState(1)
  const [added, setAdded] = useState(false)
  const available = product.available_quantity || 0
  const isOutOfStock = available <= 0
  const isLowStock = available > 0 && available <= 5
  const radius = RADIUS_CLASS[template.tokens.radius]
  const btnRadius = RADIUS_BTN[template.tokens.radius]
  const h = headingClass(template)
  const style = template.tokens.card
  const cardHover = template.tokens.cardHover
  const ctaStyle = template.tokens.ctaStyle

  const handleAddToCart = () => {
    addItem({
      productId: product.id,
      productName: product.name,
      productSlug: product.public_slug,
      quantity,
      unitPrice: product.unit_price,
      imageUrl: product.image_url,
      category: product.category,
    })
    setAdded(true)
    setTimeout(() => setAdded(false), 1200)
    setQuantity(1)
  }

  const price = <span className={`font-extrabold ${h}`}>{formatCurrency(product.unit_price, currency)}</span>

  const addBtn = (label = 'Add to Cart', customClass = '') => (
    <button
      onClick={handleAddToCart}
      disabled={isOutOfStock}
      className={`mt-4 w-full inline-flex items-center justify-center gap-2 px-5 py-3 text-sm font-semibold disabled:opacity-40 disabled:pointer-events-none transition-all duration-200 active:scale-[0.98] ${btnRadius} ${customClass}`}
      style={{ backgroundColor: isOutOfStock ? 'var(--store-surface)' : 'var(--store-primary)', color: isOutOfStock ? 'inherit' : 'var(--store-on-primary)', minHeight: 48 }}
    >
      {added ? <Check className="h-4 w-4" /> : <ShoppingCart className="h-4 w-4" />}
      {isOutOfStock ? 'Out of Stock' : added ? 'Added' : quantity > 1 ? `Add ${quantity}` : label}
    </button>
  )

  const ghostBtn = (label = 'View Details') => (
    <a href={`/shop/${businessSlug}/product/${product.public_slug}`} className={`mt-4 w-full inline-flex items-center justify-center gap-2 px-5 py-3 text-sm font-semibold border-2 transition-all duration-200 ${btnRadius}`} style={{ borderColor: 'var(--store-primary)', color: 'var(--store-primary)', minHeight: 48 }}>
      {label}
      <ExternalLink className="h-4 w-4" />
    </a>
  )

  const hoverClasses = {
    lift: 'hover:-translate-y-1 hover:shadow-xl transition-all duration-300',
    zoom: 'hover:scale-[1.02] transition-transform duration-300',
    glow: 'hover:shadow-[0_0_30px_rgba(0,0,0,0.15)] transition-shadow duration-300',
    reveal: 'transition-all duration-300',
    tilt: 'hover:rotate-1 hover:scale-[1.01] transition-transform duration-300',
    none: '',
  }

  const hoverClass = hoverClasses[cardHover] || hoverClasses.lift

  /* ---------------------------- CARD ANATOMIES --------------------------- */

  // 1. EDITORIAL: Large image, serif title, minimal chrome — African Premium gets sandstone frame + quick view
  if (style === 'editorial') {
    const isAfrican = template.id === 'african-premium'
    if (isAfrican) {
      return (
        <article className="group overflow-hidden" style={{ backgroundColor: 'var(--store-surface)', borderRadius: 2 }}>
          <div className="p-2">
            <div className="relative overflow-hidden" style={{ backgroundColor: 'var(--store-surface)' }}>
              <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[3/4]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
              <Link href={`/shop/${businessSlug}/product/${product.public_slug}`} aria-label={`Quick view ${product.name}`} className="absolute top-3 right-3 w-8 h-8 rounded-full bg-white/90 backdrop-blur grid place-items-center opacity-0 group-hover:opacity-100 transition-opacity shadow-sm">
                <span aria-hidden className="text-sm">♡</span>
              </Link>
            </div>
          </div>
          <div className="px-4 pb-4 pt-2">
            <p className="text-[10px] tracking-[0.18em] uppercase font-semibold mb-1.5" style={{ color: 'var(--store-accent)' }}>{product.category}</p>
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`text-base md:text-lg leading-snug ${h}`}>{product.name}</h3>
            </Link>
            <div className="mt-2 flex items-baseline gap-2">
              <span className="font-bold" style={{ color: 'var(--store-text)' }}>{formatCurrency(product.unit_price, currency)}</span>
              <span className="text-xs" style={{ color: 'var(--store-accent)' }}>$</span>
            </div>
          </div>
        </article>
      )
    }
    return (
      <article className="group">
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[3/4]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="pt-6 pb-2 flex items-start justify-between gap-3 border-b pb-6" style={{ borderColor: 'var(--store-border)' }}>
          <div className="min-w-0">
            <p className="text-[11px] tracking-[0.18em] uppercase opacity-50 mb-2">{product.category}</p>
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`text-lg md:text-xl leading-snug ${h}`}>{product.name}</h3>
            </Link>
          </div>
          <div className="text-right shrink-0">{price}</div>
        </div>
      </article>
    )
  }

  // 2. PREMIUM: Floating price badge, premium feel — Signature & Beauty get bespoke
  if (style === 'premium') {
    const isSignature = template.id === 'signature-premium'
    if (isSignature) {
      return (
        <article className={`group overflow-hidden border bg-white ${radius} ${hoverClass}`} style={{ borderColor: 'var(--store-border)' }}>
          <div className="p-3" style={{ backgroundColor: '#FAF9F6' }}>
            <div className="relative overflow-hidden" style={{ backgroundColor: '#FAF9F6', borderRadius: 4 }}>
              <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[4/5]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
              <span className="absolute top-3 left-3 text-[10px] font-bold tracking-[0.12em] uppercase px-2.5 py-1 rounded-full border shadow-sm" style={{ backgroundColor: 'var(--store-primary)', color: '#fff', borderColor: 'var(--store-primary)' }}>Signature Edition</span>
              <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5">
                <span className="w-2.5 h-2.5 rounded-full border-2" style={{ backgroundColor: '#D4AF37', borderColor: '#fff', boxShadow: '0 0 0 1px #D4AF37' }} />
                <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: '#0F172A', border: '1px solid #fff' }} />
                <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: '#E5E7EB', border: '1px solid #fff' }} />
              </div>
            </div>
          </div>
          <div className="p-4">
            <p className="text-[10px] tracking-[0.14em] uppercase opacity-50">{product.category} • Ref. {product.sku ? product.sku.slice(0, 6).toUpperCase() : 'ED.01'}</p>
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`mt-1 font-serif font-semibold leading-snug line-clamp-1 ${h}`}>{product.name}</h3>
            </Link>
            <div className="mt-3 flex items-baseline justify-between">
              <span className="font-bold" style={{ color: 'var(--store-text)' }}>{formatCurrency(product.unit_price, currency)}</span>
              <span className="text-xs opacity-50">{available > 0 ? 'In stock' : 'Made to order'}</span>
            </div>
          </div>
        </article>
      )
    }
    const isBeauty = template.id === 'beauty-wellness'
    if (isBeauty) {
      return (
        <article className={`group overflow-hidden border bg-white ${hoverClass}`} style={{ borderColor: '#FFE4E6', borderRadius: 20, boxShadow: '0 4px 20px rgba(159,18,57,0.04)' }}>
          <div className="relative overflow-hidden" style={{ borderRadius: '20px 20px 0 0', backgroundColor: '#FFFFFF' }}>
            <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[4/5]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
            <span className="absolute top-3 left-3 text-[10px] font-bold tracking-wide uppercase px-2.5 py-1 rounded-full" style={{ backgroundColor: '#FFF1F2', color: '#9F1239', border: '1px solid #FFE4E6' }}>Clean Beauty</span>
            {!isOutOfStock && (
              <span className="absolute bottom-3 left-3 right-3 translate-y-full group-hover:translate-y-0 transition-transform duration-300">
                <button onClick={handleAddToCart} className="w-full py-2.5 text-xs font-bold rounded-full shadow-md" style={{ backgroundColor: 'var(--store-primary)', color: '#fff' }}>Add to Routine</button>
              </span>
            )}
          </div>
          <div className="p-4">
            <p className="text-[11px] opacity-60">For Sensitive & Dry Skin • 50ml / 1.7 fl oz</p>
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`mt-1 font-serif font-semibold leading-snug line-clamp-1 ${h}`} style={{ color: '#4C0519' }}>{product.name}</h3>
            </Link>
            <div className="mt-3 flex items-baseline justify-between">
              <span className="font-bold" style={{ color: '#4C0519' }}>{formatCurrency(product.unit_price, currency)}</span>
              <span className="text-xs px-2 py-1 rounded-full" style={{ backgroundColor: '#FFF1F2', color: '#9F1239', border: '1px solid #FFE4E6' }}>{available > 0 ? 'In stock' : 'Out of stock'}</span>
            </div>
          </div>
        </article>
      )
    }
    return (
      <article className={`group relative ${hoverClass} bg-[var(--store-background)] ${radius}`}>
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[4/5]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="p-5">
          <div className="flex items-start justify-between gap-2 mb-2">
            <span className="text-[10px] font-semibold uppercase tracking-wider px-2 py-0.5 rounded" style={{ background: 'var(--store-accent)', color: '#fff' }}>{product.category}</span>
            {!isOutOfStock && available <= 5 && (
              <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full" style={{ background: 'var(--store-accent)', color: '#fff' }}>Low Stock</span>
            )}
          </div>
          <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
            <h3 className={`font-semibold leading-snug line-clamp-1 ${h}`}>{product.name}</h3>
          </Link>
          <div className="mt-3 flex items-baseline justify-between gap-2">
            <span className="font-extrabold text-lg" style={{ color: 'var(--store-primary)' }}>{formatCurrency(product.unit_price, currency)}</span>
            {product.sku && <span className="text-[10px] font-mono opacity-40">{product.sku.slice(0, 12)}</span>}
          </div>
          {addBtn()}
        </div>
        {/* Floating accent line */}
        <div className="absolute bottom-0 left-1/2 -translate-x-1/2 w-0 group-hover:w-1/2 h-[3px] transition-all duration-500" style={{ background: 'var(--store-accent)' }} />
      </article>
    )
  }

  // 3. SPEC: Technical specs, mono font, compact
  if (style === 'spec') {
    return (
      <article className={`group flex flex-col overflow-hidden border ${hoverClass} ${radius}`} style={{ borderColor: 'var(--store-border)', backgroundColor: 'var(--store-background)' }}>
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="h-40" contain={true} isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="p-4 flex flex-col flex-1">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[10px] font-mono uppercase tracking-wider px-2 py-0.5 rounded-sm" style={{ backgroundColor: 'var(--store-surface)', color: 'var(--store-muted, inherit)' }}>{product.category}</span>
            {product.sku && <span className="text-[10px] font-mono opacity-40">{product.sku.slice(0, 10)}</span>}
          </div>
          <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
            <h3 className={`font-semibold leading-snug line-clamp-1 ${h}`}>{product.name}</h3>
          </Link>
          <p className="text-xs font-mono mt-1.5 mb-3" style={{ color: available > 0 ? 'var(--store-accent)' : 'inherit' }}>
            {available > 0 ? `${available} in stock` : 'out of stock'}
          </p>
          <div className="mt-auto flex items-center justify-between gap-2 pt-3 border-t" style={{ borderColor: 'var(--store-border)' }}>
            {price}
            {!isOutOfStock && (
              <button onClick={handleAddToCart} aria-label={`Add ${product.name} to cart`} className="px-3 py-2 text-xs font-bold" style={{ backgroundColor: 'var(--store-primary)', color: 'var(--store-on-primary)', borderRadius: template.tokens.radius === 'none' ? 0 : 6, minHeight: 36 }}>
                ADD
              </button>
            )}
          </div>
        </div>
      </article>
    )
  }

  // 4. PRACTICAL: Availability-first, big button — Agriculture & Local get bespoke
  if (style === 'practical') {
    const isAgriculture = template.id === 'agriculture-farm'
    if (isAgriculture) {
      return (
        <article className={`group flex flex-col overflow-hidden bg-white ${radius} ${hoverClass}`} style={{ border: '1px solid #D1E0D2' }}>
          <div className="relative">
            <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[4/3]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
            <span className="absolute top-3 right-3 text-[10px] font-bold tracking-widest uppercase px-2.5 py-1 rounded-full" style={{ backgroundColor: 'var(--store-primary)', color: '#fff' }}>Farm Direct</span>
          </div>
          <div className="p-4 flex flex-col flex-1">
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`font-bold leading-snug line-clamp-1 ${h} store-heading-serif`}>{product.name}</h3>
            </Link>
            <p className="text-xs mt-1 opacity-60">Grade A • 50kg Sack • Export Quality</p>
            <div className="mt-3 flex items-baseline justify-between gap-2">
              <span className="font-extrabold text-lg" style={{ color: 'var(--store-primary)' }}>{formatCurrency(product.unit_price, currency)}</span>
              <span className="text-xs opacity-60">{available > 0 ? `${available} in stock` : 'Out of stock'}</span>
            </div>
            <div className="mt-3">{addBtn('Add to Basket')}</div>
          </div>
        </article>
      )
    }
    const isLocal = template.id === 'local-market'
    if (isLocal) {
      const discount = 15 + (hashForDiscount(product.name) % 20)
      const hasDiscount = !isOutOfStock
      return (
        <article className={`group flex flex-col overflow-hidden bg-white border hover:shadow-md transition-all ${radius} ${hoverClass}`} style={{ borderColor: '#E2E8F0' }}>
          <div className="relative">
            <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-square" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
            {hasDiscount && <span className="absolute top-2 right-2 text-xs font-bold px-2 py-1 rounded-full" style={{ backgroundColor: '#DC2626', color: '#fff' }}>-{discount}%</span>}
            <span className="absolute top-2 left-2 text-[10px] font-medium px-2 py-1 rounded-full bg-white/90 backdrop-blur border flex items-center gap-1" style={{ borderColor: '#E2E8F0' }}><span className="w-1.5 h-1.5 rounded-full bg-green-500" /> {product.category} • Verified</span>
          </div>
          <div className="p-3 flex flex-col flex-1 gap-1.5">
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`text-sm font-semibold leading-tight line-clamp-2 min-h-[2.5em] ${h}`}>{product.name}</h3>
            </Link>
            <div className="flex items-center gap-1 text-xs">
              <span style={{ color: '#F59E0B' }}>★★★★★</span><span className="font-medium">4.8</span><span className="opacity-50">(120)</span>
            </div>
            <div className="flex items-baseline gap-2">
              <span className="font-extrabold text-sm" style={{ color: 'var(--store-primary)' }}>{formatCurrency(product.unit_price, currency)}</span>
              {hasDiscount && <span className="text-xs line-through opacity-40">{formatCurrency(product.unit_price * 1.25, currency)}</span>}
              <span className="ml-auto text-xs font-medium" style={{ color: available > 0 ? '#16A34A' : '#DC2626' }}>{available > 0 ? 'In stock' : 'Out of stock'}</span>
            </div>
            <button onClick={handleAddToCart} disabled={isOutOfStock} className="mt-1 w-full inline-flex items-center justify-center gap-1.5 py-2 text-xs font-bold rounded-full disabled:opacity-40" style={{ backgroundColor: 'var(--store-primary)', color: '#fff', minHeight: 36 }}>
              <Plus className="h-3.5 w-3.5" /> Add
            </button>
          </div>
        </article>
      )
    }
    return (
      <article className={`group flex flex-col overflow-hidden shadow-sm hover:shadow-md transition-shadow bg-[var(--store-background)] ${radius} ${hoverClass}`}>
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-square" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="p-4 flex flex-col flex-1">
          <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
            <h3 className={`font-bold leading-snug line-clamp-2 ${h}`}>{product.name}</h3>
          </Link>
          <div className="mt-3 flex items-baseline justify-between gap-2">
            {price}
            <span className="text-[11px] font-semibold px-2.5 py-1 rounded-full whitespace-nowrap"
              style={available <= 0
                ? { backgroundColor: 'var(--store-surface)', opacity: 0.7 }
                : available <= 5
                  ? { backgroundColor: 'var(--store-accent)', color: '#fff' }
                  : { color: 'var(--store-accent)', fontWeight: 700 }}>
              {available <= 0 ? 'Out of Stock' : available <= 5 ? `Only ${available} left` : 'In stock'}
            </span>
          </div>
          <div className="mt-auto">{addBtn()}</div>
        </div>
      </article>
    )
  }

  // 5. DENSE: Compact, marketplace style
  if (style === 'dense') {
    return (
      <article className={`group flex flex-col overflow-hidden border bg-[var(--store-background)] hover:shadow-md transition-shadow ${radius} ${hoverClass}`} style={{ borderColor: 'var(--store-border)' }}>
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[5/4]" contain={true} isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="p-3 flex flex-col flex-1 gap-1.5">
          <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
            <h3 className={`text-sm font-semibold leading-tight line-clamp-2 min-h-[2.4em] ${h}`}>{product.name}</h3>
          </Link>
          <div className="mt-auto flex items-center justify-between gap-2">
            <span className="font-extrabold text-sm">{formatCurrency(product.unit_price, currency)}</span>
            {!isOutOfStock && (
              <button onClick={handleAddToCart} aria-label={`Add ${product.name} to cart`} className="p-2 rounded-lg" style={{ backgroundColor: 'var(--store-primary)', color: 'var(--store-on-primary)' }}>
                <Plus className="h-4 w-4" />
              </button>
            )}
          </div>
        </div>
      </article>
    )
  }

  // 6. SERVICE: No quantity, description, "Learn more" CTA
  if (style === 'service') {
    return (
      <article className={`group flex flex-col p-5 md:p-7 border ${hoverClass} ${radius}`} style={{ borderColor: 'var(--store-border)', backgroundColor: 'var(--store-background)' }}>
        <span className="text-[11px] font-bold tracking-[0.2em] uppercase mb-3" style={{ color: 'var(--store-accent)' }}>{product.category}</span>
        <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
          <h3 className={`text-xl md:text-2xl leading-snug mb-3 ${h}`}>{product.name}</h3>
        </Link>
        <p className={`text-sm opacity-70 leading-relaxed line-clamp-3 flex-1 ${bodyClass(template)}`}>{product.description || 'Professional service tailored to your needs.'}</p>
        <div className="mt-5 pt-4 border-t flex items-center justify-between" style={{ borderColor: 'var(--store-border)' }}>
          <span className="text-sm opacity-70">Starting from</span>
          {price}
        </div>
        <Link href={`/shop/${businessSlug}/product/${product.public_slug}`} className={`mt-4 inline-flex items-center justify-center px-5 py-3 text-sm font-semibold border ${btnRadius}`} style={{ borderColor: 'var(--store-primary)', color: 'var(--store-primary)', minHeight: 48 }}>
          Learn more <ExternalLink className="h-4 w-4 ml-1" />
        </Link>
      </article>
    )
  }

  // 7. FASHION: Large image, minimal text, hover reveal
  if (style === 'fashion') {
    return (
      <article className="group relative">
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[2/3]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" aria-hidden />
        <div className="absolute bottom-0 left-0 right-0 p-5 pb-6 transform translate-y-full group-hover:translate-y-0 transition-transform duration-500">
          <div className="flex items-end justify-between gap-3">
            <div>
              <p className="text-[10px] uppercase tracking-widest text-white/70 mb-1">{product.category}</p>
              <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
                <h3 className={`font-semibold leading-snug line-clamp-1 text-white ${h}`}>{product.name}</h3>
              </Link>
            </div>
            <div className="text-right">
              <span className="font-extrabold text-white text-lg">{formatCurrency(product.unit_price, currency)}</span>
            </div>
          </div>
          {!isOutOfStock && (
            <button onClick={handleAddToCart} className="mt-3 w-full py-2.5 text-sm font-semibold rounded-full" style={{ backgroundColor: 'var(--store-primary)', color: 'var(--store-on-primary)' }}>
              <ShoppingCart className="h-4 w-4 mr-2" /> Add to Bag
            </button>
          )}
        </div>
      </article>
    )
  }

  // 8. FOOD: Warm, descriptive, with description visible — Coffee gets oat + flavor tags + roast meter
  if (style === 'food') {
    const isCoffee = template.id === 'coffee-food'
    const isRestaurant = template.id === 'construction-industrial'
    if (isCoffee) {
      return (
        <article className={`group flex flex-col overflow-hidden ${hoverClass}`} style={{ backgroundColor: 'var(--store-surface)', borderRadius: 12, border: '1px solid var(--store-border)' }}>
          <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-square" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
          <div className="p-4 flex flex-col flex-1">
            <div className="flex items-center gap-2 mb-2">
              <span className="text-[10px] font-bold tracking-widest uppercase px-2 py-1 rounded-full" style={{ backgroundColor: 'var(--store-accent)', color: '#fff' }}>{product.category}</span>
              <span className="text-[10px] opacity-60 ml-auto">250g / 1kg</span>
            </div>
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`font-bold leading-snug line-clamp-1 ${h} store-heading-serif`}>{product.name}</h3>
            </Link>
            <div className="mt-2 flex flex-wrap gap-1.5">
              <span className="text-[10px] px-2 py-1 rounded-full border" style={{ backgroundColor: 'var(--store-background)', borderColor: 'var(--store-border)', color: 'var(--store-text)' }}>Notes: Chocolate, Hazelnut</span>
            </div>
            <div className="mt-2 flex items-center gap-1">
              {[1,2,3,4,5].map(i => <span key={i} className={`w-1.5 h-4 rounded-full ${i <= 3 ? '' : 'opacity-20'}`} style={{ backgroundColor: 'var(--store-primary)' }} />)}
              <span className="text-xs ml-1 opacity-60">Roast 3/5</span>
            </div>
            <div className="mt-3 flex items-baseline justify-between gap-2 pt-3 border-t" style={{ borderColor: 'var(--store-border)' }}>
              <span className="font-extrabold text-lg" style={{ color: 'var(--store-primary)' }}>{formatCurrency(product.unit_price, currency)}</span>
              {!isOutOfStock && <button onClick={handleAddToCart} className="px-4 py-2 text-xs font-bold rounded-full" style={{ backgroundColor: 'var(--store-primary)', color: '#FFFBEB' }}>Add</button>}
            </div>
          </div>
        </article>
      )
    }
    if (isRestaurant) {
      // Deterministic but content-derived dietary tag for visual demo: cycle through the spec's badges
      const dietaryTags = ["Vegan", "Gluten-Free", "Spicy 🌶️", "Chef's Pick"]
      const tagIndex = (product.name.length + (product.category?.length || 0)) % dietaryTags.length
      const dietaryTag = dietaryTags[tagIndex]
      const isChef = dietaryTag === "Chef's Pick"
      const isSpicy = dietaryTag.startsWith('Spicy')
      return (
        <article className={`group flex flex-col overflow-hidden ${hoverClass}`} style={{ backgroundColor: 'var(--store-surface)', borderRadius: 12, border: '1px solid var(--store-border)', boxShadow: '0 4px 16px rgba(0,0,0,0.18)' }}>
          <div className="relative">
            <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[16/9]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
            {/* Floating dietary badge on top right */}
            <span
              aria-label={dietaryTag}
              className="absolute top-3 right-3 z-10 text-[10px] font-bold uppercase tracking-[0.15em] px-3 py-1.5 rounded-full shadow-md"
              style={{
                backgroundColor: isChef ? 'var(--store-accent)' : isSpicy ? '#DC2626' : 'var(--store-surface)',
                color: isChef || isSpicy ? '#fff' : 'var(--store-text)',
                border: !isChef && !isSpicy ? '1px solid var(--store-border)' : 'none',
              }}
            >
              {dietaryTag}
            </span>
          </div>
          <div className="p-5 flex flex-col flex-1">
            <div className="flex items-center justify-between gap-2 mb-2">
              <span className="text-[10px] font-bold tracking-[0.18em] uppercase" style={{ color: 'var(--store-accent)' }}>{product.category}</span>
              {!isOutOfStock && isLowStock && (
                <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full" style={{ background: 'var(--store-warning, var(--store-accent))', color: '#fff' }}>Limited</span>
              )}
            </div>
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`font-bold leading-snug ${h} store-heading-serif`} style={{ fontSize: '1.25rem' }}>{product.name}</h3>
            </Link>
            {product.description && (
              <p className={`mt-2 text-sm leading-relaxed opacity-70 line-clamp-2 ${bodyClass(template)}`}>{product.description}</p>
            )}
            <div className="mt-auto pt-4">
              <div className="flex items-baseline justify-between gap-3 mb-3">
                <span className="font-extrabold text-xl" style={{ color: 'var(--store-accent)' }}>{formatCurrency(product.unit_price, currency)}</span>
                <span className="text-[10px] uppercase tracking-widest opacity-50">Serves 1</span>
              </div>
              {/* Add to Order pinned to card bottom */}
              <button
                onClick={handleAddToCart}
                disabled={isOutOfStock}
                className="w-full inline-flex items-center justify-center gap-2 px-4 py-3 text-xs font-bold uppercase tracking-wider rounded-xl disabled:opacity-40 disabled:pointer-events-none transition-transform active:scale-[0.98]"
                style={{ backgroundColor: isOutOfStock ? 'var(--store-secondary)' : 'var(--store-primary)', color: '#fff', minHeight: 44 }}
              >
                {added ? <Check className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
                {isOutOfStock ? 'Sold Out' : added ? 'Added to Order' : 'Add to Order'}
              </button>
            </div>
          </div>
        </article>
      )
    }
    return (
      <article className={`group flex flex-col overflow-hidden bg-[var(--store-background)] ${radius} ${hoverClass}`}>
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-square" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="p-4 flex flex-col flex-1">
          <div className="flex items-center justify-between gap-2 mb-2">
            <span className="text-[10px] font-semibold uppercase tracking-wider px-2 py-0.5 rounded-full" style={{ background: 'var(--store-accent)', color: '#fff' }}>{product.category}</span>
            {!isOutOfStock && isLowStock && (
              <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full" style={{ background: 'var(--store-warning, var(--store-accent))', color: '#fff' }}>Limited</span>
            )}
          </div>
          <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
            <h3 className={`font-bold leading-snug line-clamp-1 ${h}`}>{product.name}</h3>
          </Link>
          {product.description && <p className="mt-1.5 text-sm opacity-60 line-clamp-2 ${bodyClass(template)}">{product.description}</p>}
          <div className="mt-auto flex items-baseline justify-between gap-2 pt-3 border-t" style={{ borderColor: 'var(--store-border)' }}>
            <span className="font-extrabold" style={{ color: 'var(--store-primary)' }}>{formatCurrency(product.unit_price, currency)}</span>
            {addBtn('Add')}
          </div>
        </div>
      </article>
    )
  }

  // 9. MARKETPLACE: Ultra-compact, info-dense
  if (style === 'marketplace') {
    return (
      <article className={`group flex flex-col overflow-hidden border bg-[var(--store-background)] ${radius} ${hoverClass}`} style={{ borderColor: 'var(--store-border)' }}>
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[4/3]" contain={true} isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="p-2.5 flex flex-col flex-1 gap-1">
          <div className="flex items-center justify-between">
            <span className="text-[10px] font-medium uppercase tracking-wider px-1.5 py-0.5 rounded" style={{ background: 'var(--store-surface)', color: 'var(--store-text)' }}>{product.category}</span>
            {product.sku && <span className="text-[9px] font-mono opacity-40">{product.sku.slice(0, 8)}</span>}
          </div>
          <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
            <h3 className={`text-sm font-semibold leading-tight line-clamp-2 ${h}`}>{product.name}</h3>
          </Link>
          <div className="mt-auto flex items-center justify-between gap-2 pt-1 border-t" style={{ borderColor: 'var(--store-border)' }}>
            <span className="font-extrabold text-sm">{formatCurrency(product.unit_price, currency)}</span>
            <div className="flex items-center gap-1">
              <Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
              <span className="text-[11px] font-medium">4.8</span>
            </div>
          </div>
          {!isOutOfStock && (
            <button onClick={handleAddToCart} className="mt-1 w-full py-2 text-xs font-bold rounded" style={{ backgroundColor: 'var(--store-primary)', color: 'var(--store-on-primary)' }}>
              Add to Cart
            </button>
          )}
        </div>
      </article>
    )
  }

  // 10. PHOTO-FIRST: Full bleed image, overlay content
  if (style === 'photo-first') {
    return (
      <article className="group relative">
        <ProductImage product={product} businessSlug={businessSlug} template={template} aspect="aspect-[3/4]" isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
        <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" aria-hidden />
        <div className="absolute bottom-0 left-0 right-0 p-5 pb-6 transform translate-y-full group-hover:translate-y-0 transition-transform duration-500">
          <p className="text-[10px] uppercase tracking-widest text-white/70 mb-1">{product.category}</p>
          <div className="flex items-end justify-between gap-3 mb-3">
            <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
              <h3 className={`font-semibold leading-snug line-clamp-1 text-white ${h}`}>{product.name}</h3>
            </Link>
            <span className="font-bold text-white shrink-0">{formatCurrency(product.unit_price, currency)}</span>
          </div>
          {!isOutOfStock && addBtn('Add to Cart')}
        </div>
      </article>
    )
  }

  // DEFAULT: Elevated, Minimal, Blocky, Soft, Outline (photo-first handled above)
  const CARD_STYLE: Record<string, string> = {
    elevated: 'shadow-md group-hover:shadow-xl bg-[var(--store-background)]',
    minimal: 'bg-transparent group-hover:opacity-90',
    blocky: 'border-2 shadow-[6px_6px_0_0_var(--store-text)] bg-[var(--store-background)]',
    soft: 'shadow-sm group-hover:shadow-lg bg-[var(--store-background)]',
    outline: 'border border-current/15 bg-[var(--store-background)] hover:border-current/40',
  }
  const photoFirst = false as boolean
  const cardStyle = CARD_STYLE[style as string] || CARD_STYLE.elevated

  return (
    <article className={`group flex flex-col overflow-hidden transition-all ${radius} ${cardStyle} ${hoverClass}`}>
      <ProductImage product={product} businessSlug={businessSlug} template={template} aspect={photoFirst ? 'aspect-[3/4]' : 'aspect-square'} isOutOfStock={isOutOfStock} btnRadius={btnRadius} />
      {photoFirst && (
        <div className="-mt-16 relative z-10 p-4 pt-0" style={{ paddingBottom: 0 }}>
          <div className="p-4 rounded-xl backdrop-blur-md" style={{ background: 'color-mix(in srgb, var(--store-text) 85%, transparent)', color: 'var(--store-background)' }}>
            <p className="text-[10px] uppercase tracking-widest opacity-60">{product.category}</p>
            <div className="flex items-end justify-between gap-2 mt-1">
              <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
                <h3 className={`font-semibold leading-snug line-clamp-1 ${h}`}>{product.name}</h3>
              </Link>
              <span className="font-bold shrink-0">{formatCurrency(product.unit_price, currency)}</span>
            </div>
            {!isOutOfStock && addBtn()}
          </div>
        </div>
      )}
      {!photoFirst && (
        <div className="flex flex-col flex-1 p-4">
          {product.category && (
            <span className="text-xs uppercase tracking-wider opacity-50 mb-1">{product.category}</span>
          )}
          <Link href={`/shop/${businessSlug}/product/${product.public_slug}`}>
            <h3 className={`font-semibold leading-snug line-clamp-2 ${h}`}>{product.name}</h3>
          </Link>
          {product.description && (
            <p className={`mt-1 text-sm opacity-60 line-clamp-2 flex-1 ${bodyClass(template)}`}>{product.description}</p>
          )}
          <div className={`flex items-center justify-between gap-2 ${photoFirst ? 'mt-1' : 'mt-3'}`}>
            {price}
            {!isOutOfStock && available <= 5 && (
              <span className="text-xs px-2 py-0.5 rounded-full" style={{ backgroundColor: 'var(--store-accent)', color: '#fff' }}>Only {available} left</span>
            )}
          </div>
          {addBtn()}
          {!isOutOfStock && available > 5 && quantity > 1 && (
            <div className="mt-2 flex items-center justify-center gap-3 text-xs">
              <button onClick={() => setQuantity(Math.max(1, quantity - 1))} aria-label="Decrease quantity" className="px-2 py-0.5 rounded border border-current/20">−</button>
              <span>{quantity}</span>
              <button onClick={() => setQuantity(Math.min(available, quantity + 1))} aria-label="Increase quantity" className="px-2 py-0.5 rounded border border-current/20">+</button>
            </div>
          )}
        </div>
      )}
    </article>
  )
}