// RelatedArticles.jsx
'use client';

import Image from "next/image";
import Link from 'next/link';
import Heading from "../../atoms/Heading";
import { Sparkles, Clock, Calendar, User, ArrowRight } from 'lucide-react';

// Helper function to get S3 URL
const getS3Url = (imagePath) => {
  if (!imagePath) return null;
  
  if (imagePath.startsWith('/')) {
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imagePath.replace(/^\/+/, "")}`;
  }
  
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  
  return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imagePath}`;
};

export default function RelatedArticles({ blogs }) {
  const formatDate = (dateString) => {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(dateString).toLocaleDateString(undefined, options);
  };

  const calculateReadTime = (description) => {
    if (!description) return 5;
    const words = description.split(' ').length;
    return Math.ceil(words / 200);
  };

  return (
    <div className="py-16">
      <div className="text-center mb-12">
        <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-6 animate-pulse">
          <Sparkles className="w-5 h-5" />
          Recommended For You
        </div>
        
        <Heading level={2} className="text-4xl font-bold text-gray-900 mb-4">
          You Might Also Like
        </Heading>
        <p className="text-gray-600 text-lg max-w-2xl mx-auto">
          Discover more insightful articles about global education and study abroad opportunities
        </p>
      </div>

      {/* Related Articles Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {blogs.map((blog) => {
          const blogImageUrl = getS3Url(blog.image);
          const authorImageUrl = blog.author?.image ? getS3Url(blog.author.image) : null;
          
          return (
            <div key={blog.id} className="group h-full">
              <div className="bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 overflow-hidden cursor-pointer border border-gray-100 hover:border-teal-200 h-full flex flex-col">
                {/* Image Container with Link */}
                <Link href={`/${blog.slug}`} className="block">
                  <div className="relative h-48 overflow-hidden bg-linear-to-br from-teal-50 to-blue-50">
                    {blogImageUrl ? (
                      <Image
                        src={blogImageUrl}
                        alt={blog.title || "Blog image"}
                        fill
                        className="object-cover group-hover:scale-105 transition-transform duration-500"
                        sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                        unoptimized={blogImageUrl.includes('s3.amazonaws.com')}
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <div className="text-4xl">📚</div>
                      </div>
                    )}
                    <div className="absolute inset-0 bg-linear-to-t from-black/50 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                    
                    {/* Category Badge */}
                    <div className="absolute top-4 left-4">
                      <div className="bg-white/90 backdrop-blur-sm px-3 py-1.5 rounded-full flex items-center gap-2">
                        <span className="text-xs font-semibold text-teal-600">
                          {blog.category?.name || 'Education'}
                        </span>
                      </div>
                    </div>
                  </div>
                </Link>
                
                {/* Content */}
                <div className="p-6 flex flex-col grow">
                  {/* Title with Link */}
                  <Link href={`/${blog.slug}`} className="block mb-3">
                    <div className="mb-3">
                      <span className="text-xs font-semibold text-teal-600 uppercase tracking-wider">
                        Study Abroad
                      </span>
                    </div>
                    
                    <Heading level={4} className="text-lg font-bold text-gray-900 mb-3 line-clamp-2 group-hover:text-teal-600 transition-colors">
                      {blog.title}
                    </Heading>
                  </Link>
                  
                  <p className="text-gray-600 text-sm line-clamp-3 mb-4 leading-relaxed grow">
                    {blog.short_description}
                  </p>
                  
                  {/* Meta Info - Single line with author left, time/date right */}
                  <div className="flex items-center justify-between text-sm text-gray-500 pt-4 border-t border-gray-100 mt-auto">
                    {/* Author Section - Left side */}
                    {blog.author && blog.author.name && (
                      <div className="flex items-center gap-2">
                        {authorImageUrl ? (
                          <Link 
                            href={`/author/${blog.author.slug}`}
                            onClick={(e) => e.stopPropagation()}
                            className="relative w-6 h-6 rounded-full overflow-hidden flex-shrink-0"
                          >
                            <Image
                              src={authorImageUrl}
                              alt={blog.author.name}
                              fill
                              className="object-cover"
                              unoptimized={authorImageUrl.includes('s3.amazonaws.com')}
                            />
                          </Link>
                        ) : (
                          <Link 
                            href={`/author/${blog.author.slug}`}
                            onClick={(e) => e.stopPropagation()}
                            className="w-6 h-6 rounded-full bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center flex-shrink-0"
                          >
                            <User className="w-3 h-3 text-teal-500" />
                          </Link>
                        )}
                        
                        <Link 
                          href={`/author/${blog.author.slug}`}
                          onClick={(e) => e.stopPropagation()}
                          className="text-gray-700 hover:text-teal-600 transition-colors line-clamp-1 max-w-[100px]"
                          title={blog.author.name}
                        >
                          {blog.author.name}
                        </Link>
                      </div>
                    )}
                    
                    {/* Time & Date - Right side */}
                    <div className="flex items-center gap-4">
                      <div className="flex items-center gap-1">
                        <Clock className="w-3 h-3 text-teal-500" />
                        <span>{calculateReadTime(blog.description)} min</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <Calendar className="w-3 h-3 text-teal-500" />
                        <span>{formatDate(blog.created_at)}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      
      {/* View All Articles Button */}
      <div className="text-center mt-12">
        <Link 
          href="/blog" 
          className="inline-flex items-center gap-2 bg-linear-to-r from-teal-600 to-blue-500 text-white font-semibold px-8 py-4 rounded-xl hover:opacity-90 transition-all duration-300"
        >
          <span>View All Articles</span>
          <ArrowRight className="w-5 h-5" />
        </Link>
      </div>
    </div>
  );
}