"use client";

import React, { useEffect, useState } from "react";
import Product from "@/components/Product";

export default function Feed() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const res = await fetch("/api/products");
        if (!res.ok) {
          throw new Error("获取商品列表失败");
        }
        const data = await res.json();
        setProducts(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchProducts();
  }, []);

  if (loading) return <div className="p-4">加载中...</div>;
  if (error) return <div className="p-4 text-red-500">错误: {error}</div>;

  return (
    <div className="p-4 grid grid-cols-1 gap-4">
      {products.map((product) => (
        <Product
          key={product._id}
          id={product._id}
          title={product.title}
          price={product.price}
          sales={product.sales}
          imageUrl={product.imageUrl}
          isVip={product.isVip}
        />
      ))}
    </div>
  );
}
