import React, { useState, useEffect, useContext } from 'react' import { useParams, useNavigate } from 'react-router-dom' import api from '../api' import { CartContext } from '../context/CartContext' import { AuthContext } from '../context/AuthContext' import '../styles/global.css' export default function ProductDetail() { const { id } = useParams() const navigate = useNavigate() const [product, setProduct] = useState(null) const [loading, setLoading] = useState(true) const [selectedSize, setSelectedSize] = useState('') const [quantity, setQuantity] = useState(1) const [inWishlist, setInWishlist] = useState(false) const [selectedImageIndex, setSelectedImageIndex] = useState(0) const { addToCart } = useContext(CartContext) const { token } = useContext(AuthContext) useEffect(() => { fetchProduct() }, [id]) const fetchProduct = async () => { try { const response = await api.get(`/products/${id}`) setProduct(response.data) if (response.data.sizes.length > 0) setSelectedSize(response.data.sizes[0]) } catch (error) { console.error('Error fetching product:', error) } finally { setLoading(false) } } const handleAddToCart = async () => { try { if (!token) { navigate('/login') return } await api.post('/cart/add', { product_id: product.id, quantity, size: selectedSize, token, }) addToCart(product, quantity, selectedSize) alert('Product added to cart!') } catch (error) { console.error('Error adding to cart:', error) } } const handleToggleWishlist = async () => { if (!token) { navigate('/login') return } try { if (inWishlist) { await api.delete(`/wishlist/${product.id}`) } else { await api.post(`/wishlist/${product.id}`) } setInWishlist(!inWishlist) } catch (error) { console.error('Error updating wishlist:', error) } } if (loading) return
{product.brand}
{product.description}
{product.sizes.length > 0 && (