import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams, useLocation, Link } from 'react-router-dom';
import { Search, Calendar, Filter, Grid as GridIcon, List, Sparkles, BookOpen, Clock, Tag, Pin } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { PageLayout } from '@/components/layouts/PageLayout';
import { FadeIn } from '@/components/animations/FadeIn';
import { LoadingAnimation } from '@/components/ui/loading-animation';
import { cachedNewsApi } from '@/db/cached-api';
import { newsFallback } from '@/db/fallbackService';
import { Container, Section, Grid, SectionHeader } from '@/components/ui/Container';
import { NewsCard } from '@/components/ui/TraditionalCard';
import { useScrollRestoration } from '@/hooks/use-scroll-restoration';
import { SmartLink, smartNavigate } from '@/components/ui/SmartLink';
import { logEnvironmentInfo } from '@/lib/env-detect';
import type { NewsWithAuthor } from '@/types/types';
import SEO from '@/components/common/SEO';
import { getLocalizedNewsList } from '@/lib/i18n-utils';
import { useCurrentLanguage } from '@/hooks/useCurrentLanguage';
import { OptimizedImage } from '@/components/ui/OptimizedImage';
import { PageSection } from '@/components/ui/page-section';
import NewsNavigation from '@/components/common/NewsNavigation';
import { T } from '@/i18n/smartTranslate';

// 辅助函数：从HTML内容中提取纯文本
const extractTextFromHtml = (html: string): string => {
  if (!html) return '';
  // 移除HTML标签
  const text = html.replace(/<[^>]*>/g, '');
  // 移除多余空白
  return text.replace(/\s+/g, ' ').trim();
};

// 辅助函数：生成摘要
const generateSummary = (item: NewsWithAuthor, maxLength: number = 80): string => {
  // 如果有summary，直接使用
  if (item.summary) return item.summary;
  
  // 如果没有summary，从content中提取
  if (item.content) {
    const text = extractTextFromHtml(item.content);
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
  }
  
  // 如果都没有，返回空字符串
  return '';
};

// 封面图轮播组件
interface CoverImageCarouselProps {
  coverImages: string[];
  carouselInterval: number;
  title: string;
  cropX?: number;
  cropY?: number;
}

const CoverImageCarousel: React.FC<CoverImageCarouselProps> = ({
  coverImages,
  carouselInterval,
  title,
  cropX,
  cropY
}) => {
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  
  // 自动轮播
  useEffect(() => {
    if (coverImages.length <= 1) return;
    
    const interval = setInterval(() => {
      setCurrentImageIndex((prev) => (prev + 1) % coverImages.length);
    }, carouselInterval * 1000);
    
    return () => clearInterval(interval);
  }, [coverImages.length, carouselInterval]);
  
  // 计算裁剪样式（如果有裁剪坐标）
  const getCropStyle = () => {
    if (cropX === undefined || cropY === undefined) {
      // 无裁剪坐标：显示完整图片，保持宽高比
      return {
        objectFit: 'contain' as const,
        display: 'block',
        width: '100%',
        height: 'auto'
      };
    }
    
    // 有裁剪坐标：使用object-position和object-fit实现裁剪效果
    // object-fit: cover会填充容器，object-position定位显示区域
    return {
      objectPosition: `${cropX}% ${cropY}%`,
      objectFit: 'cover' as const,
      display: 'block',
      height: '100%',
      width: '100%'
    };
  };
  
  return (
    <div className="relative w-full h-full">
      {/* 使用OptimizedImage组件 - 支持懒加载和占位符 */}
      <div className="w-full h-full group-hover:scale-110 transition-transform duration-500">
        <OptimizedImage
          src={coverImages[currentImageIndex]}
          alt={title || T('资讯封面')}
          className="w-full h-full"
          placeholder="skeleton"
          priority={false}
        />
      </div>
      
      {/* 轮播指示器 */}
      {coverImages.length > 1 && (
        <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 flex flex-wrap gap-1.5 z-10 pointer-events-none">
          {coverImages.map((_, index) => (
            <div
              key={index}
              className={`w-1.5 h-1.5 rounded-full transition-all ${
                index === currentImageIndex
                  ? 'bg-white w-4'
                  : 'bg-white/50'
              }`}
            />
          ))}
        </div>
      )}
    </div>
  );
};

