"use client"; import { useState, useEffect } from "react"; import Link from "next/link"; import { getSpaceIdFromCookie, getCartKey } from "@/lib/spaces"; const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000/api"; interface CartItem { id: string; product_slug: string; product_name: string; variant_sku: string; variant_name: string | null; quantity: number; unit_price: number; subtotal: number; } interface Cart { id: string; items: CartItem[]; item_count: number; subtotal: number; } export default function CartPage() { const [cart, setCart] = useState(null); const [loading, setLoading] = useState(true); const [checkingOut, setCheckingOut] = useState(false); const [updating, setUpdating] = useState(null); const fetchCart = async () => { const cartKey = getCartKey(getSpaceIdFromCookie()); const cartId = localStorage.getItem(cartKey); if (cartId) { try { const res = await fetch(`${API_URL}/cart/${cartId}`); if (res.ok) { const data = await res.json(); setCart(data); } else { // Cart expired or deleted localStorage.removeItem(cartKey); setCart(null); } } catch { setCart(null); } } setLoading(false); }; useEffect(() => { fetchCart(); }, []); const updateQuantity = async (itemId: string, newQuantity: number) => { if (!cart || newQuantity < 1) return; setUpdating(itemId); try { const res = await fetch(`${API_URL}/cart/${cart.id}/items/${itemId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ quantity: newQuantity }), }); if (res.ok) { const updatedCart = await res.json(); setCart(updatedCart); } } catch { console.error("Failed to update quantity"); } finally { setUpdating(null); } }; const removeItem = async (itemId: string) => { if (!cart) return; setUpdating(itemId); try { const res = await fetch(`${API_URL}/cart/${cart.id}/items/${itemId}`, { method: "DELETE", }); if (res.ok) { const updatedCart = await res.json(); setCart(updatedCart); } } catch { console.error("Failed to remove item"); } finally { setUpdating(null); } }; const handleCheckout = async () => { if (!cart) return; setCheckingOut(true); try { const res = await fetch(`${API_URL}/checkout/session`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cart_id: cart.id, success_url: `${window.location.origin}/checkout/success`, cancel_url: `${window.location.origin}/cart`, }), }); if (res.ok) { const { checkout_url } = await res.json(); window.location.href = checkout_url; } else { const data = await res.json(); alert(data.detail || "Failed to start checkout"); } } catch (error) { console.error("Checkout error:", error); alert("Failed to start checkout"); } finally { setCheckingOut(false); } }; if (loading) { return (
); } if (!cart || cart.items.length === 0) { return (

Your Cart

Your cart is empty.

Continue Shopping
); } return (

Your Cart

{cart.items.map((item) => (
{/* Product Image */}
{item.product_name}
{/* Product Info */}
{item.product_name} {item.variant_name && (

{item.variant_name}

)}

${item.unit_price.toFixed(2)} each

{/* Quantity Controls */}
{item.quantity}
{/* Subtotal */}

${item.subtotal.toFixed(2)}

))}
{/* Order Summary */}

Order Summary

Subtotal ({cart.item_count} item{cart.item_count !== 1 ? "s" : ""}) ${cart.subtotal.toFixed(2)}
Shipping Calculated at checkout
Total ${cart.subtotal.toFixed(2)}
Continue Shopping
); }