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

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

// Check admin role
const meRes = await fetch(new URL('/api/auth/me', Astro.url).toString(), {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { user } = await meRes.json();
if (user?.role !== 'admin') return Astro.redirect('/');

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

<Layout title="จัดการหมวดหมู่">
  <div class="min-h-screen bg-gray-100">
    <Header />
    <div class="flex">
      <AdminSidebar client:load role="admin" />
      <main class="flex-1 p-8">
        <div class="flex justify-between items-center mb-8">
          <h1 class="text-2xl font-bold">หมวดหมู่สินค้า</h1>
          <button class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors">
            + เพิ่มหมวดหมู่
          </button>
        </div>
        
        <div class="grid md:grid-cols-2 gap-6">
          {categories?.map(category => (
            <div class="bg-white rounded-xl p-6 shadow-sm">
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-4">
                  <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center text-2xl">
                    {category.icon || '📦'}
                  </div>
                  <div>
                    <h3 class="font-bold">{category.name}</h3>
                    <p class="text-sm text-gray-500">
                      {category.parent ? `หมวดหมู่ย่อยของ ${category.parent.name}` : 'หมวดหมู่หลัก'}
                    </p>
                  </div>
                </div>
                <div class="flex gap-2">
                  <button class="text-blue-600 hover:text-blue-800">แก้ไข</button>
                  <button class="text-red-600 hover:text-red-800">ลบ</button>
                </div>
              </div>
            </div>
          ))}
        </div>
        
        {(!categories || categories.length === 0) && (
          <div class="text-center py-20 bg-white rounded-xl">
            <p class="text-gray-500">ยังไม่มีหมวดหมู่</p>
          </div>
        )}
      </main>
    </div>
  </div>
</Layout>
