Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | 1x 1x 3x 3x 3x 3x 1x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 3x 3x 3x | 'use client';
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
import { useSession } from 'next-auth/react';
import { Product, CartItem, Review, Order } from '../types';
interface ShopContextType {
products: Product[];
cart: CartItem[];
reviews: Review[];
orders: Order[];
loading: boolean;
isAuthenticated: boolean;
addToCart: (product: Product & { selectedColor?: string | null; selectedSize?: string | null }) => void;
removeFromCart: (productId: string, selectedColor?: string | null, selectedSize?: string | null) => void;
updateQuantity: (productId: string, quantity: number, selectedColor?: string | null, selectedSize?: string | null) => void;
clearCart: () => void;
submitOrder: (customer: Order['customer'], shippingMethod: string) => Promise<void>;
submitReview: (review: Omit<Review, 'id' | 'status' | 'date'>) => Promise<void>;
refreshReviews: () => Promise<void>;
}
const ShopContext = createContext<ShopContextType | undefined>(undefined);
export const ShopProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { data: session, status } = useSession();
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(true);
// Initialize cart from localStorage if available (client-side only)
const [cart, setCart] = useState<CartItem[]>(() => {
Iif (typeof window === 'undefined') return [];
try {
const savedCart = localStorage.getItem('cart');
return savedCart ? JSON.parse(savedCart) : [];
} catch (e) {
console.error("Failed to load cart", e);
return [];
}
});
const [reviews, setReviews] = useState<Review[]>([]);
const [orders, setOrders] = useState<Order[]>([]);
// Check if user is authenticated
const isAuthenticated = status === 'authenticated' && !!session?.user;
// Load products on mount
useEffect(() => {
const fetchProducts = async () => {
try {
const res = await fetch('/api/products');
const data = await res.json();
setProducts(Array.isArray(data) ? data : []);
} catch (error) {
console.error('Error fetching products:', error);
setProducts([]);
} finally {
setLoading(false);
}
};
fetchProducts();
}, []);
// Load reviews on mount
useEffect(() => {
const fetchReviews = async () => {
try {
const res = await fetch('/api/reviews');
const data = await res.json();
setReviews(Array.isArray(data) ? data : []);
} catch (error) {
console.error('Error fetching reviews:', error);
setReviews([]);
}
};
fetchReviews();
}, []);
// Persist cart to localStorage whenever it changes (client-side only)
useEffect(() => {
Iif (typeof window === 'undefined') return;
try {
localStorage.setItem('cart', JSON.stringify(cart));
} catch (e) {
console.error("Failed to save cart", e);
}
}, [cart]);
// Helper to compute available stock for a product with variant selections
// When both sizes + colors exist, stock is tracked per (size, color) combination via colorStocks
const getAvailableStock = useCallback((product: Product, selectedColor?: string | null, selectedSize?: string | null): number => {
const sizeVariant = product.sizes?.find(s => s.name === selectedSize);
// Both size + color: use nested colorStocks
Iif (sizeVariant?.colorStocks && selectedColor) {
return sizeVariant.colorStocks.find(c => c.colorName === selectedColor)?.stock ?? 0;
}
// Size only
Iif (sizeVariant) return sizeVariant.stock;
// Color only
const colorVariant = product.colors?.find(c => c.name === selectedColor);
Iif (colorVariant) return colorVariant.stock;
// No variants
return product.stock;
}, []);
// Match cart item by id + selectedColor + selectedSize
const matchCartItem = useCallback((item: CartItem, productId: string, selectedColor?: string | null, selectedSize?: string | null): boolean => {
return item.id === productId &&
(item.selectedColor ?? null) === (selectedColor ?? null) &&
(item.selectedSize ?? null) === (selectedSize ?? null);
}, []);
// OPTIMIZATION: Use useCallback with functional state updates to keep function identity stable
const addToCart = useCallback((product: Product & { selectedColor?: string | null; selectedSize?: string | null }) => {
setCart(prev => {
const existing = prev.find(item => matchCartItem(item, product.id, product.selectedColor, product.selectedSize));
const availableStock = getAvailableStock(product, product.selectedColor, product.selectedSize);
Iif (existing) {
if (existing.quantity >= availableStock) return prev;
return prev.map(item =>
matchCartItem(item, product.id, product.selectedColor, product.selectedSize)
? { ...item, quantity: item.quantity + 1 }
: item
);
}
Iif (availableStock < 1) return prev;
return [...prev, { ...product, quantity: 1, selectedColor: product.selectedColor || null, selectedSize: product.selectedSize || null }];
});
}, [getAvailableStock, matchCartItem]);
const updateQuantity = useCallback((productId: string, quantity: number, selectedColor?: string | null, selectedSize?: string | null) => {
setCart(prev => {
if (quantity < 1) {
return prev.filter(item => !matchCartItem(item, productId, selectedColor, selectedSize));
}
return prev.map(item => {
if (matchCartItem(item, productId, selectedColor, selectedSize)) {
const availableStock = getAvailableStock(item, item.selectedColor, item.selectedSize);
const safeQuantity = Math.min(quantity, availableStock);
return { ...item, quantity: safeQuantity };
}
return item;
});
});
}, [matchCartItem, getAvailableStock]);
const removeFromCart = useCallback((productId: string, selectedColor?: string | null, selectedSize?: string | null) => {
setCart(prev => prev.filter(item =>
!(item.id === productId &&
(selectedColor === undefined || (item.selectedColor ?? null) === (selectedColor ?? null)) &&
(selectedSize === undefined || (item.selectedSize ?? null) === (selectedSize ?? null)))
));
}, []);
const clearCart = useCallback(() => setCart([]), []);
// submitOrder needs access to the current cart state
const submitOrder = useCallback(async (customer: Order['customer'], shippingMethod: string) => {
// Validate cart is not empty
if (cart.length === 0) {
throw new Error('Cannot submit empty order');
}
// Calculate subtotal
const subtotal = cart.reduce((sum, item) => sum + (item.salePrice || item.price) * item.quantity, 0);
// Calculate shipping cost based on method
const shippingCost = shippingMethod === 'postitus' ? 10 : 0;
const total = subtotal + shippingCost;
try {
const res = await fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
customer,
items: cart,
total,
shippingMethod,
}),
});
if (res.ok) {
const newOrder = await res.json();
setOrders(prev => [newOrder, ...prev]);
setCart([]); // Clear cart after successful order
} else {
throw new Error('Failed to submit order');
}
} catch (error) {
console.error('Error submitting order:', error);
throw error;
}
}, [cart]);
const submitReview = useCallback(async (reviewData: Omit<Review, 'id' | 'status' | 'date'>) => {
try {
const res = await fetch('/api/reviews', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(reviewData),
});
if (res.ok) {
const newReview = await res.json();
setReviews(prev => [...prev, newReview]);
} else {
throw new Error('Failed to submit review');
}
} catch (error) {
console.error('Error submitting review:', error);
throw error;
}
}, []);
const refreshReviews = useCallback(async () => {
try {
const res = await fetch('/api/reviews');
const data = await res.json();
setReviews(data);
} catch (error) {
console.error('Error refreshing reviews:', error);
}
}, []);
// OPTIMIZATION: Memoize the context value to prevent re-renders of consumers
const contextValue = useMemo(() => ({
products,
cart,
reviews,
orders,
loading,
isAuthenticated,
addToCart,
removeFromCart,
updateQuantity,
clearCart,
submitOrder,
submitReview,
refreshReviews,
}), [
products, cart, reviews, orders, loading, isAuthenticated,
addToCart, removeFromCart, updateQuantity, clearCart, submitOrder, submitReview, refreshReviews
]);
return (
<ShopContext.Provider value={contextValue}>
{children}
</ShopContext.Provider>
);
};
export const useShop = () => {
const context = useContext(ShopContext);
Iif (!context) throw new Error("useShop must be used within ShopProvider");
return context;
}; |