import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
  View,
  ScrollView,
  Image,
  StyleSheet,
  Pressable,
  Alert,
  Modal,
  LayoutAnimation,
  Platform,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import {
  useAppColors,
  spacing,
  borderRadius,
  fontSizes,
  shadows,
  type AppColors,
} from '../../theme';
import { Text, Loading, AppBackButton, ImageGrid, ImageGallery } from '../../components/common';
import { tradeService } from '../../services/trade/tradeService';
import { messageService } from '../../services/message/messageService';
import { useIsAuthenticated, useCurrentUser } from '../../stores/auth';
import type { TradeItemDetailDTO } from '../../types/trade';
import {
  TRADE_CONDITION_MAP,
  TRADE_CATEGORY_MAP,
  TRADE_TYPE_MAP,
  TRADE_STATUS_MAP,
} from '../../types/trade';
import { hrefChat, hrefEditTrade } from '../../navigation/hrefs';
import { useResponsive, useResponsiveValue, useResponsiveSpacing } from '../../hooks';

function createStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.default,
    },

    // ─── Header ├──
    header: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.md,
      backgroundColor: colors.background.paper,
      ...shadows.sm,
    },
    headerTitle: {
      fontSize: fontSizes.xl,
      fontWeight: '700',
      color: colors.text.primary,
    },

    // ─── 卖家信息卡片 ───
    sellerCard: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.md,
      backgroundColor: colors.background.paper,
    },
    sellerAvatarWrap: {
      position: 'relative',
    },
    sellerAvatar: {
      width: 44,
      height: 44,
      borderRadius: 22,
      backgroundColor: colors.background.default,
      borderWidth: 2,
      borderColor: colors.primary.main + '30',
    },
    sellerAvatarPlaceholder: {
      width: 44,
      height: 44,
      borderRadius: 22,
      backgroundColor: colors.primary.main + '18',
      alignItems: 'center',
      justifyContent: 'center',
      borderWidth: 2,
      borderColor: colors.primary.main + '30',
    },
    sellerInfo: {
      flex: 1,
      marginLeft: spacing.md,
    },
    sellerNameRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
    },
    sellerName: {
      fontSize: fontSizes.lg,
      fontWeight: '700',
      color: colors.text.primary,
      letterSpacing: -0.2,
    },
    sellerBadge: {
      paddingHorizontal: 6,
      paddingVertical: 2,
      borderRadius: 6,
      backgroundColor: colors.primary.main + '15',
    },
    sellerBadgeText: {
      fontSize: 10,
      fontWeight: '700',
      color: colors.primary.main,
      letterSpacing: 0.3,
    },
    sellerMetaRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.sm,
      marginTop: 2,
    },
    sellerMetaText: {
      fontSize: fontSizes.xs,
      color: colors.text.hint,
    },
    sellerMetaDot: {
      width: 3,
      height: 3,
      borderRadius: 1.5,
      backgroundColor: colors.text.hint,
    },

    // ─── 内容主体 ───
    bodySection: {
      paddingHorizontal: spacing.lg,
      paddingTop: spacing.lg,
      paddingBottom: spacing.md,
      backgroundColor: colors.background.paper,
    },

    // 标题 + 价格 同行
    titlePriceRow: {
      flexDirection: 'row',
      alignItems: 'flex-start',
      justifyContent: 'space-between',
      gap: spacing.md,
      marginBottom: spacing.sm,
    },
    titleText: {
      fontWeight: '800',
      color: colors.text.primary,
      letterSpacing: -0.5,
      flex: 1,
      flexShrink: 1,
    },
    priceBlock: {
      alignItems: 'flex-end',
      flexShrink: 0,
      marginTop: 2,
    },
    priceSymbol: {
      fontSize: fontSizes.sm,
      fontWeight: '700',
      color: '#E8453C',
    },
    priceValue: {
      fontSize: fontSizes['2xl'],
      fontWeight: '800',
      color: '#E8453C',
      letterSpacing: -0.5,
    },
    priceNegotiable: {
      fontSize: fontSizes.xs,
      fontWeight: '600',
      color: '#E8453C',
      paddingHorizontal: 5,
      paddingVertical: 1,
      borderRadius: 4,
      backgroundColor: '#E8453C' + '12',
      marginTop: 2,
    },

    // 类型标签行
    tagRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
      marginBottom: spacing.md,
      flexWrap: 'wrap',
    },
    typeTag: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 3,
      paddingHorizontal: 8,
      paddingVertical: 3,
      borderRadius: 6,
      overflow: 'hidden',
    },
    typeTagSell: {
      backgroundColor: colors.secondary.main + '14',
    },
    typeTagBuy: {
      backgroundColor: colors.info.main + '14',
    },
    typeTagText: {
      fontSize: fontSizes.xs,
      fontWeight: '700',
      letterSpacing: 0.3,
    },
    conditionTag: {
      paddingHorizontal: 8,
      paddingVertical: 3,
      borderRadius: 6,
      backgroundColor: '#F5A623' + '18',
    },
    conditionTagText: {
      fontSize: fontSizes.xs,
      fontWeight: '600',
      color: '#B87A00',
      letterSpacing: 0.2,
    },
    categoryTag: {
      paddingHorizontal: 8,
      paddingVertical: 3,
      borderRadius: 6,
      backgroundColor: colors.neutral.bg,
    },
    categoryTagText: {
      fontSize: fontSizes.xs,
      fontWeight: '500',
      color: colors.text.secondary,
    },
    statusTagSold: {
      paddingHorizontal: 8,
      paddingVertical: 3,
      borderRadius: 6,
      backgroundColor: colors.text.hint + '20',
    },
    statusTagSoldText: {
      fontSize: fontSizes.xs,
      fontWeight: '700',
      color: colors.text.hint,
    },

    // 描述
    descriptionText: {
      color: colors.text.secondary,
      letterSpacing: 0.15,
      lineHeight: 24,
      marginBottom: spacing.md,
    },

    // 属性行
    attrSection: {
      paddingTop: spacing.md,
      borderTopWidth: 1,
      borderTopColor: colors.divider + '60',
    },
    attrGrid: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: spacing.md,
    },
    attrPill: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
    },
    attrIcon: {
      width: 22,
      height: 22,
      borderRadius: 6,
      backgroundColor: colors.background.default,
      alignItems: 'center',
      justifyContent: 'center',
    },
    attrLabel: {
      fontSize: fontSizes.xs,
      color: colors.text.hint,
    },
    attrValue: {
      fontSize: fontSizes.sm,
      color: colors.text.primary,
      fontWeight: '600',
    },

    // 物流标签
    shippingRow: {
      flexDirection: 'row',
      gap: spacing.sm,
      marginTop: spacing.md,
      flexWrap: 'wrap',
    },
    shippingPill: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 3,
      paddingHorizontal: 8,
      paddingVertical: 4,
      borderRadius: 8,
      backgroundColor: colors.secondary.main + '0D',
      borderWidth: 1,
      borderColor: colors.secondary.main + '25',
    },
    shippingPillText: {
      fontSize: fontSizes.xs,
      fontWeight: '600',
      color: colors.secondary.dark,
    },

    // ─── 促销横幅 ───
    promoBanner: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.sm,
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.md,
      backgroundColor: '#FFF7ED',
      borderBottomWidth: 1,
      borderBottomColor: '#FFD6A8' + '40',
    },
    promoIcon: {
      width: 28,
      height: 28,
      borderRadius: 8,
      backgroundColor: colors.primary.main + '18',
      alignItems: 'center',
      justifyContent: 'center',
    },
    promoText: {
      fontSize: fontSizes.md,
      fontWeight: '700',
      color: '#C2410C',
      flex: 1,
    },

    // ─── 图片区域 ───
    imageSection: {
      backgroundColor: colors.background.paper,
    },

    // ─── 分隔线 ───
    divider: {
      height: spacing.sm,
      backgroundColor: colors.background.default,
    },

    // ─── 底部操作栏 ───
    bottomBar: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.sm + 2,
      backgroundColor: colors.background.paper,
      borderTopWidth: StyleSheet.hairlineWidth,
      borderTopColor: colors.divider,
      gap: spacing.md,
    },
    favButton: {
      width: 44,
      height: 44,
      borderRadius: 14,
      borderWidth: 1.5,
      borderColor: colors.divider,
      backgroundColor: colors.background.paper,
      alignItems: 'center',
      justifyContent: 'center',
    },
    favButtonActive: {
      borderColor: '#E8453C',
      backgroundColor: '#E8453C' + '0A',
    },
    shareButton: {
      width: 44,
      height: 44,
      borderRadius: 14,
      borderWidth: 1.5,
      borderColor: colors.divider,
      backgroundColor: colors.background.paper,
      alignItems: 'center',
      justifyContent: 'center',
    },
    chatButton: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      gap: spacing.xs,
      height: 44,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      ...shadows.sm,
    },
    chatButtonText: {
      color: colors.text.inverse,
      fontSize: fontSizes.lg,
      fontWeight: '700',
      letterSpacing: 0.5,
    },
    chatButtonDisabled: {
      backgroundColor: colors.text.hint,
      ...shadows.sm,
    },
    manageButton: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      gap: spacing.xs,
      height: 44,
      borderRadius: 14,
      borderWidth: 1.5,
      borderColor: colors.divider,
      backgroundColor: colors.background.paper,
    },
    manageButtonText: {
      fontSize: fontSizes.lg,
      color: colors.text.primary,
      fontWeight: '700',
    },

    // ─── 管理弹窗 ───
    modalOverlay: {
      flex: 1,
      backgroundColor: 'rgba(0,0,0,0.4)',
      justifyContent: 'flex-end',
    },
    modalContent: {
      backgroundColor: colors.background.paper,
      borderTopLeftRadius: 20,
      borderTopRightRadius: 20,
      paddingBottom: spacing.xl,
    },
    modalHandle: {
      width: 36,
      height: 4,
      borderRadius: 2,
      backgroundColor: colors.divider,
      alignSelf: 'center',
      marginTop: spacing.sm,
      marginBottom: spacing.md,
    },
    modalTitle: {
      fontSize: fontSizes.lg,
      fontWeight: '700',
      color: colors.text.primary,
      textAlign: 'center',
      marginBottom: spacing.md,
    },
    modalItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.md,
      paddingVertical: spacing.md + 2,
      paddingHorizontal: spacing.xl,
    },
    modalItemIcon: {
      width: 36,
      height: 36,
      borderRadius: 10,
      alignItems: 'center',
      justifyContent: 'center',
    },
    modalItemText: {
      fontSize: fontSizes.lg,
      color: colors.text.primary,
      fontWeight: '500',
      flex: 1,
    },
    modalCancel: {
      marginHorizontal: spacing.xl,
      marginTop: spacing.sm,
      paddingVertical: spacing.md + 2,
      alignItems: 'center',
      borderRadius: 14,
      backgroundColor: colors.background.default,
    },
    modalCancelText: {
      fontSize: fontSizes.lg,
      color: colors.text.secondary,
      fontWeight: '600',
    },

    // ─── 底部统计 ───
    statsRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.lg,
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.md,
      backgroundColor: colors.background.paper,
    },
    statItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
    },
    statText: {
      fontSize: fontSizes.xs,
      color: colors.text.hint,
      fontWeight: '500',
    },
  });
}

