---
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 CartDrawer from '../components/cart/CartDrawer';
import CartBadge from '../components/cart/CartBadge';

const token = Astro.cookies.get('session')?.value;

// If not logged in, show login prompt
if (!token) {
  return Astro.redirect('/login?redirect=/wishlist');
}

// Fetch wishlist
const wishlistRes = await fetch(new URL('/api/wishlist', Astro.url).toString(), {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { items } = await wishlistRes.json();

// Transform wishlist items to products
const products = items?.map(item => item.product) || [];
---

<Layout title="สินค้าที่ชอบ">
  <Header />
  
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-8">สินค้าที่ชอบ</h1>
    
    {products.length > 0 ? (
      <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
        {products.map((product, index) => (
          <div class="relative">
            <ProductCard product={product} index={index} />
            <button 
              class="remove-wishlist absolute top-3 right-3 w-8 h-8 bg-white rounded-full shadow flex items-center justify-center text-red-500 hover:bg-red-50 transition-colors"
              data-product-id={product.id}
            >
              <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
            </button>
          </div>
        ))}
      </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="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
          </svg>
        </div>
        <p class="text-gray-500 text-lg mb-4">ยังไม่มีสินค้าที่ชอบ</p>
        <p class="text-gray-400 mb-6">คลิกหัวใจที่สินค้าที่คุณชอบเพื่อบันทึกไว้</p>
        <a href="/products" class="inline-block bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors">
          เริ่มช้อปเลย
        </a>
      </div>
    )}
  </div>
  
  <Footer />
  <CartDrawer client:load />
  <CartBadge client:load />
</Layout>

<script>
  // Handle remove from wishlist
  document.querySelectorAll('.remove-wishlist').forEach(button => {
    button.addEventListener('click', async (e) => {
      e.preventDefault();
      const productId = button.dataset.productId;
      if (!confirm('ลบสินค้านี้ออกจากรายการที่ชอบ?')) return;
      
      try {
        const token = document.cookie.split('; ').find(row => row.startsWith('session='))?.split('=')[1];
        const res = await fetch(`/api/wishlist/${productId}`, {
          method: 'DELETE',
          headers: { 'Authorization': `Bearer ${token}` }
        });
        
        if (res.ok) {
          // Remove card from view
          button.closest('.relative')?.remove();
        }
      } catch (error) {
        alert('เกิดข้อผิดพลาด');
      }
    });
  });
</script>
