import React, { useState, useRef, useEffect } from 'react';
import { Button } from './ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Input } from './ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { ImageWithFallback } from './figma/ImageWithFallback';
import { PrimaryCTAButton } from './PrimaryCTAButton';
import { navigateTo } from './Router';
import {
  Search,
  Calendar,
  User,
  ArrowRight,
  BookOpen,
  Filter,
  Grid,
  List,
  SortAsc,
  Clock,
  Eye,
  Star,
  ChevronLeft,
  ChevronRight,
  X
} from 'lucide-react';

// Mock articles data
const articles = [
  {
    id: '1',
    slug: 'future-of-leadership-development',
    title: 'The Future of Leadership Development: Trends and Innovations',
    excerpt: 'Explore emerging trends in leadership development and how organizations are adapting to create more effective leaders for tomorrow\'s challenges.',
    content: 'Leadership development is evolving rapidly in response to changing workplace dynamics, technological advances, and new generations entering the workforce...',
    author: 'Sarah Johnson',
    authorTitle: 'Senior Leadership Consultant',
    authorAvatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b47c?w=150&h=150&fit=crop&crop=face',
    date: '2024-02-20',
    readTime: '8 min read',
    category: 'Leadership Development',
    tags: ['Future of Work', 'Leadership Trends', 'Innovation', 'Strategy'],
    thumbnail: 'https://images.unsplash.com/photo-1552664730-d307ca884978?w=600&h=400&fit=crop',
    featured: true,
    views: '2.4k',
    likes: 45
  },
  {
    id: '2',
    slug: 'emotional-intelligence-in-leadership',
    title: 'Emotional Intelligence: The Key to Effective Leadership',
    excerpt: 'Discover how emotional intelligence impacts leadership effectiveness and learn practical strategies to develop your EQ.',
    content: 'Emotional intelligence has become increasingly recognized as a critical factor in leadership success...',
    author: 'Dr. Michael Chen',
    authorTitle: 'Executive Coach',
    authorAvatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face',
    date: '2024-02-18',
    readTime: '6 min read',
    category: 'Personal Development',
    tags: ['Emotional Intelligence', 'Leadership Skills', 'Communication', 'Self-Awareness'],
    thumbnail: 'https://images.unsplash.com/photo-1559027615-cd4628902d4a?w=600&h=400&fit=crop',
    featured: true,
    views: '1.8k',
    likes: 32
  },
  {
    id: '3',
    slug: 'building-high-performing-teams',
    title: 'Building High-Performing Teams: A Leader\'s Guide',
    excerpt: 'Learn the essential strategies for creating and maintaining high-performing teams that deliver exceptional results.',
    content: 'High-performing teams don\'t happen by accident. They require intentional leadership, clear purpose, and the right environment...',
    author: 'Lisa Rodriguez',
    authorTitle: 'Team Development Specialist',
    authorAvatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=150&h=150&fit=crop&crop=face',
    date: '2024-02-15',
    readTime: '10 min read',
    category: 'Team Development',
    tags: ['Team Building', 'Performance', 'Collaboration', 'Leadership'],
    thumbnail: 'https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=600&h=400&fit=crop',
    featured: false,
    views: '3.1k',
    likes: 58
  },
  {
    id: '4',
    slug: 'digital-transformation-leadership',
    title: 'Leading Digital Transformation: A Strategic Approach',
    excerpt: 'Navigate the complexities of digital transformation with proven leadership strategies and best practices.',
    content: 'Digital transformation is reshaping industries and organizations worldwide. Successful transformation requires strong leadership...',
    author: 'David Park',
    authorTitle: 'Digital Strategy Consultant',
    authorAvatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face',
    date: '2024-02-12',
    readTime: '12 min read',
    category: 'Digital Transformation',
    tags: ['Digital Strategy', 'Change Management', 'Technology', 'Innovation'],
    thumbnail: 'https://images.unsplash.com/photo-1560472355-536de3962603?w=600&h=400&fit=crop',
    featured: false,
    views: '2.7k',
    likes: 41
  },
  {
    id: '5',
    slug: 'crisis-leadership-strategies',
    title: 'Crisis Leadership: Navigating Uncertainty with Confidence',
    excerpt: 'Master the art of crisis leadership and learn how to guide your organization through challenging times.',
    content: 'Crisis situations test the mettle of leaders and reveal the true strength of an organization...',
    author: 'Jennifer Adams',
    authorTitle: 'Crisis Management Expert',
    authorAvatar: 'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=150&h=150&fit=crop&crop=face',
    date: '2024-02-10',
    readTime: '9 min read',
    category: 'Crisis Management',
    tags: ['Crisis Leadership', 'Risk Management', 'Decision Making', 'Communication'],
    thumbnail: 'https://images.unsplash.com/photo-1584697964358-3e14ca57658b?w=600&h=400&fit=crop',
    featured: false,
    views: '1.9k',
    likes: 35
  },
  {
    id: '6',
    slug: 'sustainable-leadership-practices',
    title: 'Sustainable Leadership: Building for the Long Term',
    excerpt: 'Explore sustainable leadership practices that create lasting value for organizations and stakeholders.',
    content: 'Sustainable leadership goes beyond short-term gains to create lasting value for all stakeholders...',
    author: 'Robert Kim',
    authorTitle: 'Sustainability Consultant',
    authorAvatar: 'https://images.unsplash.com/photo-1560250097-0b93528c311a?w=150&h=150&fit=crop&crop=face',
    date: '2024-02-08',
    readTime: '7 min read',
    category: 'Strategy',
    tags: ['Sustainability', 'ESG', 'Long-term Thinking', 'Stakeholder Value'],
    thumbnail: 'https://images.unsplash.com/photo-1542601906990-b4d3fb778b09?w=600&h=400&fit=crop',
    featured: false,
    views: '1.5k',
    likes: 28
  },
  {
    id: '7',
    slug: 'strategic-thinking-frameworks',
    title: 'Strategic Thinking Frameworks for Modern Leaders',
    excerpt: 'Master strategic thinking with proven frameworks that help leaders anticipate challenges and seize opportunities.',
    content: 'Strategic thinking is a critical skill for leaders navigating complex business environments...',
    author: 'Dr. Amanda Foster',
    authorTitle: 'Strategic Leadership Coach',
    authorAvatar: 'https://images.unsplash.com/photo-1544725176-7c40e5a71c5e?w=150&h=150&fit=crop&crop=face',
    date: '2024-02-05',
    readTime: '11 min read',
    category: 'Strategy',
    tags: ['Strategic Thinking', 'Frameworks', 'Decision Making', 'Planning'],
    thumbnail: 'https://images.unsplash.com/photo-1552664730-d307ca884978?w=600&h=400&fit=crop',
    featured: false,
    views: '2.1k',
    likes: 39
  },
];

