---
import Layout from '../../../../layouts/Layout.astro';
import Header from '../../../../components/layout/Header';
import AdminSidebar from '../../../../components/admin/AdminSidebar';
import ProductForm from '../../../../components/vendor/ProductForm';

const token = Astro.cookies.get('session')?.value;
if (!token) return Astro.redirect('/login');

const { id } = Astro.params;

// Fetch product data
const productRes = await fetch(new URL(`/api/vendors/products/${id}`, Astro.url).toString(), {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { product } = await productRes.json();

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

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

<Layout title={`แก้ไข: ${product.name}`}>
  <div class="min-h-screen bg-gray-100">
    <Header />
    <div class="flex">
      <AdminSidebar client:load role="vendor" />
      <main class="flex-1 p-8">
        <div class="flex items-center gap-4 mb-8">
          <a href="/vendor/products" class="text-gray-500 hover:text-gray-700">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
            </svg>
          </a>
          <h1 class="text-2xl font-bold">แก้ไขสินค้า</h1>
        </div>
        
        <div class="max-w-3xl">
          <ProductForm client:load categories={categories} product={product} />
        </div>
      </main>
    </div>
  </div>
</Layout>
