'use client';

import * as React from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Badge } from '@/components/ui/badge';

interface Article {
  slug: string;
  title: string;
  cardImage: string | null;
  category: string | null;
  publicationDate: Date | null;
}

interface PopularArticlesRankingProps {
  articles: Article[];
}

/**
 * Format date to Japanese format (YYYY年MM月DD日)
 */
function formatDate(date: Date | null): string {
  if (!date) return '';
  
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  
  return `${year}年${month}月${day}日`;
}

// Red numbered badges (①②③④⑤)
const rankBadges = ['①', '②', '③', '④', '⑤'];

/**
 * PopularArticlesRanking Component
 * 
 * Displays Top 5 most popular articles with red numbered badges.
 * VERY IMPORTANT for engagement and page views.
 * 
 * Features:
 * - Section heading "人気記事ランキング" with vertical red accent bar
 * - Top 5 articles
 * - Large numbered badges (①②③④⑤) in red circles (#E60023)
 * - Article thumbnail, category badge, title, and date
 * - Hover red border glow effects
 * - Dark background (#1A1A1F) for section
 * - Responsive (mobile/desktop)
 */
export function PopularArticlesRanking({ articles }: PopularArticlesRankingProps) {
  const [imageErrors, setImageErrors] = React.useState<Record<number, boolean>>({});

  // Limit to Top 5 articles
  const topArticles = articles.slice(0, 5);

  // Don't render if no articles
  if (topArticles.length === 0) {
    return null;
  }

  const handleImageError = (index: number) => {
    setImageErrors(prev => ({ ...prev, [index]: true }));
  };

  return (
    <section className="py-12 md:py-16 bg-[#1A1A1F]">
      <div className="container">
        {/* Section heading with vertical red accent bar */}
        <h2 className="text-2xl md:text-3xl font-bold text-white border-l-4 border-[#E60023] pl-4 mb-8">
          人気記事ランキング
        </h2>

        {/* Articles list */}
        <div className="space-y-4">
          {topArticles.map((article, index) => (
            <Link
              key={article.slug}
              href={`/post/${encodeURIComponent(article.slug)}`}
              className="block group"
            >
              <div className="bg-[#202026] rounded-xl p-4 hover:shadow-[0_0_20px_rgba(230,0,35,0.3)] transition-all duration-300 border border-transparent hover:border-[#E60023]">
                <div className="flex gap-4">
                  {/* Numbered Badge (Red Circle) */}
                  <div className="flex-shrink-0">
                    <div className="w-12 h-12 md:w-14 md:h-14 rounded-full bg-[#E60023] flex items-center justify-center">
                      <span className="text-white text-2xl md:text-3xl font-bold">
                        {rankBadges[index]}
                      </span>
                    </div>
                  </div>

                  {/* Thumbnail */}
                  <div className="flex-shrink-0 w-24 h-24 md:w-32 md:h-32">
                    <div className="relative w-full h-full rounded-lg overflow-hidden bg-gradient-to-br from-gray-800 to-gray-900">
                      {article.cardImage && !imageErrors[index] ? (
                        <Image
                          src={article.cardImage}
                          alt={article.title}
                          fill
                          className="object-cover transition-transform duration-300 group-hover:scale-105"
                          sizes="(max-width: 768px) 96px, 128px"
                          unoptimized
                          onError={() => handleImageError(index)}
                        />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center">
                          <span className="text-2xl">📰</span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    {/* Category Badge */}
                    {article.category && (
                      <Badge className="mb-2 bg-[#E60023] hover:bg-[#FF2A3D] text-white border-transparent text-xs">
                        {article.category}
                      </Badge>
                    )}

                    {/* Title */}
                    <h3 className="text-base md:text-lg font-bold text-white line-clamp-2 mb-2 group-hover:text-[#E60023] transition-colors">
                      {article.title}
                    </h3>

                    {/* Date */}
                    {article.publicationDate && (
                      <p className="text-xs text-[#B8B8C0]">
                        {formatDate(article.publicationDate)}
                      </p>
                    )}
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}
