---
import Layout from '../../layouts/Layout.astro';
import Header from '../../components/layout/Header';
import Footer from '../../components/layout/Footer';
import ProductCard from '../../components/product/ProductCard.astro';
import ProductFilters from '../../components/product/ProductFilters';
import CartDrawer from '../../components/cart/CartDrawer';
import CartBadge from '../../components/cart/CartBadge';

const { searchParams } = Astro.url;
const category = searchParams.get('category');
const sort = searchParams.get('sort') || 'created_at.desc';
const page = parseInt(searchParams.get('page') || '1');
const limit = 20;

// Fetch categories for filter
const categoriesRes = await fetch(`${import.meta.env.PUBLIC_SUPABASE_URL}/rest/v1/categories?select=*&isnull=parent_id&order=name.asc`, {
  headers: { 'apikey': import.meta.env.PUBLIC_SUPABASE_ANON_KEY }
});
const categories = await categoriesRes.json();

// Build query for products
let productUrl = `${import.meta.env.PUBLIC_SUPABASE_URL}/rest/v1/products?select=*,category:categories(name,slug),vendor:vendor_profiles(id,store_name,store_slug)&status=eq.active&limit=${limit}&offset=${(page - 1) * limit}&order=${sort}`;
if (category) {
  productUrl += `&category_id=eq.${category}`;
}

const response = await fetch(productUrl, {
  headers: { 'apikey': import.meta.env.PUBLIC_SUPABASE_ANON_KEY }
});
const products = await response.json();

// Get category name if filtered
const categoryName = category ? categories.find(c => c.id === parseInt(category))?.name : null;
---

<Layout title={categoryName ? `${categoryName} - สินค้าทั้งหมด` : 'สินค้าทั้งหมด'}>
  <Header />
  
  <div class="container mx-auto px-4 py-8">
    <!-- Breadcrumb -->
    <nav class="text-sm text-gray-500 mb-6">
      <a href="/" class="hover:text-blue-600">หน้าแรก</a>
      <span class="mx-2">/</span>
      <span class="text-gray-900">{categoryName || 'สินค้าทั้งหมด'}</span>
    </nav>

    <div class="flex gap-8">
      <!-- Filters Sidebar -->
      <aside class="w-64 hidden lg:block flex-shrink-0">
        <div class="bg-white rounded-xl shadow-sm p-6 sticky top-24">
          <h3 class="font-bold text-lg mb-4">กรองสินค้า</h3>
          <ProductFilters client:load categories={categories} selectedCategory={category} />
        </div>
      </aside>
      
      <!-- Products Grid -->
      <main class="flex-1">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
          <div>
            <h1 class="text-2xl font-bold">
              {categoryName || 'สินค้าทั้งหมด'}
            </h1>
            <p class="text-gray-500 mt-1">{products.length} รายการ</p>
          </div>
          
          <!-- Sort -->
          <div class="flex items-center gap-2">
            <label class="text-gray-600">เรียงตาม:</label>
            <select 
              class="border rounded-lg px-3 py-2 bg-white"
              onchange={`window.location.href = '/products?${new URLSearchParams({...(category && {category}), sort: this.value}).toString()}'`}
            >
              <option value="created_at.desc" selected={sort === 'created_at.desc'}>สินค้าใหม่ล่าสุด</option>
              <option value="price.asc" selected={sort === 'price.asc'}>ราคาต่ำ-สูง</option>
              <option value="price.desc" selected={sort === 'price.desc'}>ราคาสูง-ต่ำ</option>
              <option value="name.asc" selected={sort === 'name.asc'}>ชื่อ ก-ฮ</option>
            </select>
          </div>
        </div>
        
        {products.length > 0 ? (
          <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {products.map((product, index) => (
              <ProductCard product={product} index={index} />
            ))}
          </div>
        ) : (
          <div class="text-center py-20 bg-white rounded-xl">
            <div class="w-20 h-20 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
              <svg class="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
              </svg>
            </div>
            <p class="text-gray-500 text-lg mb-4">ไม่พบสินค้าในหมวดหมู่นี้</p>
            <a href="/products" class="text-blue-600 hover:underline">ดูสินค้าทั้งหมด</a>
          </div>
        )}
        
        <!-- Pagination -->
        {products.length === limit && (
          <div class="flex justify-center gap-2 mt-8">
            {page > 1 && (
              <a 
                href={`/products?${new URLSearchParams({...(category && {category}), sort, page: String(page - 1)}).toString()}`}
                class="px-4 py-2 border rounded-lg hover:bg-gray-50 transition-colors"
              >
                ← ก่อนหน้า
              </a>
            )}
            <span class="px-4 py-2 bg-blue-600 text-white rounded-lg">หน้า {page}</span>
            <a 
              href={`/products?${new URLSearchParams({...(category && {category}), sort, page: String(page + 1)}).toString()}`}
              class="px-4 py-2 border rounded-lg hover:bg-gray-50 transition-colors"
            >
              ถัดไป →
            </a>
          </div>
        )}
      </main>
    </div>
  </div>
  
  <Footer />
  <CartDrawer client:load />
  <CartBadge client:load />
</Layout>
