'use client';

import { motion, AnimatePresence } from 'framer-motion';
import { useCart } from '@/hooks/useCart';
import Link from 'next/link';
import { useState, useCallback, useMemo } from 'react';
import {
  ShoppingCart,
  Trash2,
  Plus,
  Minus,
  ArrowRight,
  ExternalLink,
  Sparkles,
  Shield,
  ThumbsUp,
  CreditCard,
  Lock,
  TrendingUp,
  Users,
  Globe,
  MessageCircle,
  AlertCircle,
  Star,
  Crown,
  Zap,
  FileText,
  X,
  HelpCircle,
  Copy,
  Check,
  ArrowLeft,
  CheckCircle2,
  Info,
  AlertTriangle,
  ChevronDown,
  Save,
} from 'lucide-react';
import { useRouter } from 'next/navigation';
import PageHero from '@/app/components/Frontend/PageHero';
import { CartItem, ContentWritingDetails } from '@/hooks/useCart';

// ─── Toast System ─────────────────────────────────────────────────────────────

type ToastType = 'success' | 'error' | 'info' | 'warning';

interface Toast {
  id: string;
  message: string;
  type: ToastType;
}

function ToastContainer({ toasts, onRemove }: { toasts: Toast[]; onRemove: (id: string) => void }) {
  const icons: Record<ToastType, React.ReactNode> = {
    success: <CheckCircle2 className="h-4 w-4 text-emerald-500" />,
    error: <AlertCircle className="h-4 w-4 text-rose-500" />,
    info: <Info className="h-4 w-4 text-blue-500" />,
    warning: <AlertTriangle className="h-4 w-4 text-amber-500" />,
  };

  const bg: Record<ToastType, string> = {
    success: 'bg-emerald-50 border-emerald-200',
    error: 'bg-rose-50 border-rose-200',
    info: 'bg-blue-50 border-blue-200',
    warning: 'bg-amber-50 border-amber-200',
  };

  return (
    <div className="fixed top-4 right-4 z-100 flex flex-col gap-2 pointer-events-none">
      <AnimatePresence>
        {toasts.map(toast => (
          <motion.div
            key={toast.id}
            initial={{ opacity: 0, x: 60, scale: 0.95 }}
            animate={{ opacity: 1, x: 0, scale: 1 }}
            exit={{ opacity: 0, x: 60, scale: 0.95 }}
            transition={{ duration: 0.2 }}
            className={`pointer-events-auto flex items-center gap-2 px-4 py-3 rounded-xl border shadow-lg text-sm font-medium text-slate-700 ${bg[toast.type]}`}
          >
            {icons[toast.type]}
            <span>{toast.message}</span>
            <button
              onClick={() => onRemove(toast.id)}
              className="ml-2 p-0.5 hover:bg-black/10 rounded-md transition-colors"
            >
              <X className="h-3.5 w-3.5" />
            </button>
          </motion.div>
        ))}
      </AnimatePresence>
    </div>
  );
}

function useToast() {
  const [toasts, setToasts] = useState<Toast[]>([]);

  const addToast = useCallback((message: string, type: ToastType = 'success') => {
    const id = crypto.randomUUID();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 3500);
  }, []);

  const removeToast = useCallback((id: string) => {
    setToasts(prev => prev.filter(t => t.id !== id));
  }, []);

  return { toasts, addToast, removeToast };
}

// ─── Content Writing Form Component ─────────────────────────────────────────

