// app/(root)/checkout/CheckoutClient.tsx
'use client';

import { motion, AnimatePresence } from 'framer-motion';
import { useCart } from '@/hooks/useCart';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { Elements } from '@stripe/react-stripe-js';
import { getStripeClient } from '@/lib/stripe/stripeClient';
import StripePaymentForm from '@/app/components/checkout/StripePaymentForm';
import { useUserStore, User } from '@/stores/userStore';
import type { Country } from './page';
import {
  ShoppingCart,
  ArrowLeft,
  CreditCard,
  Lock,
  Shield,
  CheckCircle,
  User as UserIcon,
  Mail,
  Phone,
  Building,
  Eye,
  EyeOff,
  MessageCircle,
  MapPin,
  Globe,
  AlertCircle,
  ChevronRight,
  Sparkles,
  ArrowRight,
  LogOut,
} from 'lucide-react';

const stripePromise = getStripeClient();

// ── PayPal SVG Icon ───────────────────────────────────────────────────
function PayPalIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 101 32" xmlns="http://www.w3.org/2000/svg">
      <path fill="#253B80" d="M12.237 2.845H6.437c-.392 0-.725.284-.787.672L3.236 19.04a.477.477 0 0 0 .47.551h2.76c.392 0 .725-.284.787-.672l.614-3.895a.794.794 0 0 1 .786-.672h1.83c3.81 0 6.012-1.844 6.588-5.498.259-1.598.01-2.855-.742-3.735-.828-.97-2.297-1.474-4.092-1.474z"/>
      <path fill="#179BD7" d="M37.405 2.845H31.6c-.392 0-.726.284-.787.672l-2.414 15.523a.477.477 0 0 0 .47.551h2.927c.274 0 .508-.2.55-.472l.686-4.351a.794.794 0 0 1 .787-.672h1.83c3.81 0 6.012-1.844 6.589-5.498.26-1.598.01-2.855-.742-3.735-.83-.97-2.296-1.474-4.091-1.474-.001 0-.001.975 0 0z"/>
    </svg>
  );
}

// ── Stripe SVG Icon ───────────────────────────────────────────────────
function StripeIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 60 25" xmlns="http://www.w3.org/2000/svg">
      <path
        fill="#635BFF"
        d="M59.64 14.28h-8.06c.19 1.93 1.6 2.55 3.2 2.55 1.64 0 2.96-.37 4.05-.95v3.32a8.33 8.33 0 0 1-4.56 1.1c-4.01 0-6.83-2.5-6.83-7.48 0-4.19 2.39-7.52 6.3-7.52 3.92 0 5.96 3.28 5.96 7.5 0 .4-.04 1.26-.06 1.48zm-5.92-5.62c-1.03 0-2.17.73-2.17 2.58h4.25c0-1.85-1.07-2.58-2.08-2.58zM40.95 20.3c-1.44 0-2.32-.6-2.9-1.04l-.02 4.63-4.44.97V5.76h3.96l.07 1.09c.56-.69 1.7-1.33 3.23-1.33 3.36 0 5.76 2.93 5.76 7.27 0 4.8-2.54 7.51-5.66 7.51zM40 9.45c-.95 0-1.54.34-1.97.81l.03 6.27c.43.46 1.01.8 1.94.8 1.54 0 2.75-1.22 2.75-3.87 0-2.57-1.22-4.01-2.75-4.01zM28.24 5.76h4.43v14.29h-4.43V5.76zm0-4.52 4.43-.97v3.5l-4.43.97V1.24zM23.95 7.67l-.28-1.91h-3.82v14.29h4.4v-8.56c1.04-1.29 2.8-1.06 3.35-.9V5.76c-.55-.19-2.57-.51-3.65 1.91zM14.56 2.32l-4.33.93-.02 14.38c0 2.65 2 4.55 4.65 4.55 1.48 0 2.56-.27 3.16-.59v-3.43c-.57.23-3.4 1.05-3.4-1.58V9.3h3.4V5.76h-3.4l-.06-3.44zM1.32 13.76c0 .73.61 1.02 1.62 1.02 1.43 0 3.07-.47 4.5-1.3v3.99a12.4 12.4 0 0 1-4.5.8C1 18.27 0 16.15 0 13.54c0-4.44 2.85-6.94 5.72-6.94 1.47 0 2.42.37 3.02.93L8.7 5.76H4.8C2.81 5.76 0 7.72 0 12.16c0 .56.05 1.09.13 1.6l1.19 0z"
      />
    </svg>
  );
}

