---
import Layout from '../../layouts/Layout.astro';
import Header from '../../components/layout/Header';
import Footer from '../../components/layout/Footer';
import ProductGallery from '../../components/product/ProductGallery';
import ProductVariants from '../../components/product/ProductVariants';
import AddToCart from '../../components/cart/AddToCart';
import StockBadge from '../../components/product/StockBadge';
import StarRating from '../../components/review/StarRating';
import ReviewList from '../../components/review/ReviewList';
import CartDrawer from '../../components/cart/CartDrawer';
import CartBadge from '../../components/cart/CartBadge';

const { slug } = Astro.params;

// Fetch product
const productRes = await fetch(
  `${import.meta.env.PUBLIC_SUPABASE_URL}/rest/v1/products?select=*,category:categories(name,slug),vendor:vendor_profiles(id,store_name,store_slug),variants:product_variants(*)&slug=eq.${slug}&status=eq.active`,
  { headers: { 'apikey': import.meta.env.PUBLIC_SUPABASE_ANON_KEY } }
);
const { data: products } = await productRes.json();
const product = products?.[0];

if (!product) {
  return Astro.redirect('/404');
}

// Fetch reviews
const reviewsRes = await fetch(
  `${import.meta.env.PUBLIC_SUPABASE_URL}/rest/v1/reviews?select=*,user:users(name,avatar_url)&product_id=eq.${product.id}&status=eq.approved&order=created_at.desc`,
  { headers: { 'apikey': import.meta.env.PUBLIC_SUPABASE_ANON_KEY } }
);
const { data: reviews } = await reviewsRes.json();

const avgRating = reviews?.length 
  ? reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length 
  : 0;

// Related products
const relatedRes = await fetch(
  `${import.meta.env.PUBLIC_SUPABASE_URL}/rest/v1/products?select=*&category_id=eq.${product.category_id}&status=eq.active&limit=4&neq=id.${product.id}`,
  { headers: { 'apikey': import.meta.env.PUBLIC_SUPABASE_ANON_KEY } }
);
const { data: relatedProducts } = await relatedRes.json();
---

<Layout title={product.name}>
  <Header />
  
  <div class="container mx-auto px-4 py-8">
    <!-- Breadcrumb -->
    <nav class="text-sm text-gray-500 mb-6 flex items-center gap-2">
      <a href="/" class="hover:text-blue-600 transition-colors">หน้าแรก</a>
      <span>/</span>
      <a href="/products" class="hover:text-blue-600 transition-colors">สินค้า</a>
      {product.category && (
        <>
          <span>/</span>
          <a href={`/products?category=${product.category_id}`} class="hover:text-blue-600 transition-colors">
            {product.category.name}
          </a>
        </>
      )}
      <span>/</span>
      <span class="text-gray-900 truncate max-w-[200px]">{product.name}</span>
    </nav>
    
    <div class="grid lg:grid-cols-2 gap-12">
      <!-- Gallery -->
      <ProductGallery 
        client:load 
        images={product.images || []} 
        productName={product.name} 
      />
      
      <!-- Info -->
      <div>
        <h1 class="text-3xl font-bold mb-2">{product.name}</h1>
        
        {product.vendor && (
          <a href={`/vendors/${product.vendor.store_slug}`} class="text-blue-600 hover:underline mb-4 inline-block">
            โดย {product.vendor.store_name}
          </a>
        )}
        
        <div class="flex items-center gap-4 mb-6">
          <StarRating client:load rating={avgRating} size={20} showValue={true} />
          <span class="text-gray-500">({reviews?.length || 0} รีวิว)</span>
        </div>
        
        <div class="flex items-baseline gap-4 mb-6">
          <span class="text-3xl font-bold text-blue-600">
            ฿{product.price.toLocaleString()}
          </span>
          {product.compare_at_price && product.compare_at_price > product.price && (
            <>
              <span class="text-xl text-gray-400 line-through">
                ฿{product.compare_at_price.toLocaleString()}
              </span>
              <span class="bg-red-100 text-red-600 px-2 py-1 rounded text-sm font-medium">
                ลด {Math.round((1 - product.price / product.compare_at_price) * 100)}%
              </span>
            </>
          )}
        </div>
        
        <div class="mb-6">
          <StockBadge 
            client:load 
            inventory={product.inventory} 
            trackInventory={product.track_inventory}
          />
        </div>
        
        <!-- Variants -->
        {product.variants?.length > 0 && (
          <div class="mb-6">
            <ProductVariants 
              client:load 
              variants={product.variants} 
              onSelect={(v) => {}} 
            />
          </div>
        )}
        
        <!-- Add to Cart -->
        <AddToCart client:idle product={product} />
        
        <!-- Quick Info -->
        <div class="mt-6 space-y-3">
          <div class="flex items-center gap-2 text-gray-600">
            <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
            </svg>
            <span>จัดส่งฟรี สั่งซื้อตั้งแต่ 500 บาท</span>
          </div>
          <div class="flex items-center gap-2 text-gray-600">
            <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
            </svg>
            <span>รับประกันคืนเงินภายใน 7 วัน</span>
          </div>
          <div class="flex items-center gap-2 text-gray-600">
            <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
            </svg>
            <span>ชำระเงินปลอดภัย ผ่อนชำระ 0%</span>
          </div>
        </div>
        
        <!-- Description -->
        {product.description && (
          <div class="mt-8 border-t pt-6">
            <h3 class="font-bold text-lg mb-3">รายละเอียดสินค้า</h3>
            <div class="text-gray-600 whitespace-pre-line prose">
              {product.description}
            </div>
          </div>
        )}
      </div>
    </div>
    
    <!-- Reviews -->
    {reviews && reviews.length > 0 && (
      <section class="mt-16">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-xl font-bold">รีวิวจากลูกค้า</h2>
          <a href={`/products/${slug}#reviews`} class="text-blue-600 hover:underline">
            ดูทั้งหมด ({reviews.length})
          </a>
        </div>
        <ReviewList client:visible reviews={reviews.slice(0, 5)} />
      </section>
    )}
    
    <!-- Related Products -->
    {relatedProducts && relatedProducts.length > 0 && (
      <section class="mt-16">
        <h2 class="text-xl font-bold mb-6">สินค้าที่เกี่ยวข้อง</h2>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-6">
          {relatedProducts.map((p, i) => (
            <a href={`/products/${p.slug}`} class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-shadow">
              <div class="aspect-square bg-gray-100">
                <img src={p.images?.[0] || '/placeholder.jpg'} alt={p.name} class="w-full h-full object-cover" />
              </div>
              <div class="p-4">
                <h3 class="font-medium text-gray-900 line-clamp-2">{p.name}</h3>
                <p class="text-blue-600 font-bold mt-2">฿{p.price.toLocaleString()}</p>
              </div>
            </a>
          ))}
        </div>
      </section>
    )}
  </div>
  
  <Footer />
  <CartDrawer client:load />
  <CartBadge client:load />
</Layout>

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