"use client" import { useState, useEffect } from "react" import Image from "next/image" import { Button } from "@/components/ui/button" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import SquarePaymentForm from "@/components/square-payment-form" import SiteFooter from "@/components/site-footer" interface Product { id: string variationId: string name: string description: string price: number currency: string imageUrl: string inventory: number category: string } interface ApiResponse { success: boolean products?: Product[] error?: string message?: string details?: any } export default function Shop() { const [products, setProducts] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState("") const [cart, setCart] = useState< Array<{ id: string variationId: string name: string price: number quantity: number description?: string }> >([]) const [showCheckout, setShowCheckout] = useState(false) const [orderComplete, setOrderComplete] = useState(false) useEffect(() => { fetchProducts() }, []) const fetchProducts = async () => { try { setLoading(true) setError("") console.log("Fetching products from /api/square/catalog...") // First check Square health const healthResponse = await fetch("/api/square/health") const healthData = await healthResponse.json() if (!healthData.success) { console.error("Square health check failed:", healthData) setError(`Square API configuration issue: ${healthData.error || 'Connection failed'}`) return } console.log("Square health check passed, fetching catalog...") const response = await fetch("/api/square/catalog?includeInventory=true") console.log("Response status:", response.status) console.log("Response headers:", Object.fromEntries(response.headers.entries())) // Check if response is ok if (!response.ok) { const errorText = await response.text() console.error("HTTP error:", response.status, errorText.substring(0, 500)) setError(`Server error (${response.status}): ${response.statusText}`) return } // Check if response is JSON const contentType = response.headers.get("content-type") if (!contentType || !contentType.includes("application/json")) { const responseText = await response.text() console.error("Non-JSON response:", responseText.substring(0, 500)) setError("Server returned invalid response format. Check server logs for details.") return } const data: ApiResponse = await response.json() console.log("API Response:", data) if (data.success && data.products) { setProducts(data.products) console.log("Products loaded:", data.products.length) } else { const errorMsg = data.error || data.message || "Failed to load products" console.error("API returned error:", errorMsg) setError(errorMsg) // Show additional details if available if (data.details) { console.error("Error details:", data.details) } } } catch (error) { console.error("Error fetching products:", error) // More specific error handling if (error instanceof TypeError && error.message.includes("json")) { setError("Server returned invalid data format. This usually means Square SDK failed to load.") } else if (error instanceof TypeError && error.message.includes("fetch")) { setError("Network connection failed. Please check your internet connection.") } else { setError(`Unexpected error: ${error instanceof Error ? error.message : "Unknown error"}`) } } finally { setLoading(false) } } const addToCart = (product: Product) => { if (product.inventory <= 0) { alert("Sorry, this item is out of stock!") return } setCart((prev) => { const existing = prev.find((item) => item.id === product.id) if (existing) { const newQuantity = existing.quantity + 1 if (newQuantity > product.inventory) { alert(`Sorry, only ${product.inventory} items available in stock!`) return prev } return prev.map((item) => (item.id === product.id ? { ...item, quantity: newQuantity } : item)) } return [ ...prev, { id: product.id, variationId: product.variationId, name: product.name, price: product.price, quantity: 1, description: product.description, }, ] }) } const removeFromCart = (productId: string) => { setCart((prev) => prev.filter((item) => item.id !== productId)) } const updateQuantity = (productId: string, quantity: number) => { if (quantity === 0) { removeFromCart(productId) return } const product = products.find((p) => p.id === productId) if (product && quantity > product.inventory) { alert(`Sorry, only ${product.inventory} items available in stock!`) return } setCart((prev) => prev.map((item) => (item.id === productId ? { ...item, quantity } : item))) } const handlePaymentSuccess = (paymentResult: any) => { console.log("Payment successful:", paymentResult) setOrderComplete(true) setCart([]) setShowCheckout(false) fetchProducts() } const handlePaymentError = (error: string) => { console.error("Payment error:", error) alert(`Payment failed: ${error}`) } if (orderComplete) { return (

Order Complete!

Thank you for your purchase! You'll receive a confirmation email shortly.

) } if (showCheckout && cart.length > 0) { return (

Checkout

) } return (
{/* Header */}
{cart.length > 0 && (
)}
{/* Hero Section */}

Shop

Discover unique, handcrafted pieces that tell a story. Each item is lovingly upcycled and designed to help you sparkle! ✨

{/* Debug Info */} {error && (

Debug Info: {error}

Check browser console for more details. This usually means Square API credentials need to be configured.

)} {/* Products Grid */}
{loading ? (
Loading products...

Connecting to Square catalog...

) : error ? (
Unable to load products

{error}

Common solutions:

  • Check that Square API credentials are configured in environment variables
  • Verify that products exist in your Square catalog
  • Ensure Square API access token has catalog permissions
) : products.length === 0 ? (
No products available

Add products to your Square catalog to see them here.

) : (
{products.map((product) => ( {product.name} {product.inventory <= 0 && ( Out of Stock )} {product.inventory > 0 && product.inventory <= 5 && ( Only {product.inventory} left )} {product.name}

{product.description}

${product.price.toFixed(2)}
{product.inventory > 5 ? "In Stock" : `${product.inventory} in stock`}
))}
)}
{/* Cart Summary */} {cart.length > 0 && (

Shopping Cart

{cart.map((item) => (
{item.name} x{item.quantity}
))}
Total: ${cart.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2)}
)}
) }