'use client'; import Link from 'next/link'; import Image from 'next/image'; import { useState } from 'react'; import { useAuth } from '@/contexts/AuthContext'; import { useCart } from '@/contexts/CartContext'; function formatPrice(cents: number) { return `€${(cents / 100).toFixed(2)}`; } export default function CheckoutClient() { const { user, loading: authLoading } = useAuth(); const { items, subtotalCents, itemCount, clearCart } = useCart(); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(''); // Form state const [form, setForm] = useState({ firstName: '', lastName: '', email: user?.email ?? '', phone: '', address: '', city: '', postalCode: '', notes: '', shippingMethod: 'standard', }); if (authLoading) { return (
Cargando...
); } if (items.length === 0) { return (
🛒

Tu carrito está vacío

Añade productos antes de hacer el pedido.

Ver productos
); } const shippingCost = form.shippingMethod === 'express' ? 899 : 499; const totalCents = subtotalCents + shippingCost; const handlePlaceOrder = async () => { setSubmitting(true); setError(''); try { const res = await fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ shippingAddress: { firstName: form.firstName, lastName: form.lastName, email: form.email, phone: form.phone, line1: form.address, city: form.city, postalCode: form.postalCode, country: 'ES', }, items: items.map((i) => ({ productId: i.productId, variantId: i.variantId, quantity: i.quantity, })), shippingMethod: form.shippingMethod, notes: form.notes, }), }); if (res.status === 401) { setError('Debes iniciar sesión para finalizar el pedido.'); return; } if (!res.ok) { const data = await res.json().catch(() => ({})); throw new Error(data.error?.message || 'Error al procesar el pedido'); } const { orderId } = await res.json(); clearCart(); window.location.href = `/order-confirmation?orderId=${orderId}`; } catch (err) { setError(err instanceof Error ? err.message : 'Error al procesar el pedido'); } finally { setSubmitting(false); } }; return (

Finalizar pedido

{/* Form */}
{/* Login prompt — solo si NO está autenticado */} {!user && (

¿Ya tienes cuenta?

Inicia sesión para una experiencia más rápida.

Iniciar sesión Crear cuenta
)} {/* Shipping form */}

Datos de envío

setForm(f => ({ ...f, firstName: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none" />
setForm(f => ({ ...f, lastName: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none" />
setForm(f => ({ ...f, email: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none" />
setForm(f => ({ ...f, phone: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none" />
setForm(f => ({ ...f, address: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none" />
setForm(f => ({ ...f, city: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none" />
setForm(f => ({ ...f, postalCode: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none" />

Método de envío

{[ { id: 'standard', name: 'Estándar', desc: 'Entrega 3-5 días laborables', price: '€4.99' }, { id: 'express', name: 'Express 24h', desc: 'Entrega al día siguiente', price: '€8.99' }, ].map(opt => ( ))}

Notas del pedido