import { useState, useEffect, useCallback, useRef } from "react";
import { flushSync } from "react-dom";
import { supabase } from "@/integrations/supabase/client";
import { ProductCard } from "@/components/chat/ProductCard";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Package, Smartphone, Laptop, Headphones, Watch, Camera, Home, ShoppingBag, MessageSquare, ChevronDown, Plus, Search, ImageIcon, LucideIcon, X, ShoppingCart, User, Headset, Gift, Star, Ticket, Sparkles } from "lucide-react";
import { toast } from "sonner";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ChatMessage, Message as ChatMessageType } from "@/components/chat/ChatMessage";
import { ChatInput } from "@/components/chat/ChatInput";
import { useConversations, type Message as DBMessage } from "@/hooks/useConversations";
import { TypingIndicator } from "@/components/chat/TypingIndicator";
import { useAuth } from "@/contexts/AuthContext";
import { AIAgent, AI_AGENTS } from "@/types/agents";
import { callCozeEdge } from "@/utils/cozeClient";

// ─── 访客 ID + 会话 ID 模块级变量（绕过 React 闭包）───
const GUEST_ID_KEY = 'qianjiang_guest_uuid';
let _guestIdMemoryFallback: string | null = null;
function makeUUID(): string {
  try { return crypto.randomUUID(); } catch { /* 非 HTTPS 环境 */ }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}
function getOrCreateGuestId(): string {
  try {
    const existing = localStorage.getItem(GUEST_ID_KEY);
    if (existing) return existing;
    const id = makeUUID();
    localStorage.setItem(GUEST_ID_KEY, id);
    return id;
  } catch {
    if (!_guestIdMemoryFallback) _guestIdMemoryFallback = makeUUID();
    return _guestIdMemoryFallback;
  }
}
let _activeConvId: string | null = null;
import { ProductDetailDialog } from "@/components/chat/ProductDetailDialog";
import { useCart } from "@/contexts/CartContext";
import { CartSidebar } from "@/components/cart/CartSidebar";
import { CheckoutDialog } from "@/components/cart/CheckoutDialog";
import { useNavigate } from "react-router-dom";
import { Header } from "@/components/layout/Header";
import shopHeroBanner from "@/assets/shop-hero-banner.jpg";

interface Product {
  id: string;
  name: string;
  price: number;
  stock_quantity: number;
  image_url?: string;
  description?: string;
  category?: string;
  is_active: boolean;
  is_hot?: boolean;
}

interface Category {
  id: string;
  name: string;
  icon: LucideIcon;
  display_order: number;
}

// Icon mapping for categories
const getCategoryIcon = (categoryName: string): LucideIcon => {
  const iconMap: Record<string, LucideIcon> = {
    "手机": Smartphone,
    "电脑": Laptop,
    "平板": Laptop,
    "耳机": Headphones,
    "音响": Headphones,
    "手表": Watch,
    "相机": Camera,
    "摄影": Camera,
    "家电": Home,
    "其他": ShoppingBag,
  };

  for (const [key, icon] of Object.entries(iconMap)) {
    if (categoryName.includes(key)) {
      return icon;
    }
  }
  return Package;
};

