/**
 * ⚠️ AI 开发边界警告 ⚠️
 * 
 * 此文件为前端代码，AI 仅负责维护前端相关内容
 * 
 * 严格禁止 AI 修改：
 * - supabase/functions/* (Edge Functions)
 * - supabase/config.toml
 * - 数据库 migrations
 * 
 * 如发现需要后端改动：
 * 1. 立即停止修改代码
 * 2. 提供诊断报告和建议
 * 3. 等待后端 AI 或人工处理
 */

import { useState, useRef, useEffect, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { useCart } from '@/contexts/CartContext';
import { useConversations, type Message, type Conversation } from '@/hooks/useConversations';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Input } from '@/components/ui/input';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { MobileProductCard } from '@/components/mobile/MobileProductCard';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
import { callCozeEdge } from '@/utils/cozeClient';
import { 
  MessageCircle, 
  Send,
  Menu,
  X,
  Star,
  ShoppingBag,
  ChevronDown,
  Loader2,
  Plus,
  History,
  MoreHorizontal,
  Edit,
  Trash2,
  Package
} from 'lucide-react';

// Import types from the hook instead of defining them here

const MobilePage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user } = useAuth();
  const { items, addItem } = useCart();

  const handleAddToCart = (productId: string) => {
    const allProducts = [
      ...products,
      ...aiRecommendations.map((r: any) => r.product),
      ...messages.flatMap((m: any) => m.metadata?.productsInfo || m.metadata?.products || []),
    ];
    const p = allProducts.find((x: any) => x?.id === productId);
    if (!p) {
      toast.error('未找到商品信息');
      return;
    }
    addItem({
      id: p.id,
      name: p.name,
      price: p.price,
      image_url: p.image || p.image_url,
      category: p.category,
      stock_quantity: p.stock_quantity ?? 99,
    });
    toast.success(`${p.name} 已加入购物车`);
  };
  const [message, setMessage] = useState('');
  const [showSuggestions, setShowSuggestions] = useState(true);
  const [products, setProducts] = useState<any[]>([]);
  const [orders, setOrders] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [aiRecommendations, setAiRecommendations] = useState<any[]>([]);
  const [isGeneratingRecommendations, setIsGeneratingRecommendations] = useState(false);
  const [isAiTyping, setIsAiTyping] = useState(false);
  const [showConversations, setShowConversations] = useState(false);
  const [editingConversationId, setEditingConversationId] = useState<string | null>(null);
  const [editingTitle, setEditingTitle] = useState('');
  
  // 使用共享的对话管理hook
  const {
    conversations,
    currentConversationId,
    messages,
    setMessages,
    setCurrentConversationId,
    fetchConversations,
    fetchMessages,
    createConversation,
    updateConversation,
    deleteConversation,
    selectConversation,
    saveMessage
  } = useConversations();
  const inputRef = useRef<HTMLInputElement>(null);
  const isSendingRef = useRef(false);

  // 聊天建议
  const chatSuggestions = [
    "入秋外套怎么选？",
    "适合开学的",
    "秋日露营装备",
    "办公室必备好物"
  ];

  // 获取产品数据
  const fetchProducts = useCallback(async () => {
    try {
      const { data, error } = await supabase
        .from('products')
        .select('id, name, price, image_url, category, stock_quantity, description')
        .eq('is_active', true)
        .limit(6)
        .order('created_at', { ascending: false });
      
      if (error) throw error;
      console.log('移动端获取产品数据:', data);
      setProducts(data || []);
      return data || []; // 返回数据
    } catch (error) {
      console.error('获取产品数据失败:', error);
      return [];
    }
  }, []);

  // 获取订单数据
  const fetchOrders = useCallback(async () => {
    if (!user) return;
    
    try {
      const { data, error } = await supabase
        .from('orders')
        .select(`
          *,
          order_items (
            quantity,
            unit_price,
            products (name, image_url)
          )
        `)
        .eq('user_id', user.id)
        .limit(3)
        .order('created_at', { ascending: false });
      
      if (error) throw error;
      setOrders(data || []);
    } catch (error) {
      console.error('获取订单数据失败:', error);
    }
  }, [user]);

  // 生成AI推荐
  const generateAIRecommendations = useCallback(async () => {
    if (products.length === 0) return;
    
    setIsGeneratingRecommendations(true);
    try {
      // 模拟AI推荐逻辑，基于实际产品数据
      const recommendations = products.slice(0, 2).map((product, index) => ({
        id: index + 1,
        category: index === 0 ? `${product.category}精选` : `热门${product.category}`,
        description: index === 0 
          ? `${product.name}，高品质材质，适合多种场合穿搭` 
          : `${product.name}，性价比超高，用户好评如潮`,
        product: {
          id: product.id,
          name: product.name,
          price: product.price,
          rating: 100,
          image: product.image_url || "🛍️",
          reviews: `${product.stock_quantity}+库存`,
          stock_quantity: product.stock_quantity
        }
      }));
      
      setAiRecommendations(recommendations);
    } catch (error) {
      console.error('生成AI推荐失败:', error);
    } finally {
      setIsGeneratingRecommendations(false);
    }
  }, [products]);

  // 选择对话
  const handleConversationSelect = useCallback(async (conversationId: string) => {
    await selectConversation(conversationId);
    setShowConversations(false);
    setShowSuggestions(false);
  }, [selectConversation]);

  // 重命名对话
  const handleRenameConversation = useCallback(async (conversationId: string, newTitle: string) => {
    if (!newTitle.trim()) return;
    
    const success = await updateConversation(conversationId, { title: newTitle.trim() });
    if (success) {
      setEditingConversationId(null);
      setEditingTitle('');
      toast.success('对话重命名成功');
    } else {
      toast.error('重命名对话失败');
    }
  }, [updateConversation]);

  // 删除对话
  const handleDeleteConversation = useCallback(async (conversationId: string) => {
    const success = await deleteConversation(conversationId);
    if (success && currentConversationId === conversationId) {
      setShowSuggestions(true);
    }
  }, [deleteConversation, currentConversationId]);

  // 开始编辑对话标题
  const startEditingConversation = (conversationId: string, currentTitle: string) => {
    setEditingConversationId(conversationId);
    setEditingTitle(currentTitle);
  };

  // 取消编辑
  const cancelEditing = () => {
    setEditingConversationId(null);
    setEditingTitle('');
  };

  // 获取对话图标
  const getConversationIcon = () => {
    return <Package className="h-4 w-4" />;
  };

  // 初始化数据
  useEffect(() => {
    const initData = async () => {
      setIsLoading(true);
      await Promise.all([
        fetchProducts(),
        fetchOrders(),
        fetchConversations()
      ]);
      setIsLoading(false);
    };
    
    initData();
  }, [fetchProducts, fetchOrders, fetchConversations]);

  // 如果没有当前对话且有用户，创建新对话
  useEffect(() => {
    if (user && !currentConversationId && conversations.length === 0 && !isLoading) {
      createConversation('New Conversation');
    }
  }, [user, currentConversationId, conversations.length, isLoading, createConversation]);

  // 当产品数据加载完成后生成推荐
  useEffect(() => {
    if (products.length > 0) {
      generateAIRecommendations();
    }
  }, [products, generateAIRecommendations]);

  // 处理来自其他页面的初始消息
  useEffect(() => {
    if (location.state?.initialMessage) {
      // 延迟调用，确保组件完全初始化
      const timer = setTimeout(() => {
      handleAIResponse(location.state.initialMessage);
      // 清除 state 避免重复调用
        window.history.replaceState({}, '', window.location.pathname);
      }, 100);
      
      return () => clearTimeout(timer);
    }
  }, [location.state?.initialMessage]);

  // 处理AI回复
  const handleAIResponse = useCallback(async (userMessage: string) => {
    if (!userMessage.trim()) return;

    // 确保有对话ID
    let conversationId = currentConversationId;
    if (!conversationId) {
      const newConv = await createConversation('New Conversation');
      if (!newConv) return;
      conversationId = newConv.id;
      setShowSuggestions(true);
    }

    // ✅ 直接从数据库获取最新的 Dify 对话ID，避免本地 state 延迟问题
    let difyConversationId = '';
    if (conversationId) {
      const { data: convData } = await supabase
        .from('conversations')
        .select('dify_conversation_id')
        .eq('id', conversationId)
        .single();
      difyConversationId = convData?.dify_conversation_id || '';
    }
    
    console.log('🔍 前端对话上下文检查:', {
      conversationId,
      difyConversationId: difyConversationId || '(new conversation)',
      source: 'database'
    });

    // 保存用户消息到数据库（saveMessage会自动添加到messages state）
    setIsAiTyping(true);
    await saveMessage({
      content: userMessage,
      sender_type: 'user',
      message_type: 'text'
    }, conversationId);

    try {
      // 确保产品数据已加载
      let currentProducts = products;
      if (currentProducts.length === 0) {
        console.log('产品数据未加载，立即加载...');
        currentProducts = await fetchProducts();
      }
      
      // 准备产品目录数据
      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
      }));

      const firstProduct = currentProducts[0];

      console.log('📤 调用 dify-chat (方案 A - 移动端)');
      console.log('- 用户消息:', userMessage);
      console.log('- 商品数量:', currentProducts.length);

      // 使用统一客户端调用
      const { data: difyResponse, traceId, status, error: callError } = await callCozeEdge({
        message: userMessage,
        userId: user?.id || 'anonymous',
        conversationId: difyConversationId,  // ✅ 传递对话ID
        product: firstProduct ? {
          id: firstProduct.id,
          title: firstProduct.name,
          description: firstProduct.description || '',
          price: Number(firstProduct.price)
        } : undefined,
        catalog
      });

      console.log('📥 响应结果');
      console.log('- trace_id:', traceId);
      console.log('- status:', status);
      console.log('- catalog_count:', difyResponse?.meta?.catalog_count || 0);
      console.log('- picks详情:', difyResponse?.picks);
      console.log('- picks数量:', difyResponse?.picks?.length || 0);

      if (callError || !difyResponse) {
        console.error('Dify API调用失败:', callError);
        throw new Error(callError || `系统繁忙，请稍后再试（追踪码：${traceId}）`);
      }

      // ✅ 保存 Dify 返回的 conversation_id 到数据库
      // 重要：无论是新对话还是对话被重置，都要更新数据库
      const wasReset = (difyResponse as any).conversation_was_reset;
      const shouldUpdateDifyId = difyResponse.conversation_id && conversationId && 
        (wasReset || difyConversationId !== difyResponse.conversation_id);
      
      if (shouldUpdateDifyId) {
        console.log('💾 保存/更新 Dify 会话ID:', {
          old_dify_id: difyConversationId || '(none)',
          new_dify_id: difyResponse.conversation_id,
          was_reset: wasReset,
          conv_id: conversationId
        });
        
        // 直接用 supabase 更新，确保立即生效
        const { error: updateError } = await supabase
          .from('conversations')
          .update({ 
            dify_conversation_id: difyResponse.conversation_id,
            updated_at: new Date().toISOString()
          })
          .eq('id', conversationId);
        
        if (updateError) {
          console.error('❌ 保存 Dify 会话ID 失败:', updateError);
        } else {
          console.log('✅ Dify 会话ID 已更新');
        }
      }

      // UI 仅用合同字段渲染（忽略 answer/content 字符串）
      let aiContent = difyResponse.title || (difyResponse as any).answer || '收到您的消息';
      
      // 如果返回内容太简短，提供更好的回复
      if (aiContent.length < 10 && userMessage.toLowerCase().includes('商品')) {
        aiContent = '我为您推荐以下商品，这些都是目前的热门产品，库存充足，欢迎选购：';
      }

      // ✅ 使用 Dify 返回的结构化数据判断意图
      const difyIntent = difyResponse.intent || 'GENERAL';
      
      // ✅ 详细调试：打印完整的difyResponse对象来排查数据丢失问题
      console.log('🔍🔍🔍 [DEBUG] 完整difyResponse对象:', JSON.stringify(difyResponse, null, 2));
      console.log('🔍 [DEBUG] difyResponse.highlights:', difyResponse.highlights);
      console.log('🔍 [DEBUG] difyResponse.comparison:', (difyResponse as any).comparison);
      
      // ✅ 从difyResponse直接获取highlights（它是DifyResponse接口的一部分）
      const highlightsArray: string[] = difyResponse.highlights || [];
      const hasComparison = !!(difyResponse as any).comparison;
      const comparisonText = (difyResponse as any).comparison || '';
      
      // 判断是否是产品/比较相关的意图
      const intentStr = difyIntent as string;
      const isProductIntent = intentStr === 'SHOPPING' || 
        intentStr === 'COMPARE' || 
        intentStr === 'COMPARE_PRODUCTS' ||
        (difyResponse.picks && difyResponse.picks.length > 0);
      
      console.log('📊 Dify Intent:', difyIntent);
      console.log('📊 Dify返回comparison:', hasComparison);
      console.log('📊 comparison内容:', comparisonText || '(none)');
      console.log('📊 highlights数组:', highlightsArray);
      console.log('📊 highlights数量:', highlightsArray.length);
      console.log('📊 是否产品/比较意图:', isProductIntent);

      let messageType: Message['message_type'] = 'text';
      let aiProducts = [];
      let metadata: any = null;

      if (isProductIntent) {
        messageType = 'products';
        
        // ✅ 如果Dify返回了picks推荐，从数据库直接查询这些产品
        let filteredProducts: any[] = [];
        
        if (difyResponse.picks && difyResponse.picks.length > 0) {
          const pickedIds = difyResponse.picks.map((p: any) => p.product_id);
          console.log('📌 Dify推荐的产品ID:', pickedIds, '数量:', pickedIds.length);
          
          // ✅ 直接从数据库查询Dify推荐的产品，而不是只在本地匹配
          const { data: pickedProducts, error: fetchError } = await supabase
            .from('products')
            .select('id, name, price, image_url, category, stock_quantity, description')
            .in('id', pickedIds);
          
          if (fetchError) {
            console.error('❌ 查询推荐产品失败:', fetchError);
            filteredProducts = products.slice(0, 3);
          } else if (pickedProducts && pickedProducts.length > 0) {
            console.log('📦 数据库返回产品数量:', pickedProducts.length, '产品ID:', pickedProducts.map(p => p.id));
            
            // 按照Dify返回的顺序排序，并记录缺失的ID
            const foundProducts: any[] = [];
            const missingIds: string[] = [];
            
            pickedIds.forEach((id: string) => {
              const found = pickedProducts.find((p: any) => p.id === id);
              if (found) {
                foundProducts.push(found);
              } else {
                missingIds.push(id);
              }
            });
            
            if (missingIds.length > 0) {
              console.warn('⚠️ 以下产品ID在数据库中未找到:', missingIds);
            }
            
            filteredProducts = foundProducts;
            console.log('✅ 最终显示产品数量:', filteredProducts.length, '产品:', filteredProducts.map(p => ({ id: p.id, name: p.name })));
          } else {
            console.log('⚠️ 数据库中未找到推荐的产品，使用本地产品');
            filteredProducts = products.slice(0, 3);
          }
        } else {
          console.log('⚠️ 没有picks数据，显示前3个产品');
          filteredProducts = products.slice(0, 3);
        }
        
        aiProducts = filteredProducts.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
        }));
        
        // ✅ 统一使用 productsInfo 字段名，并添加 comparison 和 highlights
        metadata = { 
          productsInfo: aiProducts,
          comparison: hasComparison ? comparisonText : undefined,
          highlights: highlightsArray.length > 0 ? highlightsArray : undefined
        };
        
        console.log('📦📦📦 [DEBUG] 产品消息metadata:', JSON.stringify(metadata, null, 2));
      } else if (hasComparison || highlightsArray.length > 0) {
        // ✅ 纯比较/对比类型（没有产品卡片但有重点信息）
        messageType = 'text';
        metadata = { 
          comparison: hasComparison ? comparisonText : undefined,
          highlights: highlightsArray.length > 0 ? highlightsArray : undefined
        };
        
        console.log('📦📦📦 [DEBUG] 纯比较消息metadata:', JSON.stringify(metadata, null, 2));
      }

      console.log('💾💾💾 [DEBUG] 最终保存的metadata:', JSON.stringify(metadata, null, 2));
      
      // 保存AI消息到数据库（saveMessage会自动添加到messages state）
      await saveMessage({
        content: aiContent,
        sender_type: 'ai',
        message_type: messageType,
        metadata
      }, conversationId);
      
      setShowSuggestions(false);

    } catch (error) {
      console.error('❌ AI回复生成失败:', error);
      console.error('❌ 错误详情:', JSON.stringify(error, null, 2));
      
      const errorMsgId = `ai_error_${conversationId}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      const errorMessage: Message = {
        id: errorMsgId,
        content: "抱歉，我现在遇到了一些技术问题，请稍后再试。如果问题持续存在，请联系客服。",
        sender_type: 'ai',
        message_type: 'text',
        created_at: new Date().toISOString()
      };
      setMessages(prev => [...prev, errorMessage]);
      toast.error('AI回复失败，请重试');
    } finally {
      setIsAiTyping(false);
    }
  }, [user, products, currentConversationId, createConversation, saveMessage, conversations, updateConversation]);

  const handleSendMessage = async () => {
    const trimmedMessage = message.trim();
    if (!trimmedMessage || isSendingRef.current) return;
    
    // 设置发送标志，防止重复发送
    isSendingRef.current = true;
    
    // 立即清空输入框
    setMessage('');
    
    try {
      // 发送消息
      await handleAIResponse(trimmedMessage);
    } catch (error) {
      console.error('发送消息失败:', error);
    } finally {
      // 重置发送标志
      isSendingRef.current = false;
    }
  };

  const handleSuggestionClick = async (suggestion: string) => {
    if (isSendingRef.current) return;
    
    isSendingRef.current = true;
    setMessage('');
    
    try {
      await handleAIResponse(suggestion);
    } catch (error) {
      console.error('发送建议失败:', error);
    } finally {
      isSendingRef.current = false;
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const handleProductClick = (product: any) => {
    const productMessage = `我想了解一下${product.name}，请详细介绍一下`;
    handleAIResponse(productMessage);
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin mx-auto mb-2" />
          <p className="text-muted-foreground">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      {/* 固定头部导航栏 */}
      <header className="sticky top-0 z-50 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/60 border-b border-border p-3 flex-shrink-0 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center space-x-2">
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
              <span className="text-primary-foreground font-bold text-sm">AI</span>
            </div>
            <div>
              <p className="font-medium text-sm">智能购物助手</p>
              <p className="text-xs text-muted-foreground">为您推荐优质商品</p>
            </div>
          </div>
          <div className="flex items-center space-x-1">
            <Sheet open={showConversations} onOpenChange={setShowConversations}>
              <SheetTrigger asChild>
                <Button variant="ghost" size="icon" className="w-8 h-8">
                  <History className="w-4 h-4" />
                  {conversations.length > 0 && (
                    <Badge className="absolute -top-1 -right-1 w-4 h-4 p-0 text-xs">
                      {conversations.length}
                    </Badge>
                  )}
                </Button>
              </SheetTrigger>
              <SheetContent side="right" className="w-[300px] p-0">
                <SheetHeader className="p-4 border-b">
                  <SheetTitle className="flex items-center justify-between">
                    对话记录
                    <Button
                      variant="outline"
                      size="icon"
                      className="w-8 h-8"
                      onClick={() => createConversation('New Conversation')}
                    >
                      <Plus className="w-4 h-4" />
                    </Button>
                  </SheetTitle>
                </SheetHeader>
                <div className="flex-1 overflow-auto">
                  {conversations.length === 0 ? (
                    <div className="p-4 text-center text-muted-foreground">
                      <MessageCircle className="h-12 w-12 mx-auto mb-2 opacity-50" />
                      <p>暂无对话记录</p>
                      <p className="text-sm">开始您的第一次对话吧</p>
                    </div>
                  ) : (
                    <div className="space-y-1 p-2">
                      {conversations.map((conversation) => (
                        <div
                          key={conversation.id}
                          className={`relative group rounded-lg transition-all duration-200 ${
                            currentConversationId === conversation.id
                              ? 'bg-muted/50'
                              : 'hover:bg-muted/30'
                          }`}
                        >
                          <button
                            onClick={() => handleConversationSelect(conversation.id)}
                            className="w-full p-3 text-left transition-all duration-200"
                          >
                            <div className="flex items-start space-x-3">
                              <div className="mt-0.5 text-muted-foreground">
                                {getConversationIcon()}
                              </div>
                              <div className="flex-1 min-w-0 pr-8">
                                {editingConversationId === conversation.id ? (
                                  <Input
                                    value={editingTitle}
                                    onChange={(e) => setEditingTitle(e.target.value)}
                                    onKeyDown={(e) => {
                                      if (e.key === 'Enter') {
                                        handleRenameConversation(conversation.id, editingTitle);
                                      } else if (e.key === 'Escape') {
                                        cancelEditing();
                                      }
                                    }}
                                    onBlur={() => handleRenameConversation(conversation.id, editingTitle)}
                                    className="h-6 text-sm p-1 border-primary"
                                    autoFocus
                                    onClick={(e) => e.stopPropagation()}
                                  />
                                ) : (
                                  <>
                                    <div className="text-sm font-medium truncate">
                                      {conversation.title}
                                    </div>
                                    <div className="text-xs text-muted-foreground">
                                      {new Date(conversation.updated_at).toLocaleDateString('zh-CN')}
                                    </div>
                                  </>
                                )}
                              </div>
                            </div>
                          </button>
                          
                          {/* 操作菜单 */}
                          <div className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-6 w-6 text-muted-foreground hover:text-foreground hover:bg-muted/50"
                                  onClick={(e) => e.stopPropagation()}
                                >
                                  <MoreHorizontal className="h-3 w-3" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end" className="w-32">
                                <DropdownMenuItem
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    startEditingConversation(conversation.id, conversation.title);
                                  }}
                                  className="cursor-pointer"
                                >
                                  <Edit className="mr-2 h-3 w-3" />
                                  重命名
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    handleDeleteConversation(conversation.id);
                                  }}
                                  className="cursor-pointer text-destructive focus:text-destructive"
                                >
                                  <Trash2 className="mr-2 h-3 w-3" />
                                  删除
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </SheetContent>
            </Sheet>
            <Button 
              variant="ghost" 
              size="icon" 
              className="w-8 h-8"
              onClick={() => navigate('/orders')}
            >
              <ShoppingBag className="w-4 h-4" />
              {orders.length > 0 && (
                <Badge className="absolute -top-1 -right-1 w-4 h-4 p-0 text-xs">
                  {orders.length}
                </Badge>
              )}
            </Button>
            <Button 
              variant="ghost" 
              size="icon" 
              className="w-8 h-8"
              onClick={() => navigate('/profile')}
            >
              <Menu className="w-4 h-4" />
            </Button>
          </div>
        </div>
      </header>

      {/* 主聊天区域 */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <div className="flex-1 p-4 space-y-4 overflow-y-auto">
          {/* AI 介绍 */}
          {messages.length === 0 && (
            <>
              <Card className="bg-muted/30">
                <CardContent className="p-4">
                  <p className="text-sm text-muted-foreground mb-2">
                    我是您的专属 AI 购物助手，可以为您推荐{products.length}款精选商品，解答购物问题。有什么需要帮助的吗？
                  </p>
                </CardContent>
              </Card>

              {/* 聊天建议 */}
              {showSuggestions && (
                <div className="space-y-2">
                  {chatSuggestions.map((suggestion, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      className="w-full justify-start text-left h-auto p-3 text-sm"
                      onClick={() => handleSuggestionClick(suggestion)}
                    >
                      {suggestion}
                    </Button>
                  ))}
                </div>
              )}

              {/* AI 推荐内容 */}
              {aiRecommendations.length > 0 && (
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">
                      🧠 智能推荐 {isGeneratingRecommendations && <Loader2 className="inline w-3 h-3 animate-spin ml-1" />}
                    </span>
                    <ChevronDown className="w-4 h-4 text-muted-foreground" />
                  </div>

                  {aiRecommendations.map((rec) => (
                    <div key={rec.id} className="space-y-3">
                      <div className="flex items-start space-x-2">
                        <div className="w-6 h-6 bg-primary rounded-full flex items-center justify-center flex-shrink-0 mt-1">
                          <span className="text-primary-foreground text-xs">🧠</span>
                        </div>
                        <div className="flex-1">
                          <p className="text-sm font-medium mb-1">{rec.category}</p>
                          <p className="text-sm text-muted-foreground mb-3">{rec.description}</p>
                          
                          {/* 产品卡片 */}
                          <MobileProductCard
                            product={{
                              id: rec.product.id,
                              name: rec.product.name,
                              price: rec.product.price,
                              image: rec.product.image.startsWith('http') ? rec.product.image : undefined,
                              status: rec.product.reviews,
                              stock_quantity: rec.product.stock_quantity
                            }}
                            onViewDetails={() => handleProductClick(rec.product)}
                            onAddToCart={handleAddToCart}
                            compact
                          />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </>
          )}

          {/* 聊天消息 */}
          {messages.map((msg) => (
            <div key={msg.id} className={`flex ${msg.sender_type === 'user' ? 'justify-end' : 'justify-start'} mb-4`}>
              <div className={`max-w-[80%] rounded-lg ${
                msg.sender_type === 'user' 
                  ? 'bg-primary text-primary-foreground' 
                  : 'bg-muted'
              }`}>
                <div className="p-3">
                  <p className="text-sm">{msg.content}</p>
                  <span className="text-xs opacity-70 mt-1 inline-block">
                    {new Date(msg.created_at).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}
                  </span>
                </div>
                
                {/* ✅ 显示重点信息卡片（highlights） */}
                {msg.metadata?.highlights && msg.metadata.highlights.length > 0 && (
                  <div className="px-3 pb-2 pt-0">
                    <div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
                      <div className="flex items-start space-x-2">
                        <div className="w-5 h-5 bg-amber-500 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                          <span className="text-white text-xs">💡</span>
                        </div>
                        <div className="flex-1">
                          <p className="text-xs font-medium text-amber-700 dark:text-amber-300 mb-1">重点信息</p>
                          <ul className="text-sm text-amber-900 dark:text-amber-100 space-y-1">
                            {msg.metadata.highlights.map((h: string, i: number) => (
                              <li key={i}>• {h}</li>
                            ))}
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
                
                {/* ✅ 显示比较分析卡片（comparison） */}
                {msg.metadata?.comparison && (
                  <div className="px-3 pb-2 pt-0">
                    <div className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
                      <div className="flex items-start space-x-2">
                        <div className="w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                          <span className="text-white text-xs">⚖️</span>
                        </div>
                        <div className="flex-1">
                          <p className="text-xs font-medium text-blue-700 dark:text-blue-300 mb-1">对比分析</p>
                          <p className="text-sm text-blue-900 dark:text-blue-100 leading-relaxed">{msg.metadata.comparison}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
                
                {/* 显示产品推荐 - 兼容 productsInfo 和 products 两种字段名 */}
                {msg.message_type === 'products' && (msg.metadata?.productsInfo || msg.metadata?.products) && (msg.metadata.productsInfo || msg.metadata.products).length > 0 && (
                  <div className="px-3 pb-3 pt-0 space-y-2">
                    {(msg.metadata.productsInfo || msg.metadata.products).map((product: any) => (
                      <MobileProductCard
                        key={product.id}
                        product={{
                          id: product.id,
                          name: product.name,
                          price: product.price,
                          image: product.image,
                          status: product.status,
                          category: product.category,
                          stock_quantity: product.stock_quantity
                        }}
                        onViewDetails={() => handleProductClick(product)}
                        onAddToCart={handleAddToCart}
                        compact
                      />
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))}

          {/* AI思考指示器 */}
          {isAiTyping && (
            <div className="flex justify-start">
              <div className="bg-muted p-3 rounded-lg">
                <div className="flex items-center space-x-2">
                  <Loader2 className="w-4 h-4 animate-spin" />
                  <span className="text-sm text-muted-foreground">AI正在思考...</span>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 固定底部对话输入栏 */}
      <div className="sticky bottom-0 z-40 p-4 border-t border-border bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/60 shadow-lg">
        <div className="relative flex items-center space-x-2">
          <Input
            ref={inputRef}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="请输入你的问题"
            className="flex-1 pr-12"
          />
          <Button
            size="icon"
            onClick={handleSendMessage}
            disabled={!message.trim()}
            className="absolute right-2 w-8 h-8"
          >
            <Send className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </div>
  );
};

export default MobilePage;