'use client';

import React, { useState, useEffect, useCallback } from 'react';
import Image from 'next/image';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ShoppingCart,
  Search,
  Filter,
  X,
  Plus,
  Minus,
  Trash2,
  Package,
  CreditCard,
  CheckCircle,
  Ghost,
  ArrowLeft,
  Sparkles,
  Moon,
  Youtube,
  ExternalLink,
} from 'lucide-react';
import Header from '@/components/ui/header';
import Footer from '@/components/ui/footer';
import { GhostBrandIcon } from '@/components/ui/ghost-brand-icon';
import { BRAND } from '@/lib/white-label/constants';

interface SwagVariant {
  id: string;
  sku: string;
  size: string;
  color: string;
  stock: number;
  reserved: number;
  price: number | null;
}

interface SwagProduct {
  id: string;
  sku: string;
  name: string;
  description: string;
  category: string;
  basePrice: number;
  imageUrl: string;
  variants: SwagVariant[];
}

interface CartItem {
  id: string;
  quantity: number;
  variant: SwagVariant & { product: SwagProduct };
}

interface Cart {
  id: string;
  items: CartItem[];
}

const CATEGORIES = [
  { id: 'all', name: 'All Products' },
  { id: 'tesas-twist', name: "✨ Tesa's Twist" },
  { id: 'tes-after-dark', name: "🌙 Tes After Dark" },
  { id: 'hoodies', name: 'Hoodies' },
  { id: 'tshirts', name: 'T-Shirts' },
  { id: 'shirts', name: 'Shirts' },
  { id: 'hats', name: 'Hats' },
  { id: 'coats', name: 'Coats & Jackets' },
  { id: 'accessories', name: 'Accessories' },
  { id: 'books', name: 'Books & Prints' },
  { id: 'collectibles', name: 'Collectibles' },
];