const NewsPage: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const { page: pageParam } = useParams<{ page?: string }>();
  const lang = useCurrentLanguage();
  const [news, setNews] = useState<NewsWithAuthor[]>([]);
  const [filteredNews, setFilteredNews] = useState<NewsWithAuthor[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  // 从 URL query 参数读取初始分类，支持 ?category=地方文化 等跳转
  const [selectedCategory, setSelectedCategory] = useState(() => {
    const params = new URLSearchParams(location.search);
    return params.get('category') || 'all';
  });
  
  // 默认使用网格模式
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  
  // 使用滚动位置恢复Hook
  useScrollRestoration();
  
  // 从路由参数读取当前页码，默认为1
  const currentPage = pageParam ? Number.parseInt(pageParam, 10) : 1;
  const itemsPerPage = 9; // 每页9篇文章

  // 打印环境信息（用于调试百度App等第三方App跳转问题）
  useEffect(() => {
    logEnvironmentInfo();
  }, []);

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

  // ── BroadcastChannel: 实时接收管理后台发布/更新通知，无需刷新页面 ────────
  useEffect(() => {
    if (typeof BroadcastChannel === 'undefined') return;
    let bc: BroadcastChannel;
    try {
      bc = new BroadcastChannel('news_updates');
      bc.onmessage = (e) => {
        if (e.data?.type === 'NEWS_UPDATED') {
          // 静默重新加载（不显示 loading 骨架）
          loadNews();
        }
      };
    } catch { /* 静默忽略 */ }
    return () => { try { bc?.close(); } catch { /* ignore */ } };
  }, []);

  // 监听页面可见性变化,当页面重新可见时刷新数据
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'visible') {
        loadNews();
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  useEffect(() => {
    filterNews();
  }, [news, searchTerm, selectedCategory]);

  // 同步 URL query 参数变化（外部跳转 /news?category=xxx 时响应）
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const cat = params.get('category') || 'all';
    setSelectedCategory(cat);
  }, [location.search]);

  // 更新页码，使用路由导航
  const updatePage = (page: number) => {
    console.log('📄 切换到第', page, '页');
    if (page === 1) {
      // 第1页使用基础路由，使用smartNavigate兼容百度App
      smartNavigate('/news', navigate);
    } else {
      // 其他页使用分页路由，使用smartNavigate兼容百度App
      smartNavigate(`/news/page/${page}`, navigate);
    }
    // 注意：滚动到顶部由 ScrollToTop 组件统一处理，无需在这里重复
  };

  const loadNews = async () => {
    try {
      setLoading(true);
      // 使用带缓存和降级方案的API
      const data = await newsFallback.getAll(() => cachedNewsApi.getPublishedNews());
      
      // 过滤掉非资讯内容（如测试、功能占位符等，如果存在）
      const functionalCategories = [T('论坛'), T('成员中心'), T('管理后台')];
      // 行业资讯页面只展示行业资讯板块或未分类的内容
      const filteredArticles = data.filter(item => 
        !functionalCategories.includes(item.category || '') && 
        (!item.display_section || item.display_section === 'industry')
      );

      // 排序逻辑：置顶的在最前面，然后按权重序号排序，最后按发布时间降序排序
      const sortedData = filteredArticles.sort((a, b) => {
        // 1. 首先按置顶状态排序（置顶的在前面）
        if (a.is_pinned && !b.is_pinned) return -1;
        if (!a.is_pinned && b.is_pinned) return 1;
        
        // 2. 按 sort_order 排序 (权重序号，越小越靠前)
        const sortA = a.sort_order ?? 999;
        const sortB = b.sort_order ?? 999;
        if (sortA !== sortB) return sortA - sortB;
        
        // 3. 按发布时间降序排序
        const dateA = new Date(a.published_at || a.created_at).getTime();
        const dateB = new Date(b.published_at || b.created_at).getTime();
        return dateB - dateA; // 降序排序（最新的在前面）
      });
      
      setNews(sortedData);
      setFilteredNews(sortedData);
    } catch (error) {
      console.error('加载资讯失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const filterNews = () => {
    let filtered = news;

    if (searchTerm) {
      console.log('[News页面] 开始搜索:', searchTerm);
      
      // 辅助函数：去除HTML标签
      const stripHtml = (html: string | null | undefined): string => {
        if (!html) return '';
        
        // 移除HTML标签
        let text = html.replace(/<[^>]*>/g, ' ');
        
        // 移除HTML实体
        text = text.replace(/&nbsp;/g, ' ');
        text = text.replace(/&lt;/g, '<');
        text = text.replace(/&gt;/g, '>');
        text = text.replace(/&amp;/g, '&');
        text = text.replace(/&quot;/g, '"');
        text = text.replace(/&#39;/g, "'");
        text = text.replace(/&[a-z]+;/gi, ' ');
        
        // 移除多余的空白字符
        text = text.replace(/\s+/g, ' ').trim();
        
        return text;
      };
      
      filtered = filtered.filter(item => {
        const lowerSearchTerm = searchTerm.toLowerCase();
        
        // 搜索标题
        if (item.title?.toLowerCase().includes(lowerSearchTerm)) {
          return true;
        }
        
        // 搜索摘要（去除HTML标签）
        const summaryText = stripHtml(item.summary);
        if (summaryText.toLowerCase().includes(lowerSearchTerm)) {
          return true;
        }
        
        // 搜索内容（去除HTML标签）
        const contentText = stripHtml(item.content);
        if (contentText.toLowerCase().includes(lowerSearchTerm)) {
          return true;
        }
        
        // 搜索来源
        if (item.source?.toLowerCase().includes(lowerSearchTerm)) {
          return true;
        }
        
        // 搜索分类
        if (item.category?.toLowerCase().includes(lowerSearchTerm)) {
          return true;
        }
        
        return false;
      });
      
      console.log('[News页面] 搜索完成，找到', filtered.length, '条结果');
    }

    if (selectedCategory !== 'all') {
      filtered = filtered.filter(item => item.category === selectedCategory);
    }

    setFilteredNews(filtered);
    // 不在这里重置页码，让用户保持在当前页
  };

  const categories = Array.from(new Set(news.map(item => item.category).filter(Boolean)));

  const totalPages = Math.ceil(filteredNews.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentNews = filteredNews.slice(startIndex, endIndex);
  
  // 本地化当前页资讯数据
  const localizedCurrentNews = getLocalizedNewsList(currentNews, lang);

  if (loading) {
    return (
      <>
        <noscript>
          <div style={{ padding: '24px', fontFamily: 'sans-serif' }}>
            <h1>中华经典传承网 — 行业资讯</h1>
            <p>正在加载内容，请启用 JavaScript 查看完整页面。</p>
          </div>
        </noscript>
        <PageLayout theme="news">
          <div className="container mx-auto px-4 py-8">
            <PageSection
              loading={true}
              skeletonConfig={{ rows: 6, card: true, cols: 2 }}
            />
          </div>
        </PageLayout>
      </>
    );
  }

  return (
    <>
      {/* SEO 优化 - 使用 react-helmet-async 管理 meta 标签 */}
      <SEO 
        title={t('news.title')}
        description={t('news.subtitle')}
        keywords={T("行业资讯,文化资讯,传统文化,文化活动,专家观点")}
        type="website"
      />
      <PageLayout 
        theme="news" 
        title={t('news.title')} 
        subtitle={t('news.subtitle')}
      >
      <div className="container mx-auto px-4 py-6 md:py-8 lg:py-10 space-y-4 sm:space-y-6 md:space-y-8">
        {/* 资讯板块导航 - 雅致子菜单 */}

        {/* 搜索和筛选区域 - 雅致升级 */}
        <section className="border-t border-amber-200/30 pt-4 mt-[0px]">
            <FadeIn direction="up">
              <div className="relative">
                {/* 优雅的背景光晕 */}
                <div className="absolute inset-0 bg-gradient-to-br from-yellow-500/5 via-amber-500/5 to-orange-500/5 rounded-3xl blur-2xl"></div>
                
                <Card className="relative border-yellow-500/20 bg-white/90 backdrop-blur-xl overflow-hidden shadow-2xl">
                  {/* 顶部装饰线 - 国风渐变 */}
                  <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent via-yellow-500 to-transparent"></div>
                  
                  {/* 四角装饰 */}
                  <div className="absolute top-0 left-0 w-20 h-20 border-t-2 border-l-2 border-yellow-500/30 rounded-tl-2xl"></div>
                  <div className="absolute top-0 right-0 w-20 h-20 border-t-2 border-r-2 border-yellow-500/30 rounded-tr-2xl"></div>
                  
                  <CardContent className="pt-12 pb-10 px-3 sm:px-4 md:px-6 lg:px-8">
                    <div className="grid grid-cols-1 md:grid-cols-12 gap-3 sm:gap-4 md:gap-6">
                    {/* 搜索框 - 雅致设计 */}
                    <div className="md:col-span-5">
                      <div className="relative group">
                        <div className="absolute inset-0 bg-gradient-to-r from-yellow-500/10 to-amber-500/10 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity"></div>
                        <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 group-hover:text-red-600 transition-colors z-10" />
                        <Input
                          type="text"
                          placeholder={t('common.searchPlaceholder')}
                          value={searchTerm}
                          onChange={(e) => setSearchTerm(e.target.value)}
                          className="relative pl-12 pr-4 py-4 sm:py-5 md:py-6 bg-white/80 border-yellow-500/20 text-gray-900 placeholder:text-gray-400 focus:border-yellow-500/50 focus:ring-2 focus:ring-yellow-500/10 transition-all rounded-lg"
                        />
                      </div>
                    </div>

                    {/* 分类筛选 - 雅致设计 */}
                    <div className="md:col-span-4">
                      <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                        <SelectTrigger className="py-4 sm:py-5 md:py-6 bg-white/80 border-yellow-500/20 text-gray-900 focus:border-yellow-500/50 focus:ring-2 focus:ring-yellow-500/10 rounded-lg">
                          <div className="flex items-center gap-2 flex-wrap">
                            <Filter className="w-4 h-4 text-red-600" />
                            <SelectValue placeholder={t('common.selectCategory')} />
                          </div>
                        </SelectTrigger>
                        <SelectContent className="bg-white border-yellow-500/30">
                          <SelectItem value="all" className="text-gray-900 hover:bg-gray-100">{t('common.allCategories')}</SelectItem>
                          {categories.map(category => (
                            <SelectItem key={category} value={category || ''} className="text-gray-900 hover:bg-gray-100">
                              {category}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    {/* 视图切换 - 雅致设计 */}
                    <div className="md:col-span-3 flex flex-wrap gap-3">

                    </div>
                  </div>
                    {/* 搜索结果统计 - 雅致设计 */}

                  </CardContent>
              </Card>
            </div>
          </FadeIn>
        </section>
        {/* 资讯列表 - 网格视图（雅致升级）*/}
        {viewMode === 'grid' && localizedCurrentNews.length > 0 && (
          <section>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 md:gap-8">
              {localizedCurrentNews.map((item, index) => (
                <FadeIn key={item.id} direction="up" delay={index * 50}>
                  <Link
                    to={`/news/${item.id}`}
                    state={{ 
                      fromPage: currentPage,
                      fromPath: location.pathname 
                    }}
                    className="block group relative h-full"
                    onClick={() => {
                      console.log('📄 从第', currentPage, '页进入文章:', item.id);
                    }}
                  >
                    {/* 优雅的背景光晕 */}
                    <div className="absolute inset-0 bg-gradient-to-br from-yellow-500/10 via-amber-500/10 to-orange-500/10 rounded-2xl blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                    
                    <Card 
                      className="relative h-full border-yellow-500/20 hover:border-yellow-500/50 bg-white/90 backdrop-blur-sm transition-all duration-300 hover:transform hover:scale-[1.02] hover:shadow-2xl hover:shadow-yellow-500/20 cursor-pointer overflow-hidden touch-manipulation"
                      style={{
                        WebkitTapHighlightColor: 'transparent',
                        touchAction: 'manipulation'
                      }}
                    >
                      {/* 顶部装饰线 */}
                      <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent via-yellow-500 to-transparent"></div>
                      
                      {/* 置顶标识（右上角） */}
                      {item.is_pinned && (
                        <div className="absolute top-3 right-3 z-10 flex items-center gap-1 flex-wrap.5 bg-gradient-to-r from-red-600 to-orange-600 text-white px-2.5 py-1 rounded-full shadow-lg shadow-red-500/50 animate-pulse">
                          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" className="w-3.5 h-3.5">
                            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                          </svg>
                          <span className="text-xs font-bold tracking-wide">{T('置顶')}</span>
                        </div>
                      )}
                      
                      {/* 判断是否有封面图 */}
                      {(item.cover_images && item.cover_images.length > 0) || item.cover_image || item.image_url ? (
                        // 有封面图：左右布局
                        (<div className="flex flex-col @md:flex-row gap-0 @md:gap-3">
                          {/* 左侧封面图 - 自适应高度，保持宽高比 */}
                          <div className={`relative flex-shrink-0 w-full @md:w-48 overflow-hidden ${
                            item.crop_x !== undefined && item.crop_y !== undefined 
                              ? 'h-48 @md:h-40' 
                              : 'bg-gray-100'
                          }`}>
                            {/* 轮播图片 */}
                            <CoverImageCarousel
                              coverImages={
                                item.cover_images && item.cover_images.length > 0 
                                  ? item.cover_images 
                                  : [item.cover_image || item.image_url].filter(Boolean) as string[]
                              }
                              carouselInterval={item.carousel_interval || 3}
                              title={item.title}
                              cropX={item.crop_x}
                              cropY={item.crop_y}
                            />
                            
                            {/* 分类标签（左上角） */}
                            {item.category && (
                              <div className="absolute top-2 left-2">
                                <Badge
                                  className="bg-white/95 backdrop-blur-sm text-yellow-600 border border-yellow-500/30 px-2 py-0.5 text-xs shadow-sm cursor-pointer hover:bg-yellow-50 transition-colors"
                                  onClick={e => { e.preventDefault(); navigate(`/news?category=${encodeURIComponent(item.category!)}`); }}
                                >
                                  {item.category}
                                </Badge>
                              </div>
                            )}
                            
                            {/* 日期（右下角） */}
                            <div className="absolute bottom-2 right-2 bg-black/70 backdrop-blur-sm text-white px-2 py-1 rounded text-xs font-medium">
                              {new Date(item.published_at || item.created_at).toLocaleDateString('zh-CN', { 
                                year: 'numeric',
                                month: '2-digit', 
                                day: '2-digit' 
                              })}
                            </div>
                          </div>
                          {/* 右侧内容区域 */}
                          <div className="flex-1 flex flex-col justify-center min-w-0 p-3 @md:p-0 @md:py-2 @md:pr-3">
                            {/* 标题 */}
                            <CardTitle className="text-base @md:text-lg text-gray-900 group-hover:text-red-600 transition-colors line-clamp-2 leading-relaxed">
                              {item.title}
                            </CardTitle>
                          </div>
                        </div>)
                      ) : (
                        // 无封面图：纯文字布局
                        (<div className="p-4">
                          {/* 分类标签 */}
                          {item.category && (
                            <Badge
                              className="bg-yellow-50 text-yellow-600 border border-yellow-500/30 px-2 py-0.5 text-xs mb-3 cursor-pointer hover:bg-yellow-100 transition-colors"
                              onClick={e => { e.preventDefault(); navigate(`/news?category=${encodeURIComponent(item.category!)}`); }}
                            >
                              {item.category}
                            </Badge>
                          )}
                          {/* 标题 */}
                          <CardTitle className="text-lg @md:text-xl text-gray-900 group-hover:text-red-600 transition-colors line-clamp-2 leading-relaxed mb-3">
                            {item.title}
                          </CardTitle>
                          {/* 摘要 - 始终显示4行 */}
                          {(() => {
                            const summary = generateSummary(item, 160);
                            return summary ? (
                              <p className="text-gray-600 text-sm line-clamp-4 leading-relaxed mb-3">
                                {summary}
                              </p>
                            ) : null;
                          })()}
                          {/* 日期和阅读全文 */}
                          <div className="flex items-center justify-between pt-3 border-t border-gray-100">
                            <div className="flex items-center gap-2 flex-wrap text-xs text-gray-400">
                              <Clock className="w-3.5 h-3.5 text-red-600" />
                              <span>
                                {new Date(item.published_at || item.created_at).toLocaleDateString('zh-CN', { 
                                  year: 'numeric', 
                                  month: 'long', 
                                  day: 'numeric' 
                                })}
                              </span>
                            </div>
                            <span className="text-xs text-red-600 group-hover:text-red-700 font-medium flex items-center gap-1 flex-wrap">
                              {T('阅读全文')}
                              <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                              </svg>
                            </span>
                          </div>
                        </div>)
                      )}
                    </Card>
                  </Link>
                </FadeIn>
              ))}
            </div>
          </section>
        )}
        {/* 资讯列表 - 列表视图（雅致升级）*/}
        {viewMode === 'list' && localizedCurrentNews.length > 0 && (
          <section>
            <div className="space-y-3 sm:space-y-4 md:space-y-6">
              {localizedCurrentNews.map((item, index) => (
                <FadeIn key={item.id} direction="up" delay={index * 30}>
                  <Link
                    to={`/news/${item.id}`}
                    state={{ 
                      fromPage: currentPage,
                      fromPath: location.pathname 
                    }}
                    className="block group relative"
                    onClick={() => {
                      console.log('📄 从第', currentPage, '页进入文章:', item.id);
                    }}
                  >
                    {/* 优雅的背景光晕 */}
                    <div className="absolute inset-0 bg-gradient-to-r from-yellow-500/5 via-amber-500/5 to-orange-500/5 rounded-2xl blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                    
                    <Card 
                      className="relative border-yellow-500/20 hover:border-yellow-500/50 bg-white/90 backdrop-blur-sm transition-all duration-300 hover:shadow-2xl hover:shadow-yellow-500/20 cursor-pointer overflow-hidden touch-manipulation"
                      style={{
                        WebkitTapHighlightColor: 'transparent',
                        touchAction: 'manipulation'
                      }}
                    >
                      {/* 顶部装饰线 */}
                      <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent via-yellow-500 to-transparent"></div>
                      
                      <CardContent className="p-4 sm:p-5 md:p-6">
                        <div className="flex flex-wrap gap-3 sm:gap-4 md:gap-6">
                          {/* 左侧封面图区域 - 始终显示 */}
                          <div className="relative w-48 h-32 flex-shrink-0 overflow-hidden rounded-xl">
                            {item.cover_image || item.image_url ? (
                              <>
                                <img src={item.cover_image || item.image_url} 
                                  alt={item.title || ''}
                                  className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                                  loading="lazy"
                                  decoding="async"
                                  onError={e => { const t = e.currentTarget; t.onerror = null; t.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300"><rect width="400" height="300" fill="#fdf8f0"/><rect x="10" y="10" width="380" height="280" fill="none" stroke="#c8a86b" stroke-width="1" opacity="0.5"/><text x="200" y="145" font-family="sans-serif" font-size="32" fill="#ddc99a" text-anchor="middle">🏮</text><text x="200" y="175" font-family="serif" font-size="12" fill="#b8892a" text-anchor="middle" opacity="0.8">暂无图片</text></svg>')}`; }} />
                                <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
                              </>
                            ) : (
                              // 默认封面（使用渐变色）
                              (<div className="w-full h-full bg-gradient-to-br from-yellow-400 via-amber-500 to-orange-600 flex items-center justify-center">
                                <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="opacity-50">
                                  <path d="M12 7v14"/>
                                  <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"/>
                                </svg>
                              </div>)
                            )}
                            
                            {/* 置顶标签（左上角） */}
                            {item.is_pinned && (
                              <div className="absolute top-2 left-2">
                                <Badge className="bg-gradient-to-r from-red-600 to-orange-600 text-white border-none shadow-lg px-2 py-0.5 text-xs">
                                  <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="currentColor" className="w-3 h-3 mr-1">
                                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                                  </svg>{T('置顶')}
                                </Badge>
                              </div>
                            )}
                          </div>
                          
                          {/* 右侧内容区域 */}
                          <div className="flex-1 flex flex-col justify-between min-w-0">
                            <div>
                              {/* 标题和分类 */}
                              <div className="flex items-start justify-between gap-4 flex-wrap mb-3">
                                <h3 className="text-xl font-bold text-gray-900 group-hover:text-red-600 transition-colors line-clamp-2 leading-relaxed flex-1 min-w-0">
                                  {item.title}
                                </h3>
                                {item.category && (
                                  <Badge
                                    className="flex-shrink-0 bg-yellow-500/10 text-yellow-600 border border-yellow-500/30 px-2 py-0.5 text-xs cursor-pointer hover:bg-yellow-500/20 transition-colors"
                                    onClick={e => { e.preventDefault(); navigate(`/news?category=${encodeURIComponent(item.category!)}`); }}
                                  >
                                    <Tag className="w-3 h-3 mr-1" />
                                    {item.category}
                                  </Badge>
                                )}
                              </div>
                              
                              {/* 摘要 */}
                              {item.summary && (
                                <p className="text-gray-600 text-sm line-clamp-2 leading-relaxed mb-4">
                                  {item.summary}
                                </p>
                              )}
                            </div>
                            
                            {/* 底部信息栏 */}
                            <div className="flex items-center justify-between pt-3 border-t border-red-600/10">
                              <div className="flex items-center gap-2 flex-wrap text-sm text-gray-400">
                                <Clock className="w-4 h-4 text-red-600" />
                                <span>{new Date(item.published_at || item.created_at).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })}</span>
                              </div>
                              <div className="flex items-center gap-2 flex-wrap text-red-600 text-sm font-medium group-hover:gap-3 transition-all">
                                <span>{t('common.readMore')}</span>
                                <BookOpen className="w-4 h-4" />
                              </div>
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </Link>
                </FadeIn>
              ))}
            </div>
          </section>
        )}
        {/* 分页 - 紧凑设计 */}
        {filteredNews.length > 0 && (
          <section className="mt-6">
            <FadeIn direction="up">
              <div className="flex items-center justify-center gap-2 flex-wrap">
                {totalPages > 1 ? (
                  <>
                    <Button
                      variant="outline"
                      disabled={currentPage === 1}
                      onClick={() => updatePage(currentPage - 1)}
                      className="border-yellow-500/20 text-gray-900 hover:bg-yellow-500/10 hover:border-yellow-500/40 disabled:opacity-30 rounded-lg transition-all h-9 px-3 text-sm"
                    >
                      {T('上一页')}
                    </Button>
                    
                    <div className="flex items-center gap-1 flex-wrap">
                      {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                        <Button
                          key={page}
                          variant={currentPage === page ? 'default' : 'outline'}
                          onClick={() => updatePage(page)}
                          className={`w-9 h-9 rounded-lg transition-all text-sm ${
                            currentPage === page
                              ? 'bg-gradient-to-r from-yellow-500 to-amber-600 text-white shadow-md shadow-yellow-500/30'
                              : 'border-yellow-500/20 text-gray-600 hover:bg-yellow-500/10 hover:border-yellow-500/40'
                          }`}
                        >
                          {page}
                        </Button>
                      ))}
                    </div>
                    
                    <Button
                      variant="outline"
                      disabled={currentPage === totalPages}
                      onClick={() => updatePage(currentPage + 1)}
                      className="border-yellow-500/20 text-gray-900 hover:bg-yellow-500/10 hover:border-yellow-500/40 disabled:opacity-30 rounded-lg transition-all h-9 px-3 text-sm"
                    >
                      {T('下一页')}
                    </Button>
                  </>
                ) : (
                  <div className="text-gray-500 text-sm py-2">
                    {`${t('common.total')} ${filteredNews.length} ${t('common.items')}`}
                  </div>
                )}
              </div>
            </FadeIn>
          </section>
        )}
        {/* 空状态 */}
        {filteredNews.length === 0 && (
          <FadeIn direction="up">
            <div className="text-center py-12 md:py-16 lg:py-20">
              <div className="w-32 h-32 mx-auto mb-6 bg-gradient-to-br from-yellow-500/20 to-amber-600/20 rounded-full flex items-center justify-center">
                <BookOpen className="w-16 h-16 text-red-600" />
              </div>
              <h3 className="text-xl sm:text-2xl font-bold text-gray-900 mb-4">{t('common.noResults')}</h3>
              <p className="text-gray-400 mb-6">{t('common.tryAdjustFilters')}</p>
              <Button
                onClick={() => {
                  setSearchTerm('');
                  setSelectedCategory('all');
                }}
                className="bg-gradient-to-r from-yellow-500 to-amber-600 hover:from-yellow-600 hover:to-amber-700 text-gray-900 rounded-lg shadow-lg shadow-yellow-500/30"
              >{T('清除筛选')}</Button>
            </div>
          </FadeIn>
        )}
      </div>
    </PageLayout>
    </>
  );
};

export default NewsPage;