function ContentWritingForm({ 
  item, 
  onUpdate 
}: { 
  item: CartItem; 
  onUpdate: (details: ContentWritingDetails) => void;
}) {
  const [details, setDetails] = useState<ContentWritingDetails>(
    item.contentWritingDetails || {
      desiredTopic: '',
      targetKeywords: '',
      wordCount: 500,
      specialInstructions: '',
    }
  );

  const [isOpen, setIsOpen] = useState(false);
  const [isSaved, setIsSaved] = useState(false);

  // Calculate hasChanges using useMemo instead of useEffect
  const hasChanges = useMemo(() => {
    const savedDetails = item.contentWritingDetails;
    if (savedDetails) {
      const isEqual = 
        savedDetails.desiredTopic === details.desiredTopic &&
        savedDetails.targetKeywords === details.targetKeywords &&
        savedDetails.wordCount === details.wordCount &&
        savedDetails.specialInstructions === details.specialInstructions;
      return !isEqual;
    }
    // If no saved details, check if any field has value
    return !!(details.desiredTopic || details.targetKeywords || details.specialInstructions);
  }, [details, item.contentWritingDetails]);

  const handleChange = (field: keyof ContentWritingDetails, value: string | number) => {
    const updated = { ...details, [field]: value };
    setDetails(updated);
  };

  const handleSave = () => {
    onUpdate(details);
    setIsSaved(true);
    setTimeout(() => setIsSaved(false), 2000);
  };

  const hasRequiredFields = details.desiredTopic.trim() !== '';

  return (
    <div className="mt-4 pt-4 border-t border-slate-100">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 text-blue-600 hover:text-blue-700 font-medium mb-3 transition-colors"
      >
        <Sparkles className="h-4 w-4" />
        {isOpen ? 'Hide' : 'Show'} Content Writing Details
        <ChevronDown className={`h-4 w-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {isOpen && (
        <div className="space-y-4 bg-linear-to-r from-blue-50 to-cyan-50 rounded-xl p-4">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <Sparkles className="h-5 w-5 text-blue-600" />
              <h4 className="font-semibold text-slate-800">Content Writing Requirements</h4>
              <span className="text-xs text-blue-600 bg-blue-100 px-2 py-0.5 rounded-full">
                Included in Service
              </span>
            </div>
            
            {/* Saved Indicator */}
            {item.contentWritingDetails?.desiredTopic && !hasChanges && (
              <div className="flex items-center gap-1 text-green-600 bg-green-100 px-2 py-1 rounded-lg text-xs">
                <CheckCircle2 className="h-3 w-3" />
                <span>Saved</span>
              </div>
            )}
            
            {hasChanges && (
              <div className="flex items-center gap-1 text-amber-600 bg-amber-100 px-2 py-1 rounded-lg text-xs">
                <AlertCircle className="h-3 w-3" />
                <span>Unsaved changes</span>
              </div>
            )}
          </div>

          {/* Desired Topic */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              Desired Topic <span className="text-red-500">*</span>
            </label>
            <textarea
              rows={3}
              className="w-full px-4 py-2 border border-slate-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
              placeholder="What topic would you like the content to cover?"
              value={details.desiredTopic}
              onChange={(e) => handleChange('desiredTopic', e.target.value)}
            />
          </div>

          {/* Target Keywords */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              Target Keywords
            </label>
            <input
              type="text"
              className="w-full px-4 py-2 border border-slate-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
              placeholder="e.g., digital marketing, SEO tips, content strategy"
              value={details.targetKeywords}
              onChange={(e) => handleChange('targetKeywords', e.target.value)}
            />
            <p className="text-xs text-slate-500 mt-1">
              Separate multiple keywords with commas
            </p>
          </div>

          {/* Word Count */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              Word Count <span className="text-red-500">*</span>
            </label>
            <select
              className="w-full px-4 py-2 border border-slate-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
              value={details.wordCount}
              onChange={(e) => handleChange('wordCount', parseInt(e.target.value))}
            >
              <option value={300}>300 words</option>
              <option value={500}>500 words (Standard)</option>
              <option value={800}>800 words</option>
              <option value={1000}>1000 words</option>
              <option value={1500}>1500 words</option>
              <option value={2000}>2000 words</option>
            </select>
          </div>

          {/* Special Instructions */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              Special Instructions
            </label>
            <textarea
              rows={3}
              className="w-full px-4 py-2 border border-slate-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
              placeholder="Any specific requirements, tone of voice, target audience, or examples to follow?"
              value={details.specialInstructions}
              onChange={(e) => handleChange('specialInstructions', e.target.value)}
            />
          </div>

          {/* Save Button */}
          <div className="flex gap-3 pt-2">
            <button
              onClick={handleSave}
              disabled={!hasChanges}
              className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-xl font-semibold transition-all duration-300 ${
                hasChanges
                  ? 'bg-blue-600 hover:bg-blue-700 text-white shadow-md hover:shadow-lg cursor-pointer'
                  : 'bg-gray-300 text-gray-500 cursor-not-allowed'
              }`}
            >
              {isSaved ? (
                <>
                  <CheckCircle2 className="h-4 w-4" />
                  Saved!
                </>
              ) : (
                <>
                  <Save className="h-4 w-4" />
                  Save Content Details
                </>
              )}
            </button>
          </div>

          {/* Validation Indicator */}
          {!hasRequiredFields && (
            <div className="flex items-center gap-2 text-amber-600 text-sm bg-amber-50 p-2 rounded-lg">
              <AlertCircle className="h-4 w-4" />
              Please provide a topic before proceeding to checkout
            </div>
          )}
          
          {hasRequiredFields && !hasChanges && item.contentWritingDetails?.desiredTopic && (
            <div className="flex items-center gap-2 text-green-600 text-sm bg-green-50 p-2 rounded-lg">
              <CheckCircle2 className="h-4 w-4" />
              Your content requirements have been saved and will be processed with your order
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

const getDAColor = (da: number) => {
  if (da >= 90) return 'text-emerald-600';
  if (da >= 80) return 'text-blue-600';
  if (da >= 70) return 'text-amber-600';
  return 'text-rose-600';
};

const getAuthorityBadge = (da: number) => {
  if (da >= 90) return { color: 'from-emerald-500 to-teal-500', text: 'Elite', icon: Crown };
  if (da >= 80) return { color: 'from-blue-500 to-cyan-500', text: 'Premium', icon: Star };
  if (da >= 70) return { color: 'from-amber-500 to-orange-500', text: 'Quality', icon: Zap };
  return { color: 'from-gray-500 to-slate-500', text: 'Standard', icon: Globe };
};

const fadeInUp = {
  initial: { opacity: 0, y: 20 },
  animate: { opacity: 1, y: 0 },
  transition: { duration: 0.5 },
};

const TEMPLATE_URL = 'https://docs.google.com/spreadsheets/d/1-template-id/copy';

// ─── Main Component ───────────────────────────────────────────────────────────

export default function CartClient() {
  const {
    items,
    removeItem,
    updateQuantity,
    updateItemDocument,
    removeItemDocument,
    updateContentWritingDetails,
    getTotalPrice,
    clearCart,
  } = useCart();

  const { toasts, addToast, removeToast } = useToast();

  const [showClearCartModal, setShowClearCartModal] = useState(false);
  const [copiedTemplate, setCopiedTemplate] = useState(false);
  const [urlInputs, setUrlInputs] = useState<Record<string, string>>({});

  const router = useRouter();

  // Initialize urlInputs only when items change - use a key-based approach
  // Instead of useEffect, we'll initialize lazily in the onChange handler
  const getUrlInput = useCallback((itemId: string) => {
    return urlInputs[itemId] ?? '';
  }, [urlInputs]);

  const setUrlInput = useCallback((itemId: string, value: string) => {
    setUrlInputs(prev => ({ ...prev, [itemId]: value }));
  }, []);

  const total = getTotalPrice();
  const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
  
  // Items that need content (either website without content service OR package with content service)
  const itemsNeedingContent = items.filter(
    item => (item.type === 'website' && !item.contentService) || item.type === 'package'
  );

  const handleQuantityChange = useCallback(
    (id: string, newQuantity: number) => {
      if (newQuantity < 1) return;
      updateQuantity(id, newQuantity);
    },
    [updateQuantity]
  );

  const handleRemoveItem = useCallback(
    (id: string, name: string) => {
      removeItem(id);
      addToast(`"${name}" removed from cart`, 'info');
    },
    [removeItem, addToast]
  );

  const handleClearCart = useCallback(() => {
    clearCart();
    setShowClearCartModal(false);
    addToast('Cart cleared successfully', 'info');
  }, [clearCart, addToast]);

  const handleUrlSubmit = useCallback(
    (itemId: string, isBulkOrder: boolean, isPackage: boolean = false) => {
      const url = getUrlInput(itemId);
      if (!url || !url.startsWith('http')) {
        addToast('Please enter a valid URL starting with http:// or https://', 'warning');
        return;
      }

      const item = items.find(i => i.id === itemId);
      if (item) {
        updateItemDocument(itemId, {
          id: crypto.randomUUID(),
          cartItemId: itemId,
          websiteId: item.websiteId!,
          websiteName: item.name,
          uploadType: 'url',
          url,
          uploadedAt: new Date(),
        });
        
        if (isPackage) {
          addToast('Google Sheet URL saved successfully!', 'success');
        } else if (isBulkOrder) {
          addToast('Google Sheet URL saved successfully!', 'success');
        } else {
          addToast('Google Docs URL saved successfully!', 'success');
        }
        
        // Clear the input after saving
        setUrlInput(itemId, '');
      }
    },
    [getUrlInput, items, updateItemDocument, addToast, setUrlInput]
  );

  const handleRemoveDocument = useCallback(
    (itemId: string) => {
      removeItemDocument(itemId);
      addToast('Document URL removed', 'info');
    },
    [removeItemDocument, addToast]
  );

  const handleCheckout = useCallback(() => {
    // Check for missing documents in items that need content
    const missingDocuments = itemsNeedingContent.filter(item => !item.document);
    if (missingDocuments.length > 0) {
      addToast(
        `Please provide content URLs for: ${missingDocuments.map(i => i.name).join(', ')}`,
        'warning'
      );
      return;
    }

    // Check for missing content writing details in content-service items
    const itemsWithMissingDetails = items.filter(
      item => item.contentService && (!item.contentWritingDetails || !item.contentWritingDetails.desiredTopic)
    );
    
    if (itemsWithMissingDetails.length > 0) {
      addToast(
        `Please provide content writing details for: ${itemsWithMissingDetails.map(i => i.name).join(', ')}`,
        'warning'
      );
      return;
    }

    router.push('/checkout');
  }, [itemsNeedingContent, items, addToast, router]);

  const copyGoogleSheetTemplate = useCallback(() => {
    navigator.clipboard.writeText(TEMPLATE_URL);
    setCopiedTemplate(true);
    addToast('Template URL copied to clipboard!', 'success');
    setTimeout(() => setCopiedTemplate(false), 2000);
  }, [addToast]);

  return (
    <div className="min-h-screen bg-linear-to-br from-slate-50 via-white to-blue-50/30">
      <ToastContainer toasts={toasts} onRemove={removeToast} />

      <PageHero
        title="Shopping Cart"
        subtitle="Review and manage your selected items"
        description="Review your selected websites and publishing opportunities. Manage quantities, upload content, and proceed to secure checkout."
        icon={<ShoppingCart className="h-4 w-4" />}
        badge="Secure Checkout"
        breadcrumbs={[
          { name: 'Home', href: '/' },
          { name: 'Cart', href: '/cart' },
        ]}
        stats={[
          { icon: <Shield className="h-4 w-4" />, label: 'Secure Payment' },
          { icon: <Lock className="h-4 w-4" />, label: 'SSL Encrypted' },
          { icon: <ThumbsUp className="h-4 w-4" />, label: 'Money-back Guarantee' },
        ]}
      />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">
        {items.length === 0 ? (
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-white rounded-2xl shadow-xl p-12 text-center"
          >
            <div className="relative inline-block mb-6">
              <div className="w-32 h-32 bg-linear-to-br from-slate-100 to-slate-200 rounded-3xl flex items-center justify-center shadow-inner">
                <ShoppingCart className="h-16 w-16 text-slate-400" />
              </div>
              <div className="absolute -top-2 -right-2 w-10 h-10 bg-white rounded-full shadow-lg flex items-center justify-center">
                <Star className="h-5 w-5 text-amber-500" />
              </div>
            </div>

            <h2 className="text-2xl font-bold text-slate-800 mb-3">Your Cart is Empty</h2>
            <p className="text-slate-600 mb-8 max-w-md mx-auto">
              Discover premium publishing opportunities to elevate your brand authority and boost
              your SEO rankings.
            </p>

            <Link
              href="/websites"
              className="inline-flex items-center gap-2 px-8 py-4 bg-linear-to-r from-blue-600 to-cyan-600 text-white rounded-xl font-semibold hover:shadow-lg hover:scale-105 transition-all duration-300"
            >
              Browse Websites
              <ArrowRight className="h-5 w-5" />
            </Link>
          </motion.div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div className="lg:col-span-2 space-y-6">
              <motion.div
                initial="initial"
                animate="animate"
                variants={{ animate: { transition: { staggerChildren: 0.1 } } }}
                className="space-y-4"
              >
                {items.map(item => {
                  const authorityBadge = getAuthorityBadge(item.da || 0);
                  const AuthorityIcon = authorityBadge.icon;
                  const itemTotal = item.price * item.quantity;
                  const needsContent = (item.type === 'website' && !item.contentService) || item.type === 'package';
                  const hasContentService = item.contentService;
                  const hasDocument = !!item.document;
                  const isBulkOrder = item.quantity > 1;
                  const isPackage = item.type === 'package';

                  return (
                    <motion.div
                      key={item.id}
                      variants={fadeInUp}
                      className="bg-white rounded-2xl shadow-lg overflow-hidden hover:shadow-xl transition-all duration-300"
                    >
                      <div className="p-6">
                        <div className="flex flex-col md:flex-row md:items-start justify-between gap-4 mb-4">
                          <div className="flex gap-4 flex-1">
                            <div className="w-16 h-16 bg-linear-to-br from-blue-50 to-cyan-50 rounded-xl flex items-center justify-center shrink-0">
                              {isPackage ? (
                                <Package className="h-8 w-8 text-blue-600" />
                              ) : (
                                <Globe className="h-8 w-8 text-blue-600" />
                              )}
                            </div>

                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2 flex-wrap mb-1">
                                <h3 className="font-semibold text-slate-800 text-lg">{item.name}</h3>
                                {!isPackage && (
                                  <div
                                    className={`px-2 py-0.5 rounded-full bg-linear-to-r ${authorityBadge.color} text-white text-xs font-semibold flex items-center gap-1`}
                                  >
                                    <AuthorityIcon className="h-3 w-3" />
                                    {authorityBadge.text}
                                  </div>
                                )}
                                {isBulkOrder && !isPackage && (
                                  <div className="px-2 py-0.5 rounded-full bg-purple-100 text-purple-700 text-xs font-semibold flex items-center gap-1">
                                    <Users className="h-3 w-3" />
                                    Bulk Order ({item.quantity} posts)
                                  </div>
                                )}
                                {isPackage && (
                                  <div className="px-2 py-0.5 rounded-full bg-purple-100 text-purple-700 text-xs font-semibold flex items-center gap-1">
                                    <Package className="h-3 w-3" />
                                    Package
                                  </div>
                                )}
                              </div>
                              {!isPackage && (
                                <>
                                  <p className="text-slate-500 text-sm break-all">{item.domain}</p>
                                  <div className="flex items-center gap-3 mt-2 text-xs">
                                    {item.da && (
                                      <div className="flex items-center gap-1">
                                        <TrendingUp className={`h-3 w-3 ${getDAColor(item.da)}`} />
                                        <span className="text-slate-600">DA {item.da}</span>
                                      </div>
                                    )}
                                    {item.dr && (
                                      <div className="flex items-center gap-1">
                                        <Users className="h-3 w-3 text-orange-500" />
                                        <span className="text-slate-600">DR {item.dr}</span>
                                      </div>
                                    )}
                                  </div>
                                </>
                              )}

                              {hasContentService && (
                                <div className="mt-2 inline-flex items-center gap-1 px-2 py-1 bg-green-50 text-green-700 rounded-lg text-xs">
                                  <Sparkles className="h-3 w-3" />
                                  Content Writing Included (${item.contentServicePrice}/article)
                                </div>
                              )}
                            </div>
                          </div>

                          <div className="flex items-center gap-3">
                            <div className="flex items-center gap-2 bg-slate-100 rounded-xl p-1">
                              <button
                                onClick={() => handleQuantityChange(item.id, item.quantity - 1)}
                                className="p-2 hover:bg-white rounded-lg transition-colors text-slate-600 hover:text-slate-800 disabled:opacity-40 disabled:cursor-not-allowed"
                                disabled={item.quantity <= 1}
                                aria-label="Decrease quantity"
                              >
                                <Minus className="h-4 w-4" />
                              </button>
                              <span className="w-10 text-center font-semibold text-slate-800">
                                {item.quantity}
                              </span>
                              <button
                                onClick={() => handleQuantityChange(item.id, item.quantity + 1)}
                                className="p-2 hover:bg-white rounded-lg transition-colors text-slate-600 hover:text-slate-800"
                                aria-label="Increase quantity"
                              >
                                <Plus className="h-4 w-4" />
                              </button>
                            </div>

                            <button
                              onClick={() => handleRemoveItem(item.id, item.name)}
                              className="p-2 bg-rose-50 text-rose-600 rounded-xl hover:bg-rose-100 transition-all duration-300"
                              aria-label={`Remove ${item.name}`}
                            >
                              <Trash2 className="h-5 w-5" />
                            </button>
                          </div>
                        </div>

                        {/* Content URL Section for items that need content (websites without content service OR packages) */}
                        {needsContent && (
                          <div className="mt-4 pt-4 border-t border-slate-100">
                            <div className="flex items-center gap-2 mb-3">
                              <FileText className="h-4 w-4 text-blue-600" />
                              <span className="text-sm font-medium text-slate-700">
                                {isPackage 
                                  ? 'Google Sheet Required (Content URLs)'
                                  : isBulkOrder 
                                    ? 'Google Sheet Required' 
                                    : 'Google Docs URL Required'}
                              </span>
                              {isPackage && (
                                <div className="flex items-center gap-1 text-xs text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full">
                                  <Sparkles className="h-3 w-3" />
                                  Free Content Writing Included
                                </div>
                              )}
                              {isBulkOrder && !isPackage && (
                                <div className="flex items-center gap-1 text-xs text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full">
                                  <HelpCircle className="h-3 w-3" />
                                  Bulk Order
                                </div>
                              )}
                            </div>

                            {!hasDocument ? (
                              <div className="space-y-3">
                                {/* Always show Google Sheet/URL input for packages and bulk orders */}
                                {(isPackage || isBulkOrder) ? (
                                  <>
                                    <div className="bg-blue-50 rounded-xl p-4 mb-3">
                                      <div className="flex items-start gap-2">
                                        <HelpCircle className="h-4 w-4 text-blue-600 mt-0.5 shrink-0" />
                                        <div className="text-xs text-blue-800">
                                          <p className="font-semibold mb-1">
                                            How to submit your content URLs:
                                          </p>
                                          <ol className="list-decimal list-inside space-y-1 ml-2">
                                            <li>
                                              Create a Google Sheet with columns: Title, Content URL,
                                              Target Keywords, Notes
                                            </li>
                                            <li>Add each article`s details in separate rows</li>
                                            <li>Share the Google Sheet with view access</li>
                                            <li>Paste the sheet URL below</li>
                                          </ol>
                                          <button
                                            onClick={copyGoogleSheetTemplate}
                                            className="mt-2 inline-flex items-center gap-1 text-blue-700 hover:text-blue-800 font-medium"
                                          >
                                            {copiedTemplate ? (
                                              <>
                                                <Check className="h-3 w-3" />
                                                Copied!
                                              </>
                                            ) : (
                                              <>
                                                <Copy className="h-3 w-3" />
                                                Copy template link
                                              </>
                                            )}
                                          </button>
                                        </div>
                                      </div>
                                    </div>

                                    <div className="flex gap-2">
                                      <input
                                        type="url"
                                        placeholder="https://docs.google.com/spreadsheets/d/your-sheet-id"
                                        className="flex-1 px-4 py-2 border border-slate-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                                        value={getUrlInput(item.id)}
                                        onChange={e => setUrlInput(item.id, e.target.value)}
                                      />
                                      <button
                                        onClick={() => handleUrlSubmit(item.id, true, isPackage)}
                                        className="px-4 py-2 bg-slate-800 text-white rounded-xl hover:bg-slate-700 transition-colors whitespace-nowrap"
                                      >
                                        Save Sheet URL
                                      </button>
                                    </div>
                                  </>
                                ) : (
                                  // Single item - Google Docs URL input only
                                  <div className="flex gap-2">
                                    <input
                                      type="url"
                                      placeholder="https://docs.google.com/document/d/your-doc-id"
                                      className="flex-1 px-4 py-2 border border-slate-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                                      value={getUrlInput(item.id)}
                                      onChange={e => setUrlInput(item.id, e.target.value)}
                                    />
                                    <button
                                      onClick={() => handleUrlSubmit(item.id, false, false)}
                                      className="px-4 py-2 bg-slate-800 text-white rounded-xl hover:bg-slate-700 transition-colors whitespace-nowrap"
                                    >
                                      Save URL
                                    </button>
                                  </div>
                                )}
                              </div>
                            ) : (
                              <div className="bg-green-50 rounded-xl p-4">
                                <div className="flex items-center justify-between">
                                  <div className="flex items-center gap-3 flex-1 min-w-0">
                                    <ExternalLink className="h-5 w-5 text-green-600 shrink-0" />
                                    <div className="min-w-0">
                                      <p className="text-sm font-medium text-green-800 truncate">
                                        {item.document?.url}
                                      </p>
                                      <p className="text-xs text-green-600">
                                        {isPackage 
                                          ? 'Google Sheet linked - Content URLs provided'
                                          : isBulkOrder 
                                            ? 'Google Sheet linked' 
                                            : 'Google Docs URL saved'}
                                      </p>
                                    </div>
                                  </div>
                                  <button
                                    onClick={() => handleRemoveDocument(item.id)}
                                    className="p-1 hover:bg-green-100 rounded-lg transition-colors shrink-0"
                                    aria-label="Remove document"
                                  >
                                    <X className="h-4 w-4 text-green-600" />
                                  </button>
                                </div>
                              </div>
                            )}
                          </div>
                        )}

                        {/* Content Writing Form for items with content service */}
                        {hasContentService && (
                          <ContentWritingForm
                            item={item}
                            onUpdate={(details) => updateContentWritingDetails(item.id, details)}
                          />
                        )}

                        <div className="mt-4 pt-4 border-t border-slate-100 flex items-center justify-between">
                          <div className="text-sm text-slate-500">
                            Unit Price: ${item.price.toLocaleString()}
                          </div>
                          <div className="text-right">
                            <div className="text-sm text-slate-500">Total</div>
                            <div className="text-xl font-bold text-blue-600">
                              ${itemTotal.toLocaleString()}
                            </div>
                          </div>
                        </div>
                      </div>
                    </motion.div>
                  );
                })}
              </motion.div>

              <motion.div {...fadeInUp} className="flex justify-between items-center gap-4">
                <Link
                  href="/websites"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-white shadow-md rounded-xl text-slate-600 hover:bg-slate-50 transition-all duration-300"
                >
                  <ArrowLeft className="h-4 w-4" />
                  Continue Shopping
                </Link>
                <button
                  onClick={() => setShowClearCartModal(true)}
                  className="inline-flex items-center gap-2 px-4 py-2 bg-white shadow-md rounded-xl text-red-600 hover:bg-red-50 transition-all duration-300"
                >
                  <Trash2 className="h-4 w-4" />
                  Clear Cart
                </button>
              </motion.div>
            </div>

            <div className="lg:col-span-1">
              <motion.div
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                className="sticky top-24"
              >
                <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-2 flex items-center gap-2">
                      <ShoppingCart className="h-5 w-5" />
                      Order Summary
                    </h3>
                    <p className="text-blue-100 text-sm">Review your order before checkout</p>
                  </div>

                  <div className="p-6 space-y-4">
                    <div className="flex justify-between items-center">
                      <span className="text-slate-600">Items ({itemCount})</span>
                      <span className="font-semibold text-slate-800">
                        ${total.toLocaleString()}
                      </span>
                    </div>

                    <div className="border-t border-slate-100 pt-4 flex justify-between items-center">
                      <span className="text-lg font-bold text-slate-800">Total</span>
                      <div className="text-right">
                        <div className="text-2xl font-bold text-blue-600">
                          ${total.toLocaleString()}
                        </div>
                        <p className="text-xs text-slate-500">No hidden fees</p>
                      </div>
                    </div>

                    <button
                      onClick={handleCheckout}
                      className="w-full flex items-center justify-center gap-2 bg-linear-to-r cursor-pointer from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white py-4 rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.02]"
                    >
                      <CreditCard className="h-5 w-5" />
                      Proceed to Checkout
                      <ArrowRight className="h-5 w-5" />
                    </button>

                    <div className="flex flex-wrap items-center justify-center gap-4 text-xs text-slate-500 pt-2">
                      <div className="flex items-center gap-1.5">
                        <Lock className="h-3 w-3 text-green-600" />
                        <span>Secure Payment</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <Shield className="h-3 w-3 text-green-600" />
                        <span>SSL Encrypted</span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <ThumbsUp className="h-3 w-3 text-green-600" />
                        <span>Money-back Guarantee</span>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="mt-6 bg-white rounded-2xl shadow-md p-6">
                  <div className="flex items-start gap-3">
                    <div className="p-2 bg-blue-100 rounded-xl">
                      <MessageCircle className="h-5 w-5 text-blue-600" />
                    </div>
                    <div>
                      <h4 className="font-semibold text-slate-800 mb-1">Need Help?</h4>
                      <p className="text-sm text-slate-600">
                        Have questions? Our support team is here to help 24/7.
                      </p>
                    </div>
                  </div>
                </div>
              </motion.div>
            </div>
          </div>
        )}
      </div>

      {/* ── Clear Cart Modal ── */}
      <AnimatePresence>
        {showClearCartModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setShowClearCartModal(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="bg-white rounded-2xl shadow-2xl max-w-md w-full"
              onClick={e => e.stopPropagation()}
            >
              <div className="p-6">
                <div className="flex items-center gap-3 mb-4">
                  <div className="p-2 bg-red-100 rounded-xl">
                    <AlertCircle className="h-6 w-6 text-red-600" />
                  </div>
                  <h3 className="text-xl font-bold text-slate-800">Clear Cart</h3>
                </div>

                <p className="text-slate-600 mb-6">
                  Are you sure you want to remove all items from your cart? This action cannot be
                  undone.
                </p>

                <div className="flex gap-3">
                  <button
                    onClick={() => setShowClearCartModal(false)}
                    className="flex-1 px-4 py-2 bg-slate-100 rounded-xl text-slate-700 hover:bg-slate-200 transition-colors"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleClearCart}
                    className="flex-1 px-4 py-2 bg-red-600 text-white rounded-xl hover:bg-red-700 transition-colors"
                  >
                    Yes, Clear Cart
                  </button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// Missing Package icon component
function Package(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
      <polyline points="3.29 7 12 12 20.71 7" />
      <line x1="12" y1="22" x2="12" y2="12" />
    </svg>
  );
}