export function Articles() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('All Categories');
  const [selectedAuthor, setSelectedAuthor] = useState('All Authors');
  const [selectedReadTime, setSelectedReadTime] = useState('All Read Times');
  const [selectedDateRange, setSelectedDateRange] = useState('All Time');
  const [selectedTopic, setSelectedTopic] = useState('All Topics');
  const [sortBy, setSortBy] = useState('Most Recent');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [currentPage, setCurrentPage] = useState(1);
  const articlesPerPage = 4;
  const containerRef = useRef<HTMLDivElement>(null);
  

  // Get unique values for filters
  const categories = ['All Categories', ...Array.from(new Set(articles.map(article => article.category)))];
  const authors = ['All Authors', ...Array.from(new Set(articles.map(article => article.author)))];
  const readTimes = ['All Read Times', 'Under 5 min', '5-10 min', 'Over 10 min'];
  const dateRanges = ['All Time', 'Last 7 days', 'Last 30 days', 'Last 3 months'];
  const allTags = Array.from(new Set(articles.flatMap(article => article.tags)));
  const sortOptions = [
    { value: 'Most Recent', label: 'Most Recent' },
    { value: 'oldest', label: 'Oldest First' },
    { value: 'title', label: 'Title A-Z' },
    { value: 'readTime', label: 'Read Time' },
    { value: 'popular', label: 'Most Popular' }
  ];

  // Filter and sort articles
  const filteredArticles = articles.filter(article => {
    const matchesSearch = article.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      article.excerpt.toLowerCase().includes(searchTerm.toLowerCase()) ||
      article.author.toLowerCase().includes(searchTerm.toLowerCase()) ||
      article.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesCategory = selectedCategory === 'All Categories' || article.category === selectedCategory;
    const matchesAuthor = selectedAuthor === 'All Authors' || article.author === selectedAuthor;

    // FIXED: Read time filter - properly parse the read time
    const readTimeMinutes = parseInt(article.readTime.replace(' min read', '')) || 0;
    const matchesReadTime = selectedReadTime === 'All Read Times' ||
      (selectedReadTime === 'Under 5 min' && readTimeMinutes < 5) ||
      (selectedReadTime === '5-10 min' && readTimeMinutes >= 5 && readTimeMinutes <= 10) ||
      (selectedReadTime === 'Over 10 min' && readTimeMinutes > 10);

    // Date range filter
    const articleDate = new Date(article.date);
    const now = new Date();
    const matchesDateRange = selectedDateRange === 'All Time' ||
      (selectedDateRange === 'Last 7 days' && (now.getTime() - articleDate.getTime()) <= 7 * 24 * 60 * 60 * 1000) ||
      (selectedDateRange === 'Last 30 days' && (now.getTime() - articleDate.getTime()) <= 30 * 24 * 60 * 60 * 1000) ||
      (selectedDateRange === 'Last 3 months' && (now.getTime() - articleDate.getTime()) <= 90 * 24 * 60 * 60 * 1000);

    // Topic filter
    const matchesTopic = selectedTopic === 'All Topics' ||
      article.tags.includes(selectedTopic);

    return matchesSearch && matchesCategory && matchesAuthor && matchesReadTime && matchesDateRange && matchesTopic;
  }).sort((a, b) => {
    switch (sortBy) {
      case 'Most Recent':
        return new Date(b.date).getTime() - new Date(a.date).getTime();
      case 'oldest':
        return new Date(a.date).getTime() - new Date(b.date).getTime();
      case 'title':
        return a.title.localeCompare(b.title);
      case 'readTime':
        // FIXED: Sort by read time - properly parse the values
        return (parseInt(a.readTime.replace(' min read', '')) || 0) - (parseInt(b.readTime.replace(' min read', '')) || 0);
      case 'popular':
        return parseInt(b.views) - parseInt(a.views);
      default:
        return 0;
    }
  });

  // Paginate results
  const totalPages = Math.ceil(filteredArticles.length / articlesPerPage);
  const startIndex = (currentPage - 1) * articlesPerPage;
  const currentArticles = filteredArticles.slice(startIndex, startIndex + articlesPerPage);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const clearAllFilters = () => {
    setSearchTerm('');
    setSelectedCategory('All Categories');
    setSelectedAuthor('All Authors');
    setSelectedReadTime('All Read Times');
    setSelectedDateRange('All Time');
    setSelectedTopic('All Topics');
    setSortBy('Most Recent');
  };



  const hasActiveFilters = searchTerm ||
    selectedCategory !== 'All Categories' ||
    selectedAuthor !== 'All Authors' ||
    selectedReadTime !== 'All Read Times' ||
    selectedDateRange !== 'All Time' ||
    selectedTopic !== 'All Topics';

  return (
    <div style={{ backgroundColor: '#FFFFFF' }}>
      {/* Hero Section */}
      <section className="relative py-28 overflow-hidden">
        <div className="absolute inset-0">
          <ImageWithFallback
            src="https://images.unsplash.com/photo-1481627834876-b7833e8f5570?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxhcnRpY2xlJTIwYmxvZyUyMGNvbnRlbnQlMjBrbm93bGVkZ2V8ZW58MXx8fHwxNzU1ODU0Mjg2fDA&ixlib=rb-4.1.0&q=80&w=1080"
            alt="Knowledge and insights through articles and research"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-black/60" />
        </div>

        <div className="relative section-margin-x">
          <div className="max-w-4xl mx-auto text-center">
            <div className="branded-tag-system-white mb-6 justify-center">
              <div className="dot"></div>
              <span className="text">INSIGHTS & KNOWLEDGE</span>
            </div>

            <h1 className="text-h1-white mb-6">
              Articles & Research
            </h1>

            <p className="text-body-lg-white mb-8 max-w-2xl mx-auto">
              Discover cutting-edge insights, research findings, and expert perspectives on leadership development, management strategies, and organizational excellence.
            </p>
          </div>
        </div>

        {/* Statistics Strip */}
        <div className="absolute bottom-0 left-0 right-0">
          <div className="bg-black/80 backdrop-blur-sm px-8 py-6">
            <div className="section-margin-x">
              <div className="grid grid-cols-3 gap-8 text-center">
                <div>
                  <div className="text-h2-white mb-2">{articles.length}+</div>
                  <div className="text-small-white">Expert Articles</div>
                </div>
                <div>
                  <div className="text-h2-white mb-2">{categories.length - 1}</div>
                  <div className="text-small-white">Categories</div>
                </div>
                <div>
                  <div className="text-h2-white mb-2">25,400</div>
                  <div className="text-small-white">Total Reads</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Search and Controls Section */}
      <section className="py-8" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="section-margin-x">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
            {/* Search Bar */}
            <div className="relative max-w-md flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                type="text"
                placeholder="Search articles, authors, topics..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 pr-4 py-3 text-body rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 w-full bg-gray-50"
                style={{
                  fontSize: 'var(--font-body)',
                  fontFamily: 'var(--font-family-base)',
                  height: '48px'
                }}
              />
            </div>

            {/* View Toggle and Sort */}
            <div className="flex items-center gap-4">
              <div className="flex items-center border border-gray-300 rounded-lg overflow-hidden">
                <button
                  onClick={() => setViewMode('grid')}
                  className={`p-2 transition-colors ${viewMode === 'grid'
                      ? 'text-white'
                      : 'bg-white text-gray-600 hover:bg-gray-50'
                    }`}
                  style={{
                    backgroundColor: viewMode === 'grid' ? 'var(--color-primary)' : undefined
                  }}
                  aria-label="Grid view"
                >
                  <Grid className="w-4 h-4" />
                </button>
                <button
                  onClick={() => setViewMode('list')}
                  className={`p-2 transition-colors ${viewMode === 'list'
                      ? 'text-white'
                      : 'bg-white text-gray-600 hover:bg-gray-50'
                    }`}
                  style={{
                    backgroundColor: viewMode === 'list' ? 'var(--color-primary)' : undefined
                  }}
                  aria-label="List view"
                >
                  <List className="w-4 h-4" />
                </button>
              </div>

              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-40 text-body">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  {sortOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      </section>

      {/* Main Content Section with Sidebar */}
      <section className="pb-16" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="section-margin-x">
          <div className="grid grid-cols-12 gap-8">
            {/* Left Sidebar - Sticky Filters */}
            <div className="col-span-12 lg:col-span-3">
              <div className="sticky top-4">
                <Card className="bg-white border border-gray-200 rounded-lg shadow-md overflow-hidden">
                  {/* Filter Header */}
                  <div className="bg-gray-50 px-4 py-3 border-b border-gray-200">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="p-1.5 rounded-md" style={{ backgroundColor: 'rgba(4, 4, 91, 0.1)' }}>
                          <Filter className="w-3.5 h-3.5" style={{ color: 'var(--color-primary)' }} />
                        </div>
                        <h3 className="text-body font-semibold text-gray-800">
                          Filters
                        </h3>
                      </div>
                      {hasActiveFilters && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={clearAllFilters}
                          className="text-xs px-2 py-1 rounded-md transition-colors filter-clear-btn"
                        >
                          <X className="w-3 h-3 mr-1" />
                          Clear
                        </Button>
                      )}
                    </div>
                  </div>

                  {/* Filter Content */}
                  <div className="p-4">
                    <div className="space-y-4">
                      {/* Category Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Category
                        </label>
                        <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors" style={{ '&:focus': { borderColor: 'var(--color-primary)' } }}>
                            <SelectValue placeholder="All Categories" />
                          </SelectTrigger>
                          <SelectContent>
                            {categories.map((category) => (
                              <SelectItem key={category} value={category} className="text-small">
                                {category}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Author Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Author
                        </label>
                        <Select value={selectedAuthor} onValueChange={setSelectedAuthor}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors" style={{ '&:focus': { borderColor: 'var(--color-primary)' } }}>
                            <SelectValue placeholder="All Authors" />
                          </SelectTrigger>
                          <SelectContent>
                            {authors.map((author) => (
                              <SelectItem key={author} value={author} className="text-small">
                                {author}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Read Time Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Read Time
                        </label>
                        <Select value={selectedReadTime} onValueChange={setSelectedReadTime}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors" style={{ '&:focus': { borderColor: 'var(--color-primary)' } }}>
                            <SelectValue placeholder="All Read Times" />
                          </SelectTrigger>
                          <SelectContent>
                            {readTimes.map((readTime) => (
                              <SelectItem key={readTime} value={readTime} className="text-small">
                                {readTime}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Date Range Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Date Range
                        </label>
                        <Select value={selectedDateRange} onValueChange={setSelectedDateRange}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors" style={{ '&:focus': { borderColor: 'var(--color-primary)' } }}>
                            <SelectValue placeholder="All Time" />
                          </SelectTrigger>
                          <SelectContent>
                            {dateRanges.map((dateRange) => (
                              <SelectItem key={dateRange} value={dateRange} className="text-small">
                                {dateRange}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Topics Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Topic
                        </label>
                        <Select value={selectedTopic} onValueChange={setSelectedTopic}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors" style={{ '&:focus': { borderColor: 'var(--color-primary)' } }}>
                            <SelectValue placeholder="All Topics" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="All Topics" className="text-small">
                              All Topics
                            </SelectItem>
                            {allTags.map((tag) => (
                              <SelectItem key={tag} value={tag} className="text-small">
                                {tag}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </div>
                </Card>
              </div>
            </div>

            {/* Right Content Area - Scrollable Articles */}
            <div className="col-span-12 lg:col-span-9">
              <div className="mb-4 text-small text-muted">
                Showing {currentArticles.length} of {filteredArticles.length} articles
              </div>

              {/* Articles Results */}
              {currentArticles.length === 0 ? (
                <div className="text-center py-12">
                  <p className="text-body-lg text-muted">
                    No articles found matching your criteria.
                  </p>
                </div>
              ) : (
                <>
                  {/* Grid View */}
                  {viewMode === 'grid' && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                      {currentArticles.map((article) => (
                        <Card
                          key={article.id}
                          className="overflow-hidden hover:shadow-lg transition-all duration-300 cursor-pointer group"
                          onClick={() => navigateTo(`/learning/articles/${article.slug}`)}
                        >
                          <div className="aspect-video w-full bg-gray-100 overflow-hidden relative">
                            <ImageWithFallback
                              src={article.thumbnail}
                              alt={article.title}
                              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                            />
                            {article.featured && (
                              <div className="absolute top-4 right-4">
                                <Badge
                                  variant="secondary"
                                  className="bg-yellow-100 text-yellow-800 border-yellow-200"
                                >
                                  Featured
                                </Badge>
                              </div>
                            )}
                          </div>
                          <CardContent className="p-6">
                            <div className="flex items-center gap-2 mb-3">
                              <Badge variant="outline" className="text-small">
                                {article.category}
                              </Badge>
                              <span className="text-small text-muted">{article.readTime}</span>
                            </div>

                            <h3 className="text-h4 mb-3 group-hover:text-blue-600 transition-colors line-clamp-2">
                              {article.title}
                            </h3>

                            <p className="text-small text-muted mb-4 line-clamp-3">
                              {article.excerpt}
                            </p>

                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <ImageWithFallback
                                  src={article.authorAvatar}
                                  alt={article.author}
                                  className="w-6 h-6 rounded-full object-cover"
                                />
                                <span className="text-small">{article.author}</span>
                              </div>
                              <div className="text-small text-muted">
                                {formatDate(article.date)}
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  )}

                  {/* List View */}
                  {viewMode === 'list' && (
                    <div className="space-y-6">
                      {currentArticles.map((article) => (
                        <Card
                          key={article.id}
                          className="overflow-hidden hover:shadow-lg transition-all duration-300 cursor-pointer group"
                          onClick={() => navigateTo(`/learning/articles/${article.slug}`)}
                        >
                          <div className="flex flex-col md:flex-row">
                            <div className="md:w-80 h-48 md:h-auto bg-gray-100 overflow-hidden relative flex-shrink-0">
                              <ImageWithFallback
                                src={article.thumbnail}
                                alt={article.title}
                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                              />
                              {article.featured && (
                                <div className="absolute top-2 right-2">
                                  <Badge
                                    variant="secondary"
                                    className="bg-yellow-100 text-yellow-800 border-yellow-200 text-xs"
                                  >
                                    Featured
                                  </Badge>
                                </div>
                              )}
                            </div>

                            <div className="flex-1 p-6">
                              <div className="flex justify-between items-start">
                                <div className="flex-1">
                                  <div className="flex items-center gap-2 mb-2">
                                    <Badge variant="outline" className="text-small">
                                      {article.category}
                                    </Badge>
                                    <span className="text-small text-muted">{article.readTime}</span>
                                    <div className="flex items-center gap-1 text-small text-muted">
                                      <Eye className="w-3 h-3" />
                                      <span>{article.views}</span>
                                    </div>
                                  </div>

                                  <h3 className="text-h4 mb-2 group-hover:text-blue-600 transition-colors">
                                    {article.title}
                                  </h3>

                                  <p className="text-body text-muted mb-3">
                                    {article.excerpt}
                                  </p>

                                  <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                      <ImageWithFallback
                                        src={article.authorAvatar}
                                        alt={article.author}
                                        className="w-6 h-6 rounded-full object-cover"
                                      />
                                      <div>
                                        <span className="text-small font-medium">{article.author}</span>
                                        <span className="text-small text-muted ml-1">• {article.authorTitle}</span>
                                      </div>
                                    </div>
                                    <div className="text-small text-muted">
                                      {formatDate(article.date)}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </Card>
                      ))}
                    </div>
                  )}

                  {/* Pagination */}
                  {totalPages > 1 && (
                    <div className="flex items-center justify-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setCurrentPage(prev => Math.max(1, prev - 1));
                          containerRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }}
                        disabled={currentPage === 1}
                        className="flex items-center gap-1 border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        <ChevronLeft className="w-4 h-4" />
                        Previous
                      </Button>

                      <div className="flex items-center gap-1">
                        {Array.from({ length: totalPages }, (_, i) => {
                          const page = i + 1;
                          // Show limited pages for better UX
                          if (totalPages > 7) {
                            const showPage =
                              page === 1 ||
                              page === totalPages ||
                              (page >= currentPage - 1 && page <= currentPage + 1);

                            if (!showPage) {
                              if (page === currentPage - 2 || page === currentPage + 2) {
                                return <span key={page} className="px-2">...</span>;
                              }
                              return null;
                            }
                          }

                          return (
                            <Button
                              key={page}
                              variant={currentPage === page ? "default" : "outline"}
                              size="sm"
                              onClick={() => {
                                setCurrentPage(page);
                                containerRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
                              }}
                              className={`min-w-10 ${currentPage === page
                                ? 'bg-blue-600 text-white hover:bg-blue-700'
                                : 'border-gray-300 text-gray-700 hover:bg-gray-50'
                                }`}
                            >
                              {page}
                            </Button>
                          );
                        })}
                      </div>

                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setCurrentPage(prev => Math.min(totalPages, prev + 1));
                          containerRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }}
                        disabled={currentPage === totalPages}
                        className="flex items-center gap-1 border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        Next
                        <ChevronRight className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* CTA Banner Section */}
      <section className="relative h-[700px] overflow-hidden">
        <div className="absolute inset-0">
          <ImageWithFallback
            src="https://images.unsplash.com/photo-1753613648191-4771cf76f034?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxvbmxpbmUlMjBsZWFybmluZyUyMGRpZ2l0YWwlMjBlZHVjYXRpb258ZW58MXx8fHwxNzU1ODU0Mjc1fDA&ixlib=rb-4.1.0&q=80&w=1080"
            alt="Online learning and digital education environment"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-black/30" />
          <div className="absolute inset-0 bg-gradient-to-r from-black/20 via-transparent to-black/60" />
        </div>

        <div className="relative h-full flex items-center justify-end section-margin-x">
          <div
            className="bg-opacity-95 backdrop-blur-sm rounded-lg p-16 max-w-2xl"
            style={{
              backgroundColor: 'var(--color-brand-primary)'
            }}
          >
            <div className="branded-tag-system-next-steps mb-6 justify-start">
              <div className="dot"></div>
              <span className="text">NEXT STEPS</span>
            </div>

            <h2 className="text-h2-white mb-8">
              Ready to explore more insights?
              <span
                className="italic"
                style={{ color: 'var(--color-brand-accent)' }}
              >
                {" "}Discover{" "}
              </span>
              our complete library of leadership resources.
            </h2>

            <PrimaryCTAButton
              text="Browse All Resources"
              onClick={() => navigateTo('/learning/articles')}
              ariaLabel="Browse all leadership articles and resources"
              className="cta-banner-yellow mb-6"
            />

            <p className="text-body-white opacity-90">
              Access cutting-edge research, expert insights, and practical guidance to accelerate your leadership journey and organizational success.
            </p>
          </div>
        </div>
      </section>
    </div>
  );
}