// ── Step types ────────────────────────────────────────────────────────
type CheckoutStep = 'details' | 'payment';
type PaymentMethod = 'paypal' | 'stripe';

interface FormData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  whatsapp: string;
  company: string;
  country: string;
  city: string;
  zipCode: string;
  password: string;
  confirmPassword: string;
}

interface StripeSession {
  clientSecret: string;
  orderNumber: string;
  paymentIntentId: string;
  total: number;
}

// Helper function to get initial form data from user with proper typing
const getInitialFormData = (user: User | null, isAuthenticated: boolean): FormData => {
  if (isAuthenticated && user) {
    return {
      firstName: user.first_name || '',
      lastName: user.last_name || '',
      email: user.email || '',
      phone: user.phone || '',
      whatsapp: user.whatsapp || '',
      company: user.company || '',
      country: user.country || 'US',
      city: user.city || '',
      zipCode: user.zip_code || '',
      password: '',
      confirmPassword: '',
    };
  }
  return {
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    whatsapp: '',
    company: '',
    country: 'US',
    city: '',
    zipCode: '',
    password: '',
    confirmPassword: '',
  };
}

interface CheckoutClientProps {
  countries: Country[];
}

export default function CheckoutClient({ countries }: CheckoutClientProps) {
  const router = useRouter();
  const { items, getTotalPrice } = useCart();
  const { user, isAuthenticated } = useUserStore();
  
  // Use a ref to track if we've initialized the form
  const initializedRef = useRef(false);
  // Track if redirect has been triggered
  const redirectTriggeredRef = useRef(false);

  // ── State ─────────────────────────────────────────────────────────
  const [step, setStep] = useState<CheckoutStep>('details');
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>('stripe');
  const [isProcessing, setIsProcessing] = useState(false);
  const [apiError, setApiError] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [createAccount, setCreateAccount] = useState(false);
  const [stripeSession, setStripeSession] = useState<StripeSession | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});
  
  // Initialize form data with user data if available (using lazy initialization)
  const [formData, setFormData] = useState<FormData>(() => 
    getInitialFormData(user, isAuthenticated)
  );

  // Handle redirect when cart is empty - only on client side
  useEffect(() => {
    if (items.length === 0 && step === 'details' && !redirectTriggeredRef.current) {
      redirectTriggeredRef.current = true;
      router.push('/cart');
    }
  }, [items.length, step, router]);

  // Mark as initialized after first render if user data was used
  useEffect(() => {
    if (!initializedRef.current && isAuthenticated && user) {
      initializedRef.current = true;
    }
  }, [isAuthenticated, user]);

  // ── Price calculations (no tax) ────────────────────────────────────
  const total = getTotalPrice();
  const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);

  // ── Form handling ─────────────────────────────────────────────────
  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    setFormData((f) => ({ ...f, [e.target.name]: e.target.value }));
    if (errors[e.target.name]) {
      setErrors((err) => ({ ...err, [e.target.name]: '' }));
    }
    setApiError('');
  };

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.firstName.trim()) newErrors.firstName = 'First name is required';
    if (!formData.lastName.trim()) newErrors.lastName = 'Last name is required';
    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Invalid email format';
    }
    if (!formData.phone.trim()) newErrors.phone = 'Phone number is required';
    if (!formData.city.trim()) newErrors.city = 'City is required';
    if (!formData.zipCode.trim()) newErrors.zipCode = 'ZIP code is required';

    if (
      formData.whatsapp &&
      !/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{4,10}$/.test(
        formData.whatsapp
      )
    ) {
      newErrors.whatsapp = 'Invalid phone number format';
    }

    if (createAccount && !isAuthenticated) {
      if (!formData.password) {
        newErrors.password = 'Password is required';
      } else if (formData.password.length < 8) {
        newErrors.password = 'Minimum 8 characters';
      }
      if (formData.password !== formData.confirmPassword) {
        newErrors.confirmPassword = 'Passwords do not match';
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // ── Shared customer payload ───────────────────────────────────────
  const getCustomerPayload = () => ({
    firstName: formData.firstName,
    lastName: formData.lastName,
    email: formData.email,
    phone: formData.phone,
    whatsapp: formData.whatsapp || null,
    company: formData.company || null,
    country: formData.country,
    city: formData.city,
    zipCode: formData.zipCode,
    createAccount: createAccount && !isAuthenticated,
    password: createAccount && !isAuthenticated ? formData.password : undefined,
    userId: isAuthenticated ? user?.id : undefined,
  });

  // ── Handle "Continue to Payment" ──────────────────────────────────
  const handleContinue = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;

    if (paymentMethod === 'paypal') {
      await handlePayPal();
    } else {
      await handleStripeInit();
    }
  };

  // ── PayPal: create order → redirect ──────────────────────────────
  const handlePayPal = async () => {
    setIsProcessing(true);
    setApiError('');

    try {
      const res = await fetch('/api/frontend/checkout/paypal/create-order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customer: getCustomerPayload(),
          items,
          totals: { subtotal: total, total },
        }),
      });

      const data = await res.json();

      if (!data.success) {
        setApiError(data.error || 'Failed to create PayPal order. Please try again.');
        setIsProcessing(false);
        return;
      }

      window.location.assign(data.approvalUrl);
    } catch {
      setApiError('Network error. Please try again.');
      setIsProcessing(false);
    }
  };

  // ── Stripe: create PaymentIntent → show card form ─────────────────
  const handleStripeInit = async () => {
    setIsProcessing(true);
    setApiError('');

    try {
      const res = await fetch('/api/frontend/checkout/stripe/create-payment-intent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customer: getCustomerPayload(),
          items,
          totals: { subtotal: total, total },
        }),
      });

      const data = await res.json();

      if (!data.success) {
        setApiError(data.error || 'Failed to initialize payment. Please try again.');
        setIsProcessing(false);
        return;
      }

      setStripeSession({
        clientSecret: data.clientSecret,
        orderNumber: data.orderNumber,
        paymentIntentId: data.paymentIntentId,
        total: data.total,
      });

      setStep('payment');
      setIsProcessing(false);

    } catch {
      setApiError('Network error. Please check your connection.');
      setIsProcessing(false);
    }
  };

  // Don't render anything while checking redirect (prevents flash)
  if (items.length === 0 && step === 'details') {
    return null;
  }

  // ── Stripe Elements appearance ────────────────────────────────────
  const stripeAppearance = {
    theme: 'stripe' as const,
    variables: {
      colorPrimary: '#6d28d9',
      colorBackground: '#ffffff',
      colorText: '#1e293b',
      colorDanger: '#ef4444',
      fontFamily: 'Inter, system-ui, sans-serif',
      borderRadius: '12px',
      spacingUnit: '4px',
    },
    rules: {
      '.Input': {
        border: '1px solid #e2e8f0',
        boxShadow: 'none',
        padding: '10px 14px',
      },
      '.Input:focus': {
        border: '1px solid #6d28d9',
        boxShadow: '0 0 0 3px rgba(109, 40, 217, 0.1)',
      },
      '.Label': {
        fontWeight: '500',
        color: '#475569',
        fontSize: '13px',
      },
      '.Tab': {
        border: '1px solid #e2e8f0',
        borderRadius: '12px',
      },
      '.Tab--selected': {
        borderColor: '#6d28d9',
        boxShadow: '0 0 0 3px rgba(109, 40, 217, 0.1)',
      },
    },
  };

  return (
    <div className="min-h-screen bg-linear-to-br from-slate-50 via-white to-blue-50/30 pt-28 pb-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        {/* ── Header ─────────────────────────────────────────────── */}
        <div className="mb-8">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div>
              <div className="flex items-center gap-3 mb-2">
                <div className="p-3 bg-white rounded-2xl shadow-lg border border-slate-200/60">
                  <CreditCard className="h-8 w-8 text-slate-700" />
                </div>
                <h1 className="text-3xl sm:text-4xl font-bold text-slate-800">
                  Checkout
                </h1>
              </div>
              <p className="text-slate-600 ml-14">Complete your order securely</p>
            </div>

            {step === 'details' ? (
              <Link
                href="/cart"
                className="inline-flex items-center gap-2 px-4 py-2 bg-white border border-slate-200 rounded-xl text-slate-600 hover:bg-slate-50 transition-all"
              >
                <ArrowLeft className="h-4 w-4" />
                Back to Cart
              </Link>
            ) : (
              <button
                onClick={() => { setStep('details'); setStripeSession(null); }}
                className="inline-flex items-center gap-2 px-4 py-2 bg-white border border-slate-200 rounded-xl text-slate-600 hover:bg-slate-50 transition-all"
              >
                <ArrowLeft className="h-4 w-4" />
                Back to Details
              </button>
            )}
          </div>

          {/* Logged in user info banner */}
          {isAuthenticated && user && step === 'details' && (
            <div className="mt-4 ml-14 p-4 bg-green-50 border border-green-200 rounded-xl flex items-center justify-between">
              <div className="flex items-center gap-3">
                <CheckCircle className="h-5 w-5 text-green-600" />
                <div>
                  <p className="text-sm font-medium text-green-800">
                    Welcome back, {user.first_name || user.email}!
                  </p>
                  <p className="text-xs text-green-600">
                    Your information has been auto-filled. You can update if needed.
                  </p>
                </div>
              </div>
              <button
                onClick={() => useUserStore.getState().logout()}
                className="flex items-center gap-2 px-3 py-1.5 bg-white border border-green-200 rounded-lg text-sm text-green-700 hover:bg-green-50 transition-colors"
              >
                <LogOut className="h-3 w-3" />
                Logout
              </button>
            </div>
          )}

          {/* ── Progress indicator ──────────────────────────────── */}
          <div className="flex items-center gap-2 mt-6 ml-0">
            {(['details', 'payment'] as CheckoutStep[]).map((s, idx) => (
              <div key={s} className="flex items-center gap-2">
                <div
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all ${
                    step === s
                      ? 'bg-slate-800 text-white'
                      : idx === 0 && step === 'payment'
                      ? 'bg-emerald-100 text-emerald-700'
                      : 'bg-slate-100 text-slate-400'
                  }`}
                >
                  {idx === 0 && step === 'payment' ? (
                    <CheckCircle className="h-3 w-3" />
                  ) : (
                    <span>{idx + 1}</span>
                  )}
                  <span className="capitalize">{s === 'details' ? 'Your Details' : 'Payment'}</span>
                </div>
                {idx < 1 && <ChevronRight className="h-4 w-4 text-slate-300" />}
              </div>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* ── Main Content ─────────────────────────────────────── */}
          <div className="lg:col-span-2">
            <AnimatePresence mode="wait">

              {/* ── STEP 1: Contact & Details Form ──────────────── */}
              {step === 'details' && (
                <motion.div
                  key="details"
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: -20 }}
                  className="bg-white rounded-2xl shadow-xl overflow-hidden"
                >
                  <div className="p-6 border-b border-slate-200 bg-linear-to-r from-slate-50 to-white">
                    <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
                      <UserIcon className="h-5 w-5 text-blue-600" />
                      Contact & Billing Information
                      {isAuthenticated && (
                        <span className="ml-2 text-xs bg-green-100 text-green-700 px-2 py-1 rounded-full">
                          Auto-filled from account
                        </span>
                      )}
                    </h2>
                  </div>

                  <form onSubmit={handleContinue} className="p-6 space-y-6">

                    {/* Global API Error */}
                    {apiError && (
                      <motion.div
                        initial={{ opacity: 0, y: -8 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="flex items-start gap-3 p-4 bg-rose-50 border border-rose-200 rounded-xl"
                      >
                        <AlertCircle className="h-5 w-5 text-rose-500 shrink-0 mt-0.5" />
                        <p className="text-rose-700 text-sm">{apiError}</p>
                      </motion.div>
                    )}

                    {/* Name */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      {[
                        { label: 'First Name', name: 'firstName', placeholder: 'John' },
                        { label: 'Last Name', name: 'lastName', placeholder: 'Doe' },
                      ].map((field) => (
                        <div key={field.name}>
                          <label className="block text-sm font-medium text-slate-700 mb-1">
                            {field.label} *
                          </label>
                          <input
                            type="text"
                            name={field.name}
                            value={formData[field.name as keyof FormData]}
                            onChange={handleInputChange}
                            placeholder={field.placeholder}
                            className={`w-full px-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${
                              errors[field.name]
                                ? 'border-red-400 bg-red-50'
                                : 'border-slate-300 hover:border-slate-400'
                            }`}
                          />
                          {errors[field.name] && (
                            <p className="text-xs text-red-500 mt-1">{errors[field.name]}</p>
                          )}
                        </div>
                      ))}
                    </div>

                    {/* Email */}
                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">
                        Email Address *
                      </label>
                      <div className="relative">
                        <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                        <input
                          type="email"
                          name="email"
                          value={formData.email}
                          onChange={handleInputChange}
                          placeholder="john@example.com"
                          disabled={isAuthenticated}
                          className={`w-full pl-10 pr-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${
                            isAuthenticated
                              ? 'bg-slate-50 cursor-not-allowed'
                              : ''
                          } ${
                            errors.email ? 'border-red-400 bg-red-50' : 'border-slate-300 hover:border-slate-400'
                          }`}
                        />
                      </div>
                      {errors.email && (
                        <p className="text-xs text-red-500 mt-1">{errors.email}</p>
                      )}
                      {isAuthenticated && (
                        <p className="text-xs text-slate-400 mt-1">
                          Email is linked to your account and cannot be changed
                        </p>
                      )}
                    </div>

                    {/* Phone + WhatsApp */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">
                          Phone Number *
                        </label>
                        <div className="relative">
                          <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                          <input
                            type="tel"
                            name="phone"
                            value={formData.phone}
                            onChange={handleInputChange}
                            placeholder="+1 234 567 8900"
                            className={`w-full pl-10 pr-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${
                              errors.phone ? 'border-red-400 bg-red-50' : 'border-slate-300 hover:border-slate-400'
                            }`}
                          />
                        </div>
                        {errors.phone && (
                          <p className="text-xs text-red-500 mt-1">{errors.phone}</p>
                        )}
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">
                          WhatsApp
                          <span className="text-slate-400 font-normal ml-1 text-xs">(Optional)</span>
                        </label>
                        <div className="relative">
                          <MessageCircle className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                          <input
                            type="tel"
                            name="whatsapp"
                            value={formData.whatsapp}
                            onChange={handleInputChange}
                            placeholder="+1 234 567 8900"
                            className={`w-full pl-10 pr-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${
                              errors.whatsapp ? 'border-red-400 bg-red-50' : 'border-slate-300 hover:border-slate-400'
                            }`}
                          />
                        </div>
                        {errors.whatsapp && (
                          <p className="text-xs text-red-500 mt-1">{errors.whatsapp}</p>
                        )}
                      </div>
                    </div>

                    {/* Company */}
                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">
                        Company <span className="text-slate-400 font-normal text-xs">(Optional)</span>
                      </label>
                      <div className="relative">
                        <Building className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                        <input
                          type="text"
                          name="company"
                          value={formData.company}
                          onChange={handleInputChange}
                          placeholder="Your Company"
                          className="w-full pl-10 pr-4 py-2.5 border border-slate-300 hover:border-slate-400 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                        />
                      </div>
                    </div>

                    {/* Location - Dynamic Countries List */}
                    <div className="space-y-4">
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                          <label className="block text-sm font-medium text-slate-700 mb-1">Country *</label>
                          <div className="relative">
                            <Globe className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                            <select
                              name="country"
                              value={formData.country}
                              onChange={handleInputChange}
                              className="w-full pl-10 pr-4 py-2.5 border border-slate-300 hover:border-slate-400 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all appearance-none bg-white"
                            >
                              <option value="">Select a country</option>
                              {countries.map((country) => (
                                <option key={country.id} value={country.id}>
                                  {country.name}
                                </option>
                              ))}
                            </select>
                          </div>
                        </div>
                        <div>
                          <label className="block text-sm font-medium text-slate-700 mb-1">City *</label>
                          <div className="relative">
                            <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                            <input
                              type="text"
                              name="city"
                              value={formData.city}
                              onChange={handleInputChange}
                              placeholder="New York"
                              className={`w-full pl-10 pr-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${
                                errors.city ? 'border-red-400 bg-red-50' : 'border-slate-300 hover:border-slate-400'
                              }`}
                            />
                          </div>
                          {errors.city && (
                            <p className="text-xs text-red-500 mt-1">{errors.city}</p>
                          )}
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">ZIP / Postal Code *</label>
                        <input
                          type="text"
                          name="zipCode"
                          value={formData.zipCode}
                          onChange={handleInputChange}
                          placeholder="10001"
                          className={`w-full px-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${
                            errors.zipCode ? 'border-red-400 bg-red-50' : 'border-slate-300 hover:border-slate-400'
                          }`}
                        />
                        {errors.zipCode && (
                          <p className="text-xs text-red-500 mt-1">{errors.zipCode}</p>
                        )}
                      </div>
                    </div>

                    {/* Create Account - Only show if not logged in */}
                    {!isAuthenticated && (
                      <>
                        <div className="pt-4 border-t border-slate-200">
                          <label className="flex items-start gap-3 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={createAccount}
                              onChange={(e) => {
                                setCreateAccount(e.target.checked);
                                if (!e.target.checked) {
                                  setFormData((f) => ({ ...f, password: '', confirmPassword: '' }));
                                  setErrors({});
                                }
                              }}
                              className="w-5 h-5 mt-0.5 text-blue-600 rounded border-slate-300 focus:ring-blue-500"
                            />
                            <div>
                              <span className="font-medium text-slate-800">Create an account</span>
                              <p className="text-xs text-slate-500 mt-0.5">
                                Track orders and enjoy faster checkout next time
                              </p>
                            </div>
                          </label>
                        </div>

                        {/* Password Fields */}
                        <AnimatePresence>
                          {createAccount && (
                            <motion.div
                              initial={{ opacity: 0, height: 0 }}
                              animate={{ opacity: 1, height: 'auto' }}
                              exit={{ opacity: 0, height: 0 }}
                              className="space-y-4 overflow-hidden"
                            >
                              <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">Password *</label>
                                <div className="relative">
                                  <input
                                    type={showPassword ? 'text' : 'password'}
                                    name="password"
                                    value={formData.password}
                                    onChange={handleInputChange}
                                    placeholder="Create a password"
                                    className={`w-full px-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent pr-10 transition-all ${
                                      errors.password ? 'border-red-400 bg-red-50' : 'border-slate-300 hover:border-slate-400'
                                    }`}
                                  />
                                  <button
                                    type="button"
                                    onClick={() => setShowPassword(!showPassword)}
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                                  >
                                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                  </button>
                                </div>
                                {errors.password ? (
                                  <p className="text-xs text-red-500 mt-1">{errors.password}</p>
                                ) : (
                                  <p className="text-xs text-slate-400 mt-1">Minimum 8 characters</p>
                                )}
                              </div>
                              <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">Confirm Password *</label>
                                <input
                                  type={showPassword ? 'text' : 'password'}
                                  name="confirmPassword"
                                  value={formData.confirmPassword}
                                  onChange={handleInputChange}
                                  placeholder="Confirm your password"
                                  className={`w-full px-4 py-2.5 border rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all ${
                                    errors.confirmPassword ? 'border-red-400 bg-red-50' : 'border-slate-300 hover:border-slate-400'
                                  }`}
                                />
                                {errors.confirmPassword && (
                                  <p className="text-xs text-red-500 mt-1">{errors.confirmPassword}</p>
                                )}
                              </div>
                            </motion.div>
                          )}
                        </AnimatePresence>
                      </>
                    )}

                    {/* ── Payment Method Selector ────────────────── */}
                    <div className="pt-4 border-t border-slate-200">
                      <h3 className="text-lg font-semibold text-slate-800 mb-4 flex items-center gap-2">
                        <CreditCard className="h-5 w-5 text-blue-600" />
                        Select Payment Method
                      </h3>

                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        {/* Stripe Option */}
                        <button
                          type="button"
                          onClick={() => setPaymentMethod('stripe')}
                          className={`relative p-4 rounded-2xl border-2 text-left transition-all duration-200 ${
                            paymentMethod === 'stripe'
                              ? 'border-violet-500 bg-violet-50 shadow-md shadow-violet-100'
                              : 'border-slate-200 hover:border-slate-300 bg-white'
                          }`}
                        >
                          {paymentMethod === 'stripe' && (
                            <div className="absolute top-3 right-3">
                              <div className="w-5 h-5 rounded-full bg-violet-500 flex items-center justify-center">
                                <CheckCircle className="h-3 w-3 text-white" />
                              </div>
                            </div>
                          )}
                          <div className="flex items-center gap-2 mb-2">
                            <div className="w-10 h-8 bg-white border border-slate-100 rounded-lg flex items-center justify-center shadow-sm">
                              <StripeIcon className="h-4 w-auto" />
                            </div>
                            <span className="font-semibold text-slate-800 text-sm">Card Payment</span>
                          </div>
                          <p className="text-xs text-slate-500">
                            Visa, Mastercard, Amex, Apple Pay & more
                          </p>
                          {paymentMethod === 'stripe' && (
                            <div className="mt-2 flex items-center gap-1">
                              <Sparkles className="h-3 w-3 text-violet-500" />
                              <span className="text-xs font-medium text-violet-600">Recommended</span>
                            </div>
                          )}
                        </button>

                        {/* PayPal Option */}
                        <button
                          type="button"
                          onClick={() => setPaymentMethod('paypal')}
                          className={`relative p-4 rounded-2xl border-2 text-left transition-all duration-200 ${
                            paymentMethod === 'paypal'
                              ? 'border-blue-400 bg-blue-50 shadow-md shadow-blue-100'
                              : 'border-slate-200 hover:border-slate-300 bg-white'
                          }`}
                        >
                          {paymentMethod === 'paypal' && (
                            <div className="absolute top-3 right-3">
                              <div className="w-5 h-5 rounded-full bg-blue-500 flex items-center justify-center">
                                <CheckCircle className="h-3 w-3 text-white" />
                              </div>
                            </div>
                          )}
                          <div className="flex items-center gap-2 mb-2">
                            <div className="w-10 h-8 bg-white border border-slate-100 rounded-lg flex items-center justify-center shadow-sm">
                              <PayPalIcon className="h-4 w-auto" />
                            </div>
                            <span className="font-semibold text-slate-800 text-sm">PayPal</span>
                          </div>
                          <p className="text-xs text-slate-500">
                            Pay with your PayPal account or card
                          </p>
                          {paymentMethod === 'paypal' && (
                            <div className="mt-2 flex items-center gap-1">
                              <Shield className="h-3 w-3 text-blue-500" />
                              <span className="text-xs font-medium text-blue-600">Buyer Protection</span>
                            </div>
                          )}
                        </button>
                      </div>
                    </div>

                    {/* ── Continue Button ────────────────────────── */}
                    <button
                      type="submit"
                      disabled={isProcessing}
                      className={`w-full flex items-center justify-center gap-3 py-4 rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.01] disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none text-white ${
                        paymentMethod === 'stripe'
                          ? 'bg-linear-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700'
                          : 'bg-[#0070BA] hover:bg-[#005ea6]'
                      }`}
                    >
                      {isProcessing ? (
                        <>
                          <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                          <span>
                            {paymentMethod === 'stripe' ? 'Setting up payment...' : 'Redirecting to PayPal...'}
                          </span>
                        </>
                      ) : (
                        <>
                          <Lock className="h-5 w-5" />
                          <span>
                            {paymentMethod === 'stripe'
                              ? `Continue to Card Payment`
                              : `Pay $${total.toLocaleString('en-US', { minimumFractionDigits: 2 })} with PayPal`}
                          </span>
                          <ArrowRight className="h-4 w-4" />
                        </>
                      )}
                    </button>

                    {/* Security badges */}
                    <div className="flex flex-wrap justify-center gap-4 pt-1">
                      {[
                        { icon: Lock, text: '256-bit SSL' },
                        { icon: Shield, text: 'PCI Compliant' },
                        { icon: CheckCircle, text: 'Money-back Guarantee' },
                      ].map(({ icon: Icon, text }) => (
                        <div key={text} className="flex items-center gap-1.5 text-xs text-slate-500">
                          <Icon className="h-3 w-3 text-emerald-600" />
                          {text}
                        </div>
                      ))}
                    </div>
                  </form>
                </motion.div>
              )}

              {/* ── STEP 2: Stripe Payment Form ──────────────────── */}
              {step === 'payment' && stripeSession && (
                <motion.div
                  key="payment"
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: 20 }}
                  className="bg-white rounded-2xl shadow-xl overflow-hidden"
                >
                  <div className="p-6 border-b border-slate-200 bg-linear-to-r from-violet-50 to-indigo-50">
                    <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
                      <CreditCard className="h-5 w-5 text-violet-600" />
                      Secure Card Payment
                    </h2>
                    <p className="text-sm text-slate-500 mt-1">
                      Order{' '}
                      <span className="font-mono font-semibold text-slate-700">
                        {stripeSession.orderNumber}
                      </span>{' '}
                      · Total:{' '}
                      <span className="font-semibold text-slate-800">
                        ${stripeSession.total.toLocaleString('en-US', { minimumFractionDigits: 2 })}
                      </span>
                    </p>
                  </div>

                  <div className="p-6">
                    <Elements
                      stripe={stripePromise}
                      options={{
                        clientSecret: stripeSession.clientSecret,
                        appearance: stripeAppearance,
                      }}
                    >
                      <StripePaymentForm
                        orderNumber={stripeSession.orderNumber}
                        paymentIntentId={stripeSession.paymentIntentId}
                        total={stripeSession.total}
                      />
                    </Elements>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* ── Order Summary ─────────────────────────────────────── */}
          <div className="lg:col-span-1">
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              className="sticky top-28"
            >
              <div className="bg-white rounded-2xl shadow-xl overflow-hidden">
                <div className="bg-linear-to-r from-blue-600 to-cyan-600 p-6 text-white">
                  <h3 className="text-xl font-bold mb-1 flex items-center gap-2">
                    <ShoppingCart className="h-5 w-5" />
                    Order Summary
                  </h3>
                  <p className="text-blue-100 text-sm">{itemCount} item{itemCount !== 1 ? 's' : ''}</p>
                </div>

                <div className="p-6 space-y-6">
                  {/* Items — stays full throughout the entire checkout */}
                  <div className="space-y-3 max-h-64 overflow-y-auto overscroll-contain pr-1">
                    {items.map((item) => (
                      <div key={item.id} className="flex justify-between text-sm">
                        <span className="text-slate-600 truncate mr-2 flex-1">
                          {item.name}
                          {item.quantity > 1 && (
                            <span className="text-slate-400 ml-1">×{item.quantity}</span>
                          )}
                        </span>
                        <span className="font-semibold text-slate-800 shrink-0">
                          ${(item.price * item.quantity).toLocaleString('en-US', { minimumFractionDigits: 2 })}
                        </span>
                      </div>
                    ))}
                  </div>

                  <div className="border-t border-slate-200 pt-4">
                    <div className="flex justify-between items-center">
                      <span className="text-lg font-bold text-slate-800">Total</span>
                      <span className="text-2xl font-bold text-blue-600">
                        ${total.toLocaleString('en-US', { minimumFractionDigits: 2 })}
                      </span>
                    </div>
                  </div>

                  {/* Payment method badges */}
                  <div className="flex flex-wrap gap-2 pt-2 border-t border-slate-100">
                    {['PayPal', 'Visa', 'Mastercard', 'Amex', 'Apple Pay'].map((brand) => (
                      <span
                        key={brand}
                        className="px-2 py-1 bg-slate-50 border border-slate-200 rounded-lg text-xs font-medium text-slate-500"
                      >
                        {brand}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  );
}