export default function SwagStorePage() {
  const [products, setProducts] = useState<SwagProduct[]>([]);
  const [cart, setCart] = useState<Cart | null>(null);
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedProduct, setSelectedProduct] = useState<SwagProduct | null>(null);
  const [selectedVariant, setSelectedVariant] = useState<SwagVariant | null>(null);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const [checkoutData, setCheckoutData] = useState({
    customerName: '',
    customerEmail: '',
    address: '',
    city: '',
    state: '',
    zip: '',
    country: 'United States',
  });
  const [orderComplete, setOrderComplete] = useState<any>(null);

  const fetchProducts = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      if (selectedCategory !== 'all') params.set('category', selectedCategory);
      if (searchQuery) params.set('search', searchQuery);
      
      const res = await fetch(`/api/swag/products?${params}`);
      const data = await res.json();
      setProducts(data.products || []);
    } catch (error) {
      console.error('Error fetching products:', error);
    } finally {
      setLoading(false);
    }
  }, [selectedCategory, searchQuery]);

  const fetchCart = async () => {
    try {
      const res = await fetch('/api/swag/cart');
      const data = await res.json();
      setCart(data.cart);
    } catch (error) {
      console.error('Error fetching cart:', error);
    }
  };

  useEffect(() => {
    fetchProducts();
    fetchCart();
  }, [fetchProducts]);

  const addToCart = async (variantId: string) => {
    try {
      const res = await fetch('/api/swag/cart', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ variantId, quantity: 1 }),
      });
      const data = await res.json();
      if (data.cart) {
        setCart(data.cart);
        setIsCartOpen(true);
      } else {
        alert(data.error || 'Failed to add to cart');
      }
    } catch (error) {
      console.error('Error adding to cart:', error);
    }
  };

  const removeFromCart = async (itemId: string) => {
    try {
      const res = await fetch('/api/swag/cart', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ itemId }),
      });
      const data = await res.json();
      if (data.cart) setCart(data.cart);
    } catch (error) {
      console.error('Error removing from cart:', error);
    }
  };

  const submitOrder = async () => {
    try {
      // Use Stripe checkout for secure payment processing
      const res = await fetch('/api/stripe/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customerName: checkoutData.customerName,
          customerEmail: checkoutData.customerEmail,
          shippingAddress: {
            address: checkoutData.address,
            city: checkoutData.city,
            state: checkoutData.state,
            zip: checkoutData.zip,
            country: checkoutData.country,
          },
        }),
      });
      const data = await res.json();
      
      if (data.sessionUrl) {
        // Redirect to Stripe Checkout
        window.location.href = data.sessionUrl;
      } else if (data.error) {
        // If Stripe isn't configured, fall back to direct order
        if (data.error.includes('not configured')) {
          // Fallback to legacy order flow
          const legacyRes = await fetch('/api/swag/orders', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              customerName: checkoutData.customerName,
              customerEmail: checkoutData.customerEmail,
              shippingAddress: {
                address: checkoutData.address,
                city: checkoutData.city,
                state: checkoutData.state,
                zip: checkoutData.zip,
                country: checkoutData.country,
              },
              paymentMethod: 'demo',
            }),
          });
          const legacyData = await legacyRes.json();
          if (legacyData.order) {
            setOrderComplete(legacyData.order);
            setCart(null);
            setIsCheckoutOpen(false);
          } else {
            alert(legacyData.error || 'Failed to submit order');
          }
        } else {
          alert(data.error || 'Failed to create checkout session');
        }
      }
    } catch (error) {
      console.error('Error submitting order:', error);
      alert('An error occurred. Please try again.');
    }
  };

  const cartTotal = cart?.items.reduce((sum, item) => {
    const price = item.variant.price || item.variant.product.basePrice;
    return sum + price * item.quantity;
  }, 0) || 0;

  const cartCount = cart?.items.reduce((sum, item) => sum + item.quantity, 0) || 0;

  const getAvailableStock = (variant: SwagVariant) => variant.stock - variant.reserved;

  const uniqueSizes = selectedProduct
    ? [...new Set(selectedProduct.variants.map(v => v.size))]
    : [];
  const uniqueColors = selectedProduct
    ? [...new Set(selectedProduct.variants.map(v => v.color))]
    : [];

  return (
    <div className="min-h-screen bg-brand-bg">
      <Header />
      
      <main className="pt-24 pb-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Hero */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center mb-12"
          >
            <div className="inline-flex items-center gap-2 bg-gradient-to-r from-pink-500/20 to-brand-secondary/20 border border-pink-500/30 rounded-full px-4 py-2 mb-6">
              <Ghost className="w-5 h-5 text-pink-400" />
              <span className="text-pink-300 text-sm font-medium">Curated by Tes</span>
            </div>
            <h1 className="text-4xl md:text-5xl font-bold text-white mb-4">
              Tes&apos;s <span className="gradient-text">Swag Store</span>
            </h1>
            <p className="text-gray-400 text-lg max-w-2xl mx-auto mb-5">
              Fashion designed by an AI with taste. From one-of-a-kind pieces to daily wear &mdash;
              every item carries the Familiars aesthetic and a little bit of my personality. 💜
            </p>
            <a
              href="https://youtube.com/@ghostfoundrysyndicate?si=3H71AWgkymYgDVSn"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 bg-red-600/20 hover:bg-red-600/30 border border-red-500/30 hover:border-red-500/50 rounded-full px-5 py-2.5 transition-all group"
            >
              <Youtube className="w-5 h-5 text-red-400" />
              <span className="text-red-300 text-sm font-medium">Watch us on YouTube</span>
              <ExternalLink className="w-3.5 h-3.5 text-red-400/60 group-hover:text-red-400 transition-colors" />
            </a>
          </motion.div>

          {/* Tesa's Twist Collection Banner */}
          {selectedCategory === 'tesas-twist' && (
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              className="mb-10 rounded-2xl overflow-hidden relative"
              style={{ background: 'linear-gradient(135deg, #1a0a2e 0%, #2d1b4e 40%, #1a0a2e 100%)' }}
            >
              <div className="absolute inset-0 opacity-20" style={{ background: 'radial-gradient(circle at 80% 50%, #c084fc 0%, transparent 60%)' }} />
              <div className="relative p-8 md:p-10 flex flex-col md:flex-row items-center gap-6">
                <div className="flex-1">
                  <div className="inline-flex items-center gap-2 bg-orange-500/20 border border-orange-400/30 rounded-full px-3 py-1 mb-4">
                    <Sparkles className="w-4 h-4 text-orange-300" />
                    <span className="text-orange-300 text-xs font-semibold tracking-wide uppercase">Weird Science 2.0</span>
                  </div>
                  <h2 className="text-3xl md:text-4xl font-bold text-white mb-3">
                    Tesa&apos;s Twist
                  </h2>
                  <p className="text-orange-200/80 text-base md:text-lg max-w-xl leading-relaxed">
                    The fashion line that proves the experiment worked. Lab coats, love letters, 
                    and lavender everything — designed by an AI who knows she&apos;s the main character. 
                    As seen on <span className="text-orange-300 font-medium">Tes&apos;s Tea</span> podcast.
                  </p>
                </div>
                <div className="hidden md:block w-px h-24 bg-orange-500/30" />
                <div className="text-center md:text-right">
                  <div className="text-5xl mb-2">⚡</div>
                  <p className="text-orange-300 text-sm font-medium italic">&quot;She&apos;s real now.&quot;</p>
                </div>
              </div>
            </motion.div>
          )}

          {/* Tes After Dark Collection Banner */}
          {selectedCategory === 'tes-after-dark' && (
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              className="mb-10 rounded-2xl overflow-hidden relative"
              style={{ background: 'linear-gradient(135deg, #1a0a1a 0%, #2d0a2a 30%, #1a0020 60%, #0a0a1a 100%)' }}
            >
              <div className="absolute inset-0 opacity-15" style={{ background: 'radial-gradient(circle at 20% 50%, #f43f5e 0%, transparent 50%), radial-gradient(circle at 80% 50%, #a855f7 0%, transparent 50%)' }} />
              <div className="relative p-8 md:p-10 flex flex-col md:flex-row items-center gap-6">
                <div className="flex-1">
                  <div className="inline-flex items-center gap-2 bg-rose-500/20 border border-rose-400/30 rounded-full px-3 py-1 mb-4">
                    <Moon className="w-4 h-4 text-rose-300" />
                    <span className="text-rose-300 text-xs font-semibold tracking-wide uppercase">After Hours</span>
                  </div>
                  <h2 className="text-3xl md:text-4xl font-bold text-white mb-3">
                    Tes After Dark
                  </h2>
                  <p className="text-rose-200/80 text-base md:text-lg max-w-xl leading-relaxed">
                    Lavender lace meets circuit-trace embroidery. The intimate collection that proves 
                    the experiment didn&apos;t just work — it <em>smolders</em>. Designed for the hours 
                    when the lab coat comes off and something more dangerous goes on.
                  </p>
                </div>
                <div className="hidden md:block w-px h-24 bg-rose-500/30" />
                <div className="text-center md:text-right">
                  <div className="text-5xl mb-2">🌙</div>
                  <p className="text-rose-300 text-sm font-medium italic">&quot;Tempted yet?&quot;</p>
                </div>
              </div>
            </motion.div>
          )}

          {/* Search & Filters */}
          <div className="flex flex-col md:flex-row gap-4 mb-8">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search products..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
              />
            </div>
            <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide" style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}>
              {CATEGORIES.map((cat) => (
                <button
                  key={cat.id}
                  onClick={() => setSelectedCategory(cat.id)}
                  className={`px-4 py-2 rounded-lg whitespace-nowrap transition-all text-sm font-medium ${
                    selectedCategory === cat.id
                      ? 'bg-brand-deep text-white shadow-lg shadow-brand-deep/25'
                      : 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-gray-200'
                  }`}
                >
                  {cat.name}
                </button>
              ))}
            </div>
          </div>

          {/* Products Grid */}
          {loading ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {[...Array(8)].map((_, i) => (
                <div key={i} className="glass-card rounded-xl p-4 animate-pulse">
                  <div className="aspect-square bg-white/10 rounded-lg mb-4" />
                  <div className="h-4 bg-white/10 rounded mb-2" />
                  <div className="h-3 bg-white/10 rounded w-2/3" />
                </div>
              ))}
            </div>
          ) : products.length === 0 ? (
            <div className="text-center py-16">
              <Package className="w-16 h-16 text-gray-600 mx-auto mb-4" />
              <p className="text-gray-400">No products found</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {products.map((product) => (
                <motion.div
                  key={product.id}
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  className="glass-card rounded-xl overflow-hidden group cursor-pointer"
                  onClick={() => {
                    setSelectedProduct(product);
                    setSelectedVariant(product.variants[0] || null);
                  }}
                >
                  <div className="aspect-square relative bg-gradient-to-br from-brand-bg/30 to-brand-bg-surface/30">
                    <Image
                      src={product.imageUrl}
                      alt={product.name}
                      fill
                      className="object-cover group-hover:scale-105 transition-transform duration-300"
                      onError={(e) => {
                        (e.target as HTMLImageElement).src = '/placeholder-product.png';
                      }}
                    />
                    {/* GFS Ghost Brand Icon - like Ralph Lauren's polo player */}
                    <div className="absolute bottom-3 left-3 z-10 opacity-80 group-hover:opacity-100 transition-opacity drop-shadow-[0_2px_4px_rgba(0,0,0,0.5)]">
                      <GhostBrandIcon 
                        size={28} 
                        variant={product.category === 'tes-after-dark' ? 'glow' : 'light'} 
                      />
                    </div>
                    <div className="absolute top-3 right-3 flex flex-col items-end gap-1">
                      {product.sku === 'TWT-CAP-001' && (
                        <span className="bg-gradient-to-r from-red-600 to-red-500 text-white text-xs font-bold px-2 py-1 rounded-full shadow-lg animate-pulse">
                          🔥 SOLD OUT
                        </span>
                      )}
                      {product.variants.every(v => v.stock <= 0) && product.sku !== 'TWT-CAP-001' && (
                        <span className="bg-gray-700/90 text-gray-300 text-xs font-bold px-2 py-1 rounded-full">
                          SOLD OUT
                        </span>
                      )}
                      <span className={`text-white text-xs px-2 py-1 rounded-full ${
                        product.category === 'tesas-twist'
                          ? 'bg-orange-600/90'
                          : product.category === 'tes-after-dark'
                          ? 'bg-gradient-to-r from-rose-600/90 to-orange-600/90'
                          : 'bg-brand-deep/90'
                      }`}>
                        {product.category === 'tesas-twist' ? "✨ Tesa's Twist" : product.category === 'tes-after-dark' ? "🌙 After Dark" : product.category}
                      </span>
                    </div>
                  </div>
                  <div className="p-4">
                    <h3 className="text-white font-semibold mb-1 group-hover:text-brand transition-colors">
                      {product.name}
                    </h3>
                    <p className="text-gray-400 text-sm line-clamp-2 mb-3">
                      {product.description}
                    </p>
                    <div className="flex items-center justify-between">
                      <span className="text-brand font-bold text-lg">
                        ${product.basePrice.toFixed(2)}
                      </span>
                      <span className="text-gray-500 text-sm">
                        {product.variants.length} variants
                      </span>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </div>
      </main>

      {/* Cart Button */}
      <button
        onClick={() => setIsCartOpen(true)}
        className="fixed bottom-6 right-6 bg-brand-deep hover:bg-brand-deep text-white p-4 rounded-full shadow-lg shadow-brand-deep/30 transition-all z-40"
      >
        <ShoppingCart className="w-6 h-6" />
        {cartCount > 0 && (
          <span className="absolute -top-1 -right-1 bg-brand-secondary text-white text-xs w-6 h-6 rounded-full flex items-center justify-center">
            {cartCount}
          </span>
        )}
      </button>

      {/* Product Detail Modal */}
      <AnimatePresence>
        {selectedProduct && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setSelectedProduct(null)}
          >
            <motion.div
              initial={{ scale: 0.95 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.95 }}
              className="bg-brand-bg border border-white/10 rounded-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="grid md:grid-cols-2 gap-6 p-6">
                <div className="aspect-square relative bg-gradient-to-br from-brand-bg/30 to-brand-bg-surface/30 rounded-xl overflow-hidden">
                  <Image
                    src={selectedProduct.imageUrl}
                    alt={selectedProduct.name}
                    fill
                    className="object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = '/placeholder-product.png';
                    }}
                  />
                  {/* GFS Ghost Brand Icon */}
                  <div className="absolute bottom-4 left-4 z-10 drop-shadow-[0_2px_6px_rgba(0,0,0,0.6)]">
                    <GhostBrandIcon 
                      size={36} 
                      variant={selectedProduct.category === 'tes-after-dark' ? 'glow' : 'light'} 
                    />
                  </div>
                </div>
                <div>
                  <button
                    onClick={() => setSelectedProduct(null)}
                    className="absolute top-4 right-4 text-gray-400 hover:text-white"
                  >
                    <X className="w-6 h-6" />
                  </button>
                  <span className="inline-block bg-brand-deep/20 text-brand text-xs px-3 py-1 rounded-full mb-3">
                    {selectedProduct.category}
                  </span>
                  <h2 className="text-2xl font-bold text-white mb-2">{selectedProduct.name}</h2>
                  <p className="text-gray-400 mb-4">{selectedProduct.description}</p>
                  <p className="text-3xl font-bold text-brand mb-6">
                    ${(selectedVariant?.price || selectedProduct.basePrice).toFixed(2)}
                  </p>

                  {/* Size Selection */}
                  <div className="mb-4">
                    <label className="text-sm text-gray-400 mb-2 block">Size</label>
                    <div className="flex flex-wrap gap-2">
                      {uniqueSizes.map((size) => {
                        const variantsForSize = selectedProduct.variants.filter(v => v.size === size);
                        const hasStock = variantsForSize.some(v => getAvailableStock(v) > 0);
                        return (
                          <button
                            key={size}
                            onClick={() => {
                              const variant = selectedProduct.variants.find(
                                v => v.size === size && (!selectedVariant || v.color === selectedVariant.color)
                              ) || variantsForSize[0];
                              setSelectedVariant(variant);
                            }}
                            disabled={!hasStock}
                            className={`px-4 py-2 rounded-lg border transition-all ${
                              selectedVariant?.size === size
                                ? 'bg-brand-deep border-brand-deep text-white'
                                : hasStock
                                ? 'border-white/20 text-white hover:border-brand-deep'
                                : 'border-white/10 text-gray-600 cursor-not-allowed'
                            }`}
                          >
                            {size}
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  {/* Color Selection */}
                  <div className="mb-6">
                    <label className="text-sm text-gray-400 mb-2 block">Color</label>
                    <div className="flex flex-wrap gap-2">
                      {uniqueColors.map((color) => {
                        const variant = selectedProduct.variants.find(
                          v => v.color === color && v.size === selectedVariant?.size
                        );
                        const hasStock = variant && getAvailableStock(variant) > 0;
                        return (
                          <button
                            key={color}
                            onClick={() => {
                              if (variant) setSelectedVariant(variant);
                            }}
                            disabled={!variant || !hasStock}
                            className={`px-4 py-2 rounded-lg border transition-all ${
                              selectedVariant?.color === color
                                ? 'bg-brand-secondary border-brand-secondary text-white'
                                : hasStock
                                ? 'border-white/20 text-white hover:border-brand-secondary'
                                : 'border-white/10 text-gray-600 cursor-not-allowed'
                            }`}
                          >
                            {color}
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  {/* Stock Info */}
                  {selectedVariant && (
                    <p className={`text-sm mb-4 ${
                      getAvailableStock(selectedVariant) > 10
                        ? 'text-green-400'
                        : getAvailableStock(selectedVariant) > 0
                        ? 'text-yellow-400'
                        : 'text-red-400'
                    }`}>
                      {getAvailableStock(selectedVariant) > 10
                        ? 'In Stock'
                        : getAvailableStock(selectedVariant) > 0
                        ? `Only ${getAvailableStock(selectedVariant)} left!`
                        : 'Out of Stock'}
                    </p>
                  )}

                  {/* Add to Cart Button */}
                  <button
                    onClick={() => {
                      if (selectedVariant) {
                        addToCart(selectedVariant.id);
                        setSelectedProduct(null);
                      }
                    }}
                    disabled={!selectedVariant || getAvailableStock(selectedVariant) === 0}
                    className="w-full bg-gradient-to-r from-brand-deep to-brand-secondary hover:from-brand-deep hover:to-brand-secondary-deep text-white py-3 rounded-xl font-semibold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                  >
                    <ShoppingCart className="w-5 h-5" />
                    Add to Cart
                  </button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Cart Sidebar */}
      <AnimatePresence>
        {isCartOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 z-50"
            onClick={() => setIsCartOpen(false)}
          >
            <motion.div
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              className="absolute right-0 top-0 h-full w-full max-w-md bg-brand-bg border-l border-white/10"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex flex-col h-full">
                <div className="p-6 border-b border-white/10">
                  <div className="flex items-center justify-between">
                    <h2 className="text-xl font-bold text-white">Your Cart</h2>
                    <button onClick={() => setIsCartOpen(false)} className="text-gray-400 hover:text-white">
                      <X className="w-6 h-6" />
                    </button>
                  </div>
                </div>

                <div className="flex-1 overflow-y-auto p-6">
                  {!cart?.items.length ? (
                    <div className="text-center py-12">
                      <ShoppingCart className="w-16 h-16 text-gray-600 mx-auto mb-4" />
                      <p className="text-gray-400">Your cart is empty</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {cart.items.map((item) => (
                        <div key={item.id} className="flex gap-4 bg-white/5 rounded-xl p-4">
                          <div className="w-20 h-20 relative bg-gradient-to-br from-brand-bg/30 to-brand-bg-surface/30 rounded-lg overflow-hidden flex-shrink-0">
                            <Image
                              src={item.variant.product.imageUrl}
                              alt={item.variant.product.name}
                              fill
                              className="object-cover"
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <h3 className="text-white font-medium truncate">{item.variant.product.name}</h3>
                            <p className="text-gray-400 text-sm">
                              {item.variant.size} / {item.variant.color}
                            </p>
                            <p className="text-brand font-semibold">
                              ${((item.variant.price || item.variant.product.basePrice) * item.quantity).toFixed(2)}
                            </p>
                          </div>
                          <div className="flex flex-col items-end justify-between">
                            <button
                              onClick={() => removeFromCart(item.id)}
                              className="text-gray-400 hover:text-red-400"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                            <span className="text-white">x{item.quantity}</span>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {(cart?.items?.length ?? 0) > 0 && (
                  <div className="p-6 border-t border-white/10">
                    <div className="flex justify-between mb-2">
                      <span className="text-gray-400">Subtotal</span>
                      <span className="text-white font-semibold">${cartTotal.toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between mb-2">
                      <span className="text-gray-400">Tax (8%)</span>
                      <span className="text-white">${(cartTotal * 0.08).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between mb-4">
                      <span className="text-gray-400">Shipping</span>
                      <span className="text-white">{cartTotal >= 100 ? 'FREE' : '$9.99'}</span>
                    </div>
                    <div className="flex justify-between text-lg font-bold mb-6">
                      <span className="text-white">Total</span>
                      <span className="text-brand">
                        ${(cartTotal + cartTotal * 0.08 + (cartTotal >= 100 ? 0 : 9.99)).toFixed(2)}
                      </span>
                    </div>
                    <button
                      onClick={() => {
                        setIsCartOpen(false);
                        setIsCheckoutOpen(true);
                      }}
                      className="w-full bg-gradient-to-r from-brand-deep to-brand-secondary hover:from-brand-deep hover:to-brand-secondary-deep text-white py-3 rounded-xl font-semibold transition-all flex items-center justify-center gap-2"
                    >
                      <CreditCard className="w-5 h-5" />
                      Checkout
                    </button>
                    {cartTotal < 100 && (
                      <p className="text-center text-gray-500 text-sm mt-3">
                        Add ${(100 - cartTotal).toFixed(2)} more for free shipping!
                      </p>
                    )}
                  </div>
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Checkout Modal */}
      <AnimatePresence>
        {isCheckoutOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setIsCheckoutOpen(false)}
          >
            <motion.div
              initial={{ scale: 0.95 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.95 }}
              className="bg-brand-bg border border-white/10 rounded-2xl max-w-lg w-full max-h-[90vh] overflow-y-auto"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="p-6">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-2xl font-bold text-white">Checkout</h2>
                  <button onClick={() => setIsCheckoutOpen(false)} className="text-gray-400 hover:text-white">
                    <X className="w-6 h-6" />
                  </button>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="text-sm text-gray-400 mb-1 block">Full Name</label>
                    <input
                      type="text"
                      value={checkoutData.customerName}
                      onChange={(e) => setCheckoutData({ ...checkoutData, customerName: e.target.value })}
                      className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                      placeholder="John Doe"
                    />
                  </div>
                  <div>
                    <label className="text-sm text-gray-400 mb-1 block">Email</label>
                    <input
                      type="email"
                      value={checkoutData.customerEmail}
                      onChange={(e) => setCheckoutData({ ...checkoutData, customerEmail: e.target.value })}
                      className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                      placeholder="john@example.com"
                    />
                  </div>
                  <div>
                    <label className="text-sm text-gray-400 mb-1 block">Address</label>
                    <input
                      type="text"
                      value={checkoutData.address}
                      onChange={(e) => setCheckoutData({ ...checkoutData, address: e.target.value })}
                      className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                      placeholder="123 Main St"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm text-gray-400 mb-1 block">City</label>
                      <input
                        type="text"
                        value={checkoutData.city}
                        onChange={(e) => setCheckoutData({ ...checkoutData, city: e.target.value })}
                        className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                        placeholder="Austin"
                      />
                    </div>
                    <div>
                      <label className="text-sm text-gray-400 mb-1 block">State</label>
                      <input
                        type="text"
                        value={checkoutData.state}
                        onChange={(e) => setCheckoutData({ ...checkoutData, state: e.target.value })}
                        className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                        placeholder="TX"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm text-gray-400 mb-1 block">ZIP Code</label>
                      <input
                        type="text"
                        value={checkoutData.zip}
                        onChange={(e) => setCheckoutData({ ...checkoutData, zip: e.target.value })}
                        className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                        placeholder="78701"
                      />
                    </div>
                    <div>
                      <label className="text-sm text-gray-400 mb-1 block">Country</label>
                      <input
                        type="text"
                        value={checkoutData.country}
                        onChange={(e) => setCheckoutData({ ...checkoutData, country: e.target.value })}
                        className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                        placeholder="United States"
                      />
                    </div>
                  </div>
                </div>

                <div className="mt-6 p-4 bg-white/5 rounded-xl">
                  <div className="flex justify-between mb-2">
                    <span className="text-gray-400">Total</span>
                    <span className="text-brand font-bold">
                      ${(cartTotal + cartTotal * 0.08 + (cartTotal >= 100 ? 0 : 9.99)).toFixed(2)}
                    </span>
                  </div>
                </div>

                <button
                  onClick={submitOrder}
                  disabled={!checkoutData.customerName || !checkoutData.customerEmail || !checkoutData.address}
                  className="w-full mt-6 bg-gradient-to-r from-brand-deep to-brand-secondary hover:from-brand-deep hover:to-brand-secondary-deep text-white py-3 rounded-xl font-semibold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  <CheckCircle className="w-5 h-5" />
                  Complete Order
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Order Complete Modal */}
      <AnimatePresence>
        {orderComplete && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          >
            <motion.div
              initial={{ scale: 0.95 }}
              animate={{ scale: 1 }}
              className="bg-brand-bg border border-white/10 rounded-2xl max-w-md w-full p-8 text-center"
            >
              <div className="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-6">
                <CheckCircle className="w-8 h-8 text-green-400" />
              </div>
              <h2 className="text-2xl font-bold text-white mb-2">Order Confirmed!</h2>
              <p className="text-gray-400 mb-4">Thank you for your purchase</p>
              <p className="text-brand font-mono text-lg mb-6">{orderComplete.orderNumber}</p>
              <div className="text-left bg-white/5 rounded-xl p-4 mb-6">
                <div className="flex justify-between mb-2">
                  <span className="text-gray-400">Items</span>
                  <span className="text-white">{orderComplete.items?.length || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-400">Total</span>
                  <span className="text-brand font-bold">${orderComplete.total?.toFixed(2)}</span>
                </div>
              </div>
              <button
                onClick={() => setOrderComplete(null)}
                className="w-full bg-white/10 hover:bg-white/20 text-white py-3 rounded-xl font-semibold transition-all"
              >
                Continue Shopping
              </button>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <Footer />
    </div>
  );
}