interface TradeDetailScreenProps {
  tradeId: string;
}

export function TradeDetailScreen({ tradeId }: TradeDetailScreenProps) {
  const colors = useAppColors();
  const styles = createStyles(colors);
  const router = useRouter();
  const isAuth = useIsAuthenticated();
  const currentUser = useCurrentUser();

  const [item, setItem] = useState<TradeItemDetailDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [manageModalVisible, setManageModalVisible] = useState(false);
  const hasRecordedView = useRef(false);
  const [showImageModal, setShowImageModal] = useState(false);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);

  const isOwner = item?.user_id === currentUser?.id;

  const { isMobile, isTablet, isDesktop, isWideScreen } = useResponsive();

  const responsivePadding = useResponsiveSpacing({
    xs: 16, sm: 18, md: 20, lg: 24, xl: 28, '2xl': 32, '3xl': 40, '4xl': 48,
  });

  const fetchItem = useCallback(async () => {
    try {
      setLoading(true);
      const data = await tradeService.getTradeItem(tradeId);
      setItem(data);
    } catch (e) {
      console.error('Failed to fetch trade item:', e);
      Alert.alert('错误', '加载失败');
    } finally {
      setLoading(false);
    }
  }, [tradeId]);

  useEffect(() => {
    fetchItem();
  }, [fetchItem]);

  useEffect(() => {
    if (tradeId && !hasRecordedView.current) {
      hasRecordedView.current = true;
      tradeService.recordView(tradeId).catch(() => {});
    }
  }, [tradeId]);

  const handleFavorite = useCallback(async () => {
    if (!isAuth || !item) return;
    try {
      if (item.is_favorited) {
        await tradeService.unfavorite(item.id);
      } else {
        await tradeService.favorite(item.id);
      }
      setItem(prev => prev ? {
        ...prev,
        is_favorited: !prev.is_favorited,
        favorites_count: prev.favorites_count + (prev.is_favorited ? -1 : 1),
      } : prev);
    } catch (e) {
      console.error('Favorite failed:', e);
    }
  }, [isAuth, item]);

  const handleDelete = useCallback(() => {
    if (!item) return;
    setManageModalVisible(false);
    Alert.alert('删除确认', '确定要删除这个商品吗？此操作不可恢复。', [
      { text: '取消', style: 'cancel' },
      {
        text: '删除',
        style: 'destructive',
        onPress: async () => {
          try {
            await tradeService.deleteTradeItem(item.id);
            router.back();
          } catch (e) {
            Alert.alert('删除失败', '请稍后重试');
          }
        },
      },
    ]);
  }, [item, router]);

  const handleEdit = useCallback(() => {
    setManageModalVisible(false);
    router.push(hrefEditTrade(item?.id || '') as any);
  }, [router, item?.id]);

  const handleChat = useCallback(async () => {
    if (!isAuth || !item?.author?.id) {
      Alert.alert('提示', '请先登录');
      return;
    }
    try {
      const conversation = await messageService.createConversation(item.author.id);
      if (conversation) {
        router.push(
          hrefChat({
            conversationId: conversation.id.toString(),
            userId: item.author.id,
          }) as any
        );
      }
    } catch (error) {
      console.error('创建会话失败:', error);
      Alert.alert('错误', '无法发起聊天，请稍后重试');
    }
  }, [isAuth, item?.author?.id, router]);

  const imageGap = isDesktop ? 12 : isTablet ? 10 : 8;
  const imageBorderRadius = isDesktop ? borderRadius.xl : borderRadius.lg;

  const images = item?.images || [];

  const tradeImages = useMemo(() => {
    return images.map(img => ({
      id: img.id,
      url: img.url || img.preview_url_large || img.preview_url || '',
      thumbnail_url: img.preview_url || img.preview_url_large || img.url || '',
      width: img.width,
      height: img.height,
    }));
  }, [images]);

  const handleImagePress = useCallback((allImages: any[], index: number) => {
    setSelectedImageIndex(index);
    setShowImageModal(true);
  }, []);

  const formatDate = (dateStr: string) => {
    const d = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - d.getTime();
    const diffMin = Math.floor(diffMs / 60000);
    const diffHr = Math.floor(diffMs / 3600000);
    const diffDay = Math.floor(diffMs / 86400000);
    if (diffMin < 1) return '刚刚';
    if (diffMin < 60) return `${diffMin}分钟前`;
    if (diffHr < 24) return `${diffHr}小时前`;
    if (diffDay < 7) return `${diffDay}天前`;
    return `${d.getMonth() + 1}月${d.getDate()}日`;
  };

  if (loading) {
    return <Loading fullScreen />;
  }

  if (!item) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <MaterialCommunityIcons name="package-variant-remove" size={48} color={colors.text.hint} />
          <Text style={{ color: colors.text.hint, marginTop: spacing.md, fontSize: fontSizes.lg }}>
            商品不存在或已删除
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  const isSell = item.trade_type === 'sell';
  const isInactive = item.status !== 'active';
  const conditionLabel = TRADE_CONDITION_MAP[item.condition as keyof typeof TRADE_CONDITION_MAP];
  const categoryLabel = TRADE_CATEGORY_MAP[item.category as keyof typeof TRADE_CATEGORY_MAP];
  const statusLabel = TRADE_STATUS_MAP[item.status as keyof typeof TRADE_STATUS_MAP];

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      {/* ─── Header ─── */}
      <View style={styles.header}>
        <AppBackButton onPress={() => router.back()} />
        <Text style={styles.headerTitle}>商品详情</Text>
        <View style={{ width: 40 }} />
      </View>

      <ScrollView showsVerticalScrollIndicator={false}>
        {/* ─── 促销横幅 ─── */}
        {item.promo_text && (
          <View style={styles.promoBanner}>
            <View style={styles.promoIcon}>
              <MaterialCommunityIcons name="tag-outline" size={16} color={colors.primary.main} />
            </View>
            <Text style={styles.promoText}>{item.promo_text}</Text>
          </View>
        )}

        {/* ─── 卖家卡片 ─── */}
        {item.author && (
          <View style={styles.sellerCard}>
            <View style={styles.sellerAvatarWrap}>
              {item.author.avatar ? (
                <Image source={{ uri: item.author.avatar }} style={styles.sellerAvatar} />
              ) : (
                <View style={styles.sellerAvatarPlaceholder}>
                  <MaterialCommunityIcons name="account" size={20} color={colors.primary.main} />
                </View>
              )}
            </View>
            <View style={styles.sellerInfo}>
              <View style={styles.sellerNameRow}>
                <Text style={styles.sellerName} numberOfLines={1}>
                  {item.author.nickname || '匿名'}
                </Text>
                {(item.author?.credit_score || 0) > 80 && (
                  <View style={styles.sellerBadge}>
                    <Text style={styles.sellerBadgeText}>信用优秀</Text>
                  </View>
                )}
              </View>
              <View style={styles.sellerMetaRow}>
                <Text style={styles.sellerMetaText}>{formatDate(item.created_at)}发布</Text>
                <View style={styles.sellerMetaDot} />
                <Text style={styles.sellerMetaText}>{item.views_count || 0}次浏览</Text>
              </View>
            </View>
          </View>
        )}

        <View style={styles.divider} />

        {/* ─── 商品主体 ─── */}
        <View style={[styles.bodySection, { paddingHorizontal: responsivePadding }]}>
          {/* 标题 + 价格 同行 */}
          <View style={styles.titlePriceRow}>
            <Text
              style={[
                styles.titleText,
                {
                  fontSize: isDesktop ? fontSizes['3xl'] : fontSizes['2xl'],
                  lineHeight: isDesktop ? 38 : 30,
                },
              ]}
              numberOfLines={3}
            >
              {item.title}
            </Text>

            <View style={styles.priceBlock}>
              {item.price != null ? (
                <>
                  <Text>
                    <Text style={styles.priceSymbol}>¥</Text>
                    <Text style={styles.priceValue}>
                      {item.price % 1 === 0 ? item.price.toFixed(0) : item.price.toFixed(2)}
                    </Text>
                  </Text>
                  {item.is_negotiable && (
                    <Text style={styles.priceNegotiable}>可议价</Text>
                  )}
                </>
              ) : (
                <Text style={styles.priceValue}>面议</Text>
              )}
            </View>
          </View>

          {/* 标签行 */}
          <View style={styles.tagRow}>
            <View style={[styles.typeTag, isSell ? styles.typeTagSell : styles.typeTagBuy]}>
              <MaterialCommunityIcons
                name={isSell ? 'tag-outline' : 'magnify'}
                size={11}
                color={isSell ? colors.secondary.dark : colors.info.dark}
              />
              <Text style={[styles.typeTagText, { color: isSell ? colors.secondary.dark : colors.info.dark }]}>
                {TRADE_TYPE_MAP[item.trade_type]}
              </Text>
            </View>

            {isInactive && (
              <View style={styles.statusTagSold}>
                <Text style={styles.statusTagSoldText}>{statusLabel}</Text>
              </View>
            )}

            {isSell && conditionLabel && (
              <View style={styles.conditionTag}>
                <Text style={styles.conditionTagText}>{conditionLabel}</Text>
              </View>
            )}

            {categoryLabel && (
              <View style={styles.categoryTag}>
                <Text style={styles.categoryTagText}>{categoryLabel}</Text>
              </View>
            )}
          </View>

          {/* 描述 */}
          {item.content && (
            <Text
              style={[
                styles.descriptionText,
                {
                  fontSize: isDesktop ? fontSizes.lg : fontSizes.md,
                  lineHeight: isDesktop ? 28 : 24,
                },
              ]}
            >
              {item.content}
            </Text>
          )}

          {/* 属性区 (出售商品) */}
          {isSell && (
            <View style={styles.attrSection}>
              <View style={styles.attrGrid}>
                {item.brand && (
                  <View style={styles.attrPill}>
                    <View style={styles.attrIcon}>
                      <MaterialCommunityIcons name="alpha-b-box-outline" size={13} color={colors.text.secondary} />
                    </View>
                    <View>
                      <Text style={styles.attrLabel}>品牌</Text>
                      <Text style={styles.attrValue}>{item.brand}</Text>
                    </View>
                  </View>
                )}
                <View style={styles.attrPill}>
                  <View style={styles.attrIcon}>
                    <MaterialCommunityIcons name="check-circle-outline" size={13} color={colors.text.secondary} />
                  </View>
                  <View>
                    <Text style={styles.attrLabel}>功能</Text>
                    <Text style={styles.attrValue}>{item.function_status || '正常'}</Text>
                  </View>
                </View>
              </View>

              {/* 物流标签 */}
              <View style={styles.shippingRow}>
                {item.is_free_shipping && (
                  <View style={styles.shippingPill}>
                    <MaterialCommunityIcons name="truck-fast-outline" size={12} color={colors.secondary.dark} />
                    <Text style={styles.shippingPillText}>包邮</Text>
                  </View>
                )}
                {item.is_self_pickup && (
                  <View style={styles.shippingPill}>
                    <MaterialCommunityIcons name="map-marker-outline" size={12} color={colors.secondary.dark} />
                    <Text style={styles.shippingPillText}>可自提</Text>
                  </View>
                )}
                {item.is_quick_ship && (
                  <View style={styles.shippingPill}>
                    <MaterialCommunityIcons name="lightning-bolt-outline" size={12} color={colors.secondary.dark} />
                    <Text style={styles.shippingPillText}>快速发货</Text>
                  </View>
                )}
              </View>
            </View>
          )}
        </View>

        {/* ─── 图片区域（文本下方） ─── */}
        {tradeImages.length > 0 && (
          <View style={[styles.imageSection, { paddingHorizontal: responsivePadding, paddingVertical: spacing.md }]}>
            <ImageGrid
              images={tradeImages}
              mode="auto"
              gap={imageGap}
              borderRadius={imageBorderRadius}
              maxDisplayCount={isWideScreen ? 20 : 100}
              showMoreOverlay={false}
              onImagePress={handleImagePress}
            />
          </View>
        )}

        {/* ─── 统计行 ─── */}
        <View style={[styles.statsRow, { paddingHorizontal: responsivePadding }]}>
          <View style={styles.statItem}>
            <MaterialCommunityIcons name="eye-outline" size={13} color={colors.text.hint} />
            <Text style={styles.statText}>{item.views_count || 0}</Text>
          </View>
          <View style={styles.statItem}>
            <MaterialCommunityIcons name="heart-outline" size={13} color={colors.text.hint} />
            <Text style={styles.statText}>{item.favorites_count || 0}</Text>
          </View>
          {item.created_at && (
            <View style={{ flex: 1, alignItems: 'flex-end' }}>
              <Text style={styles.statText}>{formatDate(item.created_at)}</Text>
            </View>
          )}
        </View>
      </ScrollView>

      {/* ─── 底部操作栏 ─── */}
      <View style={styles.bottomBar}>
        {isOwner ? (
          <Pressable style={styles.manageButton} onPress={() => setManageModalVisible(true)}>
            <MaterialCommunityIcons name="cog-outline" size={18} color={colors.text.primary} />
            <Text style={styles.manageButtonText}>管理商品</Text>
          </Pressable>
        ) : (
          <>
            <Pressable style={[styles.favButton, item.is_favorited && styles.favButtonActive]} onPress={handleFavorite}>
              <MaterialCommunityIcons
                name={item.is_favorited ? 'heart' : 'heart-outline'}
                size={20}
                color={item.is_favorited ? '#E8453C' : colors.text.hint}
              />
            </Pressable>
            {!isInactive ? (
              <Pressable style={styles.chatButton} onPress={handleChat}>
                <MaterialCommunityIcons name="chat-outline" size={18} color={colors.text.inverse} />
                <Text style={styles.chatButtonText}>聊一聊</Text>
              </Pressable>
            ) : (
              <Pressable style={[styles.chatButton, styles.chatButtonDisabled]} onPress={() => {}}>
                <Text style={styles.chatButtonText}>{statusLabel}</Text>
              </Pressable>
            )}
          </>
        )}
      </View>

      {/* ─── 管理弹窗 ─── */}
      <Modal
        visible={manageModalVisible}
        transparent
        animationType="slide"
        onRequestClose={() => setManageModalVisible(false)}
      >
        <Pressable style={styles.modalOverlay} onPress={() => setManageModalVisible(false)}>
          <Pressable style={styles.modalContent} onPress={e => e.stopPropagation()}>
            <View style={styles.modalHandle} />
            <Text style={styles.modalTitle}>管理商品</Text>

            <Pressable style={styles.modalItem} onPress={handleEdit}>
              <View style={[styles.modalItemIcon, { backgroundColor: colors.info.main + '14' }]}>
                <MaterialCommunityIcons name="pencil-outline" size={18} color={colors.info.main} />
              </View>
              <Text style={styles.modalItemText}>编辑商品</Text>
              <MaterialCommunityIcons name="chevron-right" size={20} color={colors.text.hint} />
            </Pressable>

            <Pressable style={styles.modalItem} onPress={handleDelete}>
              <View style={[styles.modalItemIcon, { backgroundColor: colors.error.main + '14' }]}>
                <MaterialCommunityIcons name="delete-outline" size={18} color={colors.error.main} />
              </View>
              <Text style={[styles.modalItemText, { color: colors.error.main }]}>删除商品</Text>
              <MaterialCommunityIcons name="chevron-right" size={20} color={colors.text.hint} />
            </Pressable>

            <Pressable style={styles.modalCancel} onPress={() => setManageModalVisible(false)}>
              <Text style={styles.modalCancelText}>取消</Text>
            </Pressable>
          </Pressable>
        </Pressable>
      </Modal>

      {/* ─── 图片预览 ─── */}
      <ImageGallery
        visible={showImageModal}
        images={tradeImages.map(img => ({
          id: img.id || img.url || String(Math.random()),
          url: img.url || '',
        }))}
        initialIndex={selectedImageIndex}
        onClose={() => setShowImageModal(false)}
        enableSave
      />
    </SafeAreaView>
  );
}
