import Image from "next/image";
import type { BlogsSectionContent } from "@/app/lib/content";

type BlogItem = {
  id: string;
  title: string;
  category: string;
  excerpt: string;
  imageUrl: string;
  featured: boolean;
};

function BlogCard({ post }: { post: BlogItem }) {
  return (
    <article className="rounded-2xl border border-[#d7e1ff] bg-white p-4 sm:p-5">
      <p className="text-[11px] uppercase tracking-[0.12em] text-[#5571cc]">
        {post.category}
      </p>
      <h3 className="mt-2 text-lg sm:text-xl font-bold text-[#1a237e] leading-snug">
        {post.title}
      </h3>
      <p className="mt-3 text-sm leading-relaxed text-[#536086]">{post.excerpt}</p>
      <span className="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-[#1a237e]">
        Read Article
        <span aria-hidden="true">&rarr;</span>
      </span>
    </article>
  );
}

function FeaturedBlogPost({ post }: { post: BlogItem }) {
  const imageSrc = post.imageUrl || "/vido_galary/futureleaders.jpg";

  return (
    <article className="overflow-hidden rounded-2xl border border-[#d7e1ff] bg-white">
      <Image
        src={imageSrc}
        alt={post.title}
        width={900}
        height={620}
        className="h-56 sm:h-64 md:h-72 w-full object-cover"
      />
      <div className="p-4 sm:p-5 md:p-6">
        <p className="text-[11px] uppercase tracking-[0.12em] text-[#5571cc]">
          {post.category || "Featured Story"}
        </p>
        <h3 className="mt-2 text-xl sm:text-2xl font-bold text-[#1a237e] leading-tight">
          {post.title}
        </h3>
        <p className="mt-3 text-sm leading-relaxed text-[#536086]">
          {post.excerpt}
        </p>
        <span className="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-[#1a237e]">
          Read Featured Story
          <span aria-hidden="true">&rarr;</span>
        </span>
      </div>
    </article>
  );
}

export default function BlogsSection({
  section,
  posts,
}: {
  section: BlogsSectionContent;
  posts: BlogItem[];
}) {
  const featured = posts.find((post) => post.featured) ?? posts[0] ?? null;
  const others = posts.filter((post) => post.id !== featured?.id).slice(0, 3);

  if (!featured) {
    return null;
  }

  return (
    <section className="site-container py-8 md:py-12">
      <h2 className="mt-2 text-2xl md:text-3xl font-bold text-[#1a237e]">
        {section.heading}
      </h2>
      <p className="mt-2 max-w-3xl text-sm md:text-base text-[#5b678d] leading-relaxed">
        {section.body}
      </p>

      <div className="mt-6 grid grid-cols-1 gap-5 md:gap-6 lg:grid-cols-[1.08fr_1fr]">
        <FeaturedBlogPost post={featured} />

        <div className="grid grid-cols-1 gap-4">
          {others.map((post) => (
            <BlogCard key={post.id} post={post} />
          ))}
        </div>
      </div>
    </section>
  );
}