export default function ShopPage() {
  const { user } = useAuth();
  const { addItem } = useCart();
  const navigate = useNavigate();
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([
    { id: "all", name: "全部商品", icon: Package, display_order: 0 }
  ]);
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [isLoading, setIsLoading] = useState(true);
  const [showAI, setShowAI] = useState(true);
  
  // Search states
  const [searchQuery, setSearchQuery] = useState("");
  const [searchType, setSearchType] = useState("商品");
  
  // Product detail dialog states
  const [selectedProductId, setSelectedProductId] = useState<string | null>(null);
  const [showProductDetail, setShowProductDetail] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  
  // Chat states
  const [messages, setMessages] = useState<ChatMessageType[]>([]);
  const [isAiTyping, setIsAiTyping] = useState(false);
  const [currentAgent, setCurrentAgent] = useState<AIAgent>(AI_AGENTS.general);
  const scrollAreaRef = useRef<HTMLDivElement>(null);
  const floorsRef = useRef<HTMLDivElement>(null);

  const scrollToFloors = () => {
    floorsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const handleSearch = () => {
    if (searchQuery.trim()) {
      scrollToFloors();
    }
  };

  const handleHotKeyword = (keyword: string) => {
    setSearchQuery(keyword);
    setSelectedCategory("all");
    setTimeout(scrollToFloors, 50);
  };
  
  const {
    conversations: rawConversations,
    currentConversationId: activeConversationId,
    messages: dbMessages,
    setCurrentConversationId: setActiveConversationId,
    createConversation: createNewConversation,
    selectConversation,
    saveMessage,
    fetchConversations: loadConversations,
    fetchMessages: loadMessages
  } = useConversations();

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

  const fetchCategories = async () => {
    try {
      const { data, error } = await supabase
        .from("categories")
        .select("*")
        .eq("is_active", true)
        .order("display_order", { ascending: true });

      if (error) throw error;

      const dbCategories: Category[] = (data || []).map(cat => ({
        id: cat.id,
        name: cat.name,
        icon: getCategoryIcon(cat.name),
        display_order: cat.display_order
      }));

      setCategories([
        { id: "all", name: "全部商品", icon: Package, display_order: 0 },
        ...dbCategories
      ]);
    } catch (error) {
      console.error("Error fetching categories:", error);
      toast.error("加载分类失败");
    }
  };

  // Initialize or load existing conversation
  const initializeConversation = async () => {
    const conversations = await loadConversations();
    
    // If there's no active conversation, select the most recent one
    if (!activeConversationId && conversations && conversations.length > 0) {
      const mostRecent = conversations[0];
      await selectConversation(mostRecent.id);
    } else if (!activeConversationId && (!conversations || conversations.length === 0)) {
      // Create a new conversation only if none exist
      await handleNewConversation();
    }
  };

  // Handle creating new conversation
  const handleNewConversation = async () => {
    const newConv = await createNewConversation('商城对话');
    if (newConv) {
      _activeConvId = newConv.id;
      setActiveConversationId(newConv.id);
      
      // Add welcome message
      const welcomeMessage: ChatMessageType = {
        id: `welcome_${Date.now()}`,
        content: "您好！我是智能购物助手，可以帮您推荐商品、查询订单等。请问有什么需要帮助的吗？",
        sender: "ai",
        timestamp: new Date().toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit'
        }),
        type: "text",
        agent: AI_AGENTS.general
      };
      
      setMessages([welcomeMessage]);
      
      await saveMessage({
        content: welcomeMessage.content,
        sender_type: welcomeMessage.sender,
        message_type: welcomeMessage.type as DBMessage['message_type'],
        metadata: welcomeMessage.metadata
      }, newConv.id);
      
      toast.success('已创建新对话');
    }
  };

  // Handle conversation selection
  const handleSelectConversation = async (conversationId: string) => {
    await selectConversation(conversationId);
    toast.success('已切换对话');
  };

  // Convert DB messages to Chat messages
  useEffect(() => {
    const convertedMessages: ChatMessageType[] = dbMessages.map(msg => ({
      id: msg.id,
      content: msg.content,
      sender: msg.sender_type as 'user' | 'ai',
      timestamp: new Date(msg.created_at).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      }),
      type: msg.message_type as ChatMessageType['type'],
      metadata: msg.metadata as any || {}
    }));
    setMessages(convertedMessages);
  }, [dbMessages]);
  
  // Auto scroll to bottom
  useEffect(() => {
    if (scrollAreaRef.current) {
      const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
      if (scrollContainer) {
        scrollContainer.scrollTop = scrollContainer.scrollHeight;
      }
    }
  }, [messages, isAiTyping]);

  const fetchProducts = async (): Promise<Product[]> => {
    try {
      setIsLoading(true);
      const { data, error } = await supabase
        .from("products")
        .select("*")
        .eq("is_active", true)
        .order("created_at", { ascending: false });

      if (error) throw error;
      setProducts(data || []);
      return data || [];
    } catch (error) {
      console.error("Error fetching products:", error);
      toast.error("加载商品失败");
      return [];
    } finally {
      setIsLoading(false);
    }
  };

  // Group products by category for floor layout
  const productsByCategory = categories
    .filter(cat => cat.id !== "all")
    .filter(cat => selectedCategory === "all" || cat.id === selectedCategory)
    .map(cat => {
      const categoryProducts = products.filter(p => {
        const matchesCategory = p.category === cat.id || p.category === cat.name;
        const matchesSearch = !searchQuery || 
          p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          p.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
          p.category?.toLowerCase().includes(searchQuery.toLowerCase());
        return matchesCategory && matchesSearch;
      });
      return {
        category: cat,
        products: categoryProducts
      };
    })
    .filter(floor => floor.products.length > 0);

  // Recommended products (first 8 active products)
  const recommendedProducts = products
    .filter(p => {
      const matchesSearch = !searchQuery || 
        p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        p.description?.toLowerCase().includes(searchQuery.toLowerCase());
      return matchesSearch && p.is_active;
    })
    .slice(0, 8);

  // Handle product detail view
  const handleViewProductDetails = (productId: string) => {
    setSelectedProductId(productId);
    setShowProductDetail(true);
  };

  // Handle add to cart
  const handleAddToCart = (product: any) => {
    addItem(product);
    toast.success(`${product.name} 已加入购物车`);
  };

  // AI response handler
  const simulateAIResponse = useCallback(async (userMessage: string) => {
    setIsAiTyping(true);
    const activeConvId = _activeConvId;
    const currentUserId = user?.id || getOrCreateGuestId();
    console.log('🔍 [Shop AI] simulateAIResponse start — convId:', activeConvId, 'userId:', currentUserId);
    const streamMsgId = `ai_${Date.now()}`;

    // 先插入一个占位消息，后续流式更新
    const placeholderMessage: ChatMessageType = {
      id: streamMsgId,
      content: '',
      sender: "ai",
      timestamp: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      }),
      type: "text",
      agent: currentAgent,
    };
    setMessages(prev => [...prev, placeholderMessage]);

    try {
      let currentProducts = products;
      if (currentProducts.length === 0) {
        currentProducts = await fetchProducts();
        console.log('🔍 [Shop AI] fetchProducts retry returned:', currentProducts.length, 'products');
      }

      // 商品目录可以为空，AI Edge Function 使用 service_role 自行查询数据库
      const catalog = currentProducts.map(p => ({
        id: p.id,
        name: p.name,
        price: p.price,
        stock_quantity: p.stock_quantity,
        category: p.category,
        description: p.description
      }));

      // ─── 流式接收 AI 回复文字 ───
      let fullContent = '';
      console.log('🔍 [Shop AI] About to call callCozeEdge — catalog size:', catalog.length);
      const { data: intentCard } = await callCozeEdge({
        message: userMessage,
        userId: currentUserId,
        localConversationId: activeConvId,
        product: currentProducts.length > 0 ? {
          id: currentProducts[0].id,
          title: currentProducts[0].name,
          description: currentProducts[0].description || '',
          price: Number(currentProducts[0].price)
        } : undefined,
        catalog,
        onText: (text: string) => {
          fullContent += text;
          flushSync(() => {
            setMessages(prev => prev.map(msg =>
              msg.id === streamMsgId
                ? { ...msg, content: fullContent }
                : msg
            ));
          });
        }
      });

      if (!intentCard) throw new Error('系统繁忙，请稍后再试');

      // 清洗 JSON 代码块，避免裸露协议数据出现在正文
      let aiContent = fullContent
        .replace(/```(?:json)?\s*\{[\s\S]*?"(?:picks|intent)"[\s\S]*?\}\s*```/gi, '')
        .replace(/\{\s*"(?:picks|intent)"\s*:[\s\S]*?\}\s*$/g, '')
        .trim();

      if (!aiContent) {
        aiContent = intentCard.title || '收到您的消息';
        if (intentCard.highlights && intentCard.highlights.length > 0) {
          aiContent += '\n\n' + intentCard.highlights.map(h => `• ${h}`).join('\n');
        }
      }

      if (intentCard.picks && intentCard.picks.length > 0) {
        aiContent += '\n\n为您推荐了 ' + intentCard.picks.length + ' 个商品';
      }

      let messageType: ChatMessageType['type'] = "text";
      let responseMetadata: ChatMessageType['metadata'] = {};

      // 优先使用 AI 返回的 picks 渲染商品卡片（与 /chat 页面一致）
      const pickedProducts = (intentCard.picks || [])
        .map(pick => currentProducts.find(p => p.id === pick.product_id))
        .filter((p): p is typeof currentProducts[number] => Boolean(p));

      if (pickedProducts.length > 0) {
        messageType = "products";
        responseMetadata = {
          productsInfo: pickedProducts.map(product => ({
            id: product.id,
            name: product.name,
            price: product.price,
            image: product.image_url || "",
            status: product.stock_quantity > 0 ? "现货充足" : "缺货",
            category: product.category || "未分类",
            stock_quantity: product.stock_quantity
          }))
        };
      }

      // 更新占位消息为最终内容 + 类型 + 元数据
      setMessages(prev => prev.map(msg =>
        msg.id === streamMsgId
          ? { ...msg, content: aiContent, type: messageType, metadata: responseMetadata }
          : msg
      ));

      if (activeConvId) {
        await saveMessage({
          content: aiContent,
          sender_type: "ai",
          message_type: messageType as DBMessage['message_type'],
          metadata: responseMetadata
        }, activeConvId);
      }
    } catch (error) {
      console.error('AI回复失败:', error);
      // 把占位消息替换为错误消息
      setMessages(prev => prev.map(msg =>
        msg.id === streamMsgId
          ? { ...msg, content: '抱歉，遇到了技术问题，请稍后再试。' }
          : msg
      ));
    } finally {
      setIsAiTyping(false);
    }
  }, [currentAgent, products, activeConversationId, saveMessage, user]);

  const handleSendMessage = useCallback(async (content: string) => {
    // 防止并发流式调用（如快速连点建议按钮）
    if (isAiTyping) return;

    // 兜底：确保有活跃对话
    let currentConvId = activeConversationId;
    if (!currentConvId) {
      await handleNewConversation();
      currentConvId = _activeConvId;
    } else {
      _activeConvId = currentConvId;
    }

    const userMessage: ChatMessageType = {
      id: `user_${Date.now()}`,
      content,
      sender: "user",
      timestamp: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      }),
      type: "text"
    };

    setMessages(prev => [...prev, userMessage]);

    if (currentConvId) {
      await saveMessage({
        content: userMessage.content,
        sender_type: userMessage.sender,
        message_type: userMessage.type as DBMessage['message_type'],
        metadata: userMessage.metadata
      }, currentConvId);
    }

    await simulateAIResponse(content);
  }, [simulateAIResponse, activeConversationId, saveMessage, isAiTyping]);

  return (
    <div className="min-h-screen bg-background">
      {/* Header 已移除：右侧悬浮快捷栏已提供购物车/我的/客服/反馈入口 */}
      {/* Main Content - Products Grid */}
      <div className="flex-1 overflow-auto">
        <div className="container mx-auto px-6 pt-8 pb-6">
          {/* Search Bar - Rectangular, primary outline */}
          <div className="mb-6">
            <div className="flex items-stretch h-11 rounded-lg border-2 border-primary bg-card overflow-hidden">
              {/* Search Type Dropdown */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <button className="flex items-center gap-1 px-4 text-sm text-foreground hover:bg-muted/50 transition-colors">
                    <span>{searchType}</span>
                    <ChevronDown className="h-3.5 w-3.5 opacity-60" />
                  </button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  <DropdownMenuItem onClick={() => setSearchType("商品")}>商品</DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setSearchType("店铺")}>店铺</DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>

              {/* Search Input */}
              <input
                placeholder="搜索商品名称、品牌、分类..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="flex-1 px-2 bg-transparent outline-none text-sm placeholder:text-muted-foreground"
                onKeyPress={(e) => {
                  if (e.key === 'Enter') handleSearch();
                }}
              />

              {/* Image Search */}
              <button
                className="px-3 text-muted-foreground hover:text-foreground transition-colors"
                onClick={() => toast.info("图片搜索功能开发中")}
                aria-label="图片搜索"
              >
                <Camera className="h-5 w-5" />
              </button>

              {/* Search Button */}
              <button
                className="px-8 bg-primary hover:bg-primary-hover text-primary-foreground text-sm font-medium flex items-center gap-1.5 transition-colors"
                onClick={handleSearch}
              >
                搜索
              </button>
            </div>

            {/* Hot Products - text links, no borders */}
            {products.filter(p => p.is_hot).length > 0 && (
              <div className="flex items-center gap-x-4 gap-y-1 flex-wrap mt-3 px-2">
                <span className="text-xs text-muted-foreground">热门</span>
                {products.filter(p => p.is_hot).slice(0, 6).map((product) => (
                  <button
                    key={product.id}
                    className="text-xs text-muted-foreground hover:text-primary transition-colors"
                    onClick={() => handleViewProductDetails(product.id)}
                  >
                    {product.name}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Floor Layout - JD Style */}
          {isLoading ? (
            <div className="space-y-8">
              {[...Array(3)].map((_, i) => (
                <div key={i} className="bg-card rounded-lg p-6">
                  <div className="h-8 w-48 bg-muted animate-pulse rounded mb-4" />
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    {[...Array(4)].map((_, j) => (
                      <div key={j} className="h-80 bg-muted animate-pulse rounded-lg" />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="space-y-8">
              {/* Hero + Sidebar Layout (natural height, no inner scrollbar) */}
              <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-6 items-stretch">
                {/* Category Sidebar - grows naturally to match banner */}
                <aside className="bg-card rounded-xl shadow-sm border border-border overflow-hidden flex flex-col">
                  <nav className="flex-1 p-2">
                    {categories.map((cat) => {
                      const isActive = selectedCategory === cat.id;
                      return (
                        <button
                          key={cat.id}
                          onClick={() => {
                            setSelectedCategory(cat.id);
                            setTimeout(scrollToFloors, 50);
                          }}
                          className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-md text-sm text-left transition-all ${
                            isActive
                              ? "bg-primary text-primary-foreground shadow-sm"
                              : "text-foreground hover:bg-muted"
                          }`}
                        >
                          <cat.icon className="h-4 w-4 flex-shrink-0" />
                          <span className="truncate">{cat.name}</span>
                        </button>
                      );
                    })}
                  </nav>
                </aside>

                {/* Hero Banner */}
                <div className="bg-card rounded-xl shadow-sm border border-border overflow-hidden">
                  <div className="relative h-full min-h-[320px] overflow-hidden">
                    <img
                      src={shopHeroBanner}
                      alt="精选商品"
                      className="absolute inset-0 w-full h-full object-cover"
                      width={896}
                      height={640}
                    />
                    <div className="absolute inset-0 bg-gradient-to-r from-background/95 via-background/70 to-transparent" />
                    <div className="relative h-full flex items-center pl-12 pr-8 py-10">
                      <div className="space-y-5 max-w-md">
                        <h1 className="text-5xl font-bold tracking-tight text-foreground">
                          欢迎光临
                        </h1>
                        <p className="text-lg text-muted-foreground">
                          精选优质商品，为您提供专业的采购体验
                        </p>
                        <div className="flex gap-3 pt-2">
                          <Button
                            size="lg"
                            className="px-8"
                            onClick={() => {
                              setSelectedCategory("all");
                              setTimeout(scrollToFloors, 50);
                            }}
                          >
                            立即选购
                          </Button>
                          <Button
                            size="lg"
                            variant="outline"
                            className="px-8"
                            onClick={() => setShowAI(true)}
                          >
                            咨询客服
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Category Floors */}
              <div ref={floorsRef} className="scroll-mt-6" />
              {productsByCategory.length === 0 && recommendedProducts.length === 0 ? (
                <div className="text-center py-20 text-muted-foreground bg-card rounded-xl border border-border">
                  <Package className="h-16 w-16 mx-auto mb-4 opacity-50" />
                  <p className="text-lg">暂无商品</p>
                </div>
              ) : (
                productsByCategory.map((floor, index) => (
                  <section key={floor.category.id} className="space-y-4">
                    <div className="flex items-center justify-between px-1">
                      <div className="flex items-center gap-3">
                        <div className="h-9 w-9 rounded-lg bg-primary/10 text-primary flex items-center justify-center">
                          <floor.category.icon className="h-5 w-5" />
                        </div>
                        <h2 className="text-lg font-semibold text-foreground">{floor.category.name}</h2>
                        <span className="text-xs text-muted-foreground">{floor.products.length} 件商品</span>
                      </div>
                      {floor.products.length > 8 && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setSelectedCategory(floor.category.id)}
                          className="text-muted-foreground hover:text-foreground"
                        >
                          查看更多 →
                        </Button>
                      )}
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                      {floor.products.slice(0, 8).map((product) => (
                        <ProductCard
                          key={product.id}
                          product={product}
                          onViewDetails={handleViewProductDetails}
                          onAddToCart={handleAddToCart}
                        />
                      ))}
                    </div>
                  </section>
                ))
              )}
            </div>
          )}
        </div>
      </div>

      {/* Floating AI Chat Window */}
      {showAI && (
        <div className="fixed right-16 bottom-24 w-[340px] h-[calc(100vh-14rem)] bg-background border border-border rounded-xl shadow-xl flex flex-col z-50 overflow-hidden">
          {/* Header */}
          <div className="px-4 py-3 border-b border-border bg-background">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className="h-8 w-8 rounded-full bg-primary flex items-center justify-center">
                  <MessageSquare className="h-4 w-4 text-primary-foreground" />
                </div>
                <div>
                  <h2 className="text-sm font-semibold">千匠智能助手</h2>
                  <p className="text-xs text-muted-foreground">智能购物，千匠相伴</p>
                </div>
              </div>
              <div className="flex items-center gap-1">
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                    >
                      <span className="text-lg">⋯</span>
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="w-48 bg-background z-[60]">
                    <DropdownMenuLabel className="text-xs">历史对话记录</DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    {rawConversations.length > 0 ? (
                      rawConversations.map((conv) => (
                        <DropdownMenuItem
                          key={conv.id}
                          onClick={() => handleSelectConversation(conv.id)}
                          className={`cursor-pointer ${activeConversationId === conv.id ? 'bg-accent' : ''}`}
                        >
                          <div className="flex flex-col gap-0.5 w-full">
                            <span className="text-xs font-medium truncate">{conv.title}</span>
                            <span className="text-[10px] text-muted-foreground">
                              {new Date(conv.updated_at).toLocaleString('zh-CN')}
                            </span>
                          </div>
                        </DropdownMenuItem>
                      ))
                    ) : (
                      <DropdownMenuItem disabled>
                        <span className="text-xs text-muted-foreground">暂无历史对话</span>
                      </DropdownMenuItem>
                    )}
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleNewConversation}>
                      <Plus className="h-3 w-3 mr-2" />
                      <span className="text-xs">新建对话</span>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => setShowAI(false)}
                  className="h-8 w-8"
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>
          
          {/* Messages Area */}
          <ScrollArea className="flex-1 bg-background" ref={scrollAreaRef}>
            <div className="p-3 space-y-3">
              {messages.length === 0 ? (
                <div className="py-6">
                  <div className="text-lg font-semibold mb-2">Hi!</div>
                  <p className="text-xs text-muted-foreground leading-relaxed mb-4">
                    我是千匠智能助手，你的专属 AI 购物助手。我可以为你解答各种购物问题，提供实用信息。有问题随时问我~
                  </p>
                  <div className="space-y-2">
                    <div className="text-xs text-muted-foreground mb-2">内容由AI生成</div>
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="w-full justify-start text-xs h-8 hover:bg-accent"
                      onClick={() => handleSendMessage("软白营养套餐")}
                    >
                      软白营养套餐
                    </Button>
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="w-full justify-start text-xs h-8 hover:bg-accent"
                      onClick={() => handleSendMessage("办公室必备好物")}
                    >
                      办公室必备好物
                    </Button>
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="w-full justify-start text-xs h-8 hover:bg-accent"
                      onClick={() => handleSendMessage("送长辈礼物")}
                    >
                      送长辈礼物
                    </Button>
                  </div>
                </div>
              ) : (
                messages.map((message) => (
                  <ChatMessage 
                    key={message.id} 
                    message={message}
                    compact={true}
                    onViewDetails={handleViewProductDetails}
                    onAddToCart={handleAddToCart}
                    onViewOrderDetails={() => {}}
                    onViewAfterSalesDetails={() => {}}
                  />
                ))
              )}
              {isAiTyping && <TypingIndicator />}
            </div>
          </ScrollArea>
          
          {/* Input Area */}
          <ChatInput onSendMessage={handleSendMessage} disabled={isAiTyping} />
        </div>
      )}

      {/* Floating AI Toggle Button */}
      {!showAI && (
        <Button
          className="fixed right-24 bottom-6 rounded-full h-14 w-14 shadow-lg hover:shadow-xl transition-all hover:scale-105"
          onClick={() => setShowAI(true)}
        >
          <MessageSquare className="h-7 w-7" />
        </Button>
      )}

      {/* Hidden Cart Trigger */}
      <CartSidebar>
        <button data-cart-trigger className="hidden" aria-label="购物车触发器" />
      </CartSidebar>

      {/* Right Side Quick Access Buttons - JD Style */}
      <div className="fixed right-0 top-1/2 -translate-y-1/2 z-[60] flex flex-col gap-0 bg-background border-l border-t border-b border-border rounded-l-lg shadow-lg overflow-hidden">
        <Button
          variant="ghost"
          size="sm"
          className="h-14 w-14 rounded-none flex flex-col items-center justify-center gap-1 hover:bg-accent border-b border-border"
          onClick={() => {
            const cartButton = document.querySelector('[data-cart-trigger]');
            if (cartButton instanceof HTMLElement) {
              cartButton.click();
            }
          }}
        >
          <ShoppingCart className="h-5 w-5" />
          <span className="text-[10px]">购物车</span>
        </Button>
        
        <Button
          variant="ghost"
          size="sm"
          className="h-14 w-14 rounded-none flex flex-col items-center justify-center gap-1 hover:bg-accent border-b border-border"
          onClick={() => navigate('/profile')}
        >
          <User className="h-5 w-5" />
          <span className="text-[10px]">我的</span>
        </Button>
        
        <Button
          variant="ghost"
          size="sm"
          className="h-14 w-14 rounded-none flex flex-col items-center justify-center gap-1 hover:bg-accent border-b border-border"
          onClick={() => setShowAI(true)}
        >
          <Headset className="h-5 w-5" />
          <span className="text-[10px]">客服</span>
        </Button>
        
        <Button
          variant="ghost"
          size="sm"
          className="h-14 w-14 rounded-none flex flex-col items-center justify-center gap-1 hover:bg-accent border-b border-border"
          onClick={() => toast.info("反馈功能开发中")}
        >
          <Gift className="h-5 w-5" />
          <span className="text-[10px]">反馈</span>
        </Button>
        
      </div>

      {/* Product Detail Dialog */}
      <ProductDetailDialog
        open={showProductDetail}
        onOpenChange={setShowProductDetail}
        productId={selectedProductId}
        onBuyNow={() => setCheckoutOpen(true)}
      />

      <CheckoutDialog 
        open={checkoutOpen} 
        onOpenChange={setCheckoutOpen} 
      />
    </div>
  );
}
