/* eslint-disable @next/next/no-img-element */
import Link from 'next/link';
import {
  ArrowRight,
  Award,
  BookOpen,
  ChevronRight,
  Clock,
  Mic,
  Radio,
  Search,
  Star,
  Users,
} from 'lucide-react';
import CVHeader from '@/components/layout/CVHeader';
import CVFooter from '@/components/layout/CVFooter';
import {
  blogCategory,
  blogDate,
  blogExcerpt,
  blogImage,
  blogPostUrl,
  blogReadTime,
  cleanText,
  getBlogCategories,
  getBlogPosts,
} from '@/lib/blogPosts';
import { mergeStaticBlogPosts } from '@/lib/staticBlogPosts';

const DARK = '#2D0A18';
const MID = '#4A1429';
const ACCENT = '#D4B038';
const HERO_CHIP_STYLE = {
  background: 'rgba(255,255,255,0.12)',
  color: 'rgba(255,255,255,0.84)',
  borderColor: 'rgba(255,255,255,0.24)',
};
const HERO_CHIP_ACTIVE_STYLE = {
  background: ACCENT,
  color: '#1C0A12',
  borderColor: ACCENT,
  boxShadow: `0 16px 42px ${ACCENT}35`,
};
const POSTS_PER_PAGE = 12;

const TRUST = [
  { icon: Star, label: '4.9/5 Rating', sub: 'From verified students', color: ACCENT },
  { icon: Users, label: '14,000+ Graduates', sub: 'In 87 countries', color: '#7C3AED' },
  { icon: Award, label: 'Cambridge Certified', sub: 'Accredited programmes', color: '#C2410C' },
  { icon: Mic, label: 'AI Practice', sub: 'Real-time feedback', color: '#059669' },
  { icon: Radio, label: 'Live Training', sub: 'With expert trainers', color: MID },
  { icon: BookOpen, label: 'Global Community', sub: '150+ countries', color: '#1D4ED8' },
];

function CategoryBadge({ category }) {
  return (
    <span
      className="inline-flex w-fit max-w-fit self-start items-center gap-1 rounded-full px-3 py-1 text-[10px] font-extrabold uppercase tracking-widest"
      style={{
        background: `${category.color}15`,
        color: category.color,
        border: `1px solid ${category.color}30`,
      }}
    >
      <span>{category.emoji}</span>
      {category.name}
    </span>
  );
}

function FeaturedCard({ post }) {
  const category = blogCategory(post);
  const image = blogImage(post);

  return (
    <article
      className="group overflow-hidden rounded-3xl border bg-white transition-all hover:-translate-y-1 hover:shadow-2xl"
      style={{ borderColor: '#E8DDD5' }}
    >
      <Link href={blogPostUrl(post)} className="grid grid-cols-1 lg:grid-cols-2">
        <div className="relative min-h-64 overflow-hidden bg-[#F5EFE8]">
          {image ? (
            <img
              src={image}
              alt={cleanText(post.alt, post.title)}
              className="h-full min-h-64 w-full object-cover transition-transform duration-700 group-hover:scale-105"
            />
          ) : (
            <div className="flex h-full min-h-64 items-center justify-center bg-[#4A1429] text-5xl font-black text-white">
              CV
            </div>
          )}
          <div
            className="absolute left-4 top-4 rounded-full px-3 py-1.5 text-xs font-extrabold text-white"
            style={{ background: `linear-gradient(135deg, ${ACCENT}, #B8892A)` }}
          >
            Featured Article
          </div>
        </div>
        <div className="flex flex-col justify-center p-7 lg:p-10">
          <CategoryBadge category={category} />
          <h2 className="mt-3 text-xl font-black leading-snug text-[#1C0A12] transition-colors group-hover:text-[#4A1429] lg:text-2xl">
            {post.title}
          </h2>
          <p className="mt-3 text-sm leading-relaxed text-[#7A5C65]">{blogExcerpt(post, 220)}</p>
          <div className="mt-6 flex flex-wrap items-center gap-4 text-xs text-[#7A5C65]">
            <span className="flex items-center gap-1.5">
              <Clock className="h-3.5 w-3.5" />
              {blogReadTime(post)} min read
            </span>
            <span>{blogDate(post)}</span>
          </div>
          <span
            className="mt-6 inline-flex w-fit items-center gap-2 rounded-2xl px-6 py-3 text-sm font-extrabold text-white transition-all group-hover:scale-105"
            style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}
          >
            Read Article <ArrowRight className="h-4 w-4" />
          </span>
        </div>
      </Link>
    </article>
  );
}

function BlogCard({ post }) {
  const category = blogCategory(post);
  const image = blogImage(post);

  return (
    <article
      className="group flex h-full flex-col overflow-hidden rounded-3xl border bg-white transition-all hover:-translate-y-1 hover:shadow-xl"
      style={{ borderColor: '#E8DDD5' }}
    >
      <Link href={blogPostUrl(post)} className="flex h-full flex-col">
        <div className="relative h-48 overflow-hidden bg-[#F5EFE8]">
          {image ? (
            <img
              src={image}
              alt={cleanText(post.alt, post.title)}
              className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
            />
          ) : (
            <div className="flex h-full w-full items-center justify-center bg-[#4A1429] text-3xl font-black text-white">
              CV
            </div>
          )}
          <div className="absolute inset-0 bg-gradient-to-t from-black/30 to-transparent" />
        </div>
        <div className="flex flex-1 flex-col p-5">
          <CategoryBadge category={category} />
          <h3 className="mt-2.5 line-clamp-2 text-sm font-extrabold leading-snug text-[#1C0A12] transition-colors group-hover:text-[#4A1429]">
            {post.title}
          </h3>
          <p className="mt-2 line-clamp-3 text-xs leading-relaxed text-[#7A5C65]">{blogExcerpt(post)}</p>
          <div className="mt-auto flex items-center justify-between gap-3 pt-5 text-xs text-[#7A5C65]">
            <span className="flex items-center gap-1">
              <Clock className="h-3 w-3" />
              {blogReadTime(post)} min
            </span>
            <span className="flex items-center gap-1 font-bold text-[#4A1429] transition-all group-hover:gap-2">
              Read <ChevronRight className="h-3.5 w-3.5" />
            </span>
          </div>
        </div>
      </Link>
    </article>
  );
}

function pageHref({ category, page, query }) {
  const base = category && category !== 'all' ? `/blog/${category}` : '/blog';
  const params = new URLSearchParams();
  if (query) params.set('q', query);
  if (page > 1) params.set('page', String(page));
  const qs = params.toString();
  return qs ? `${base}?${qs}` : base;
}

function Pagination({ currentPage, totalPages, selectedCategory, query }) {
  if (totalPages <= 1) return null;
  const pages = Array.from({ length: totalPages }, (_, index) => index + 1);

  return (
    <nav className="mt-10 flex flex-wrap items-center justify-center gap-2" aria-label="Blog pagination">
      <Link
        href={pageHref({ category: selectedCategory, page: Math.max(1, currentPage - 1), query })}
        className={`rounded-xl border px-4 py-2 text-sm font-bold transition ${currentPage === 1 ? 'pointer-events-none opacity-40' : 'hover:bg-white'}`}
        style={{ borderColor: '#E8DDD5', color: MID }}
      >
        Previous
      </Link>
      {pages.map((page) => (
        <Link
          key={page}
          href={pageHref({ category: selectedCategory, page, query })}
          className="flex h-10 w-10 items-center justify-center rounded-xl border text-sm font-black transition"
          style={
            currentPage === page
              ? { background: MID, borderColor: MID, color: '#fff' }
              : { background: '#fff', borderColor: '#E8DDD5', color: MID }
          }
        >
          {page}
        </Link>
      ))}
      <Link
        href={pageHref({ category: selectedCategory, page: Math.min(totalPages, currentPage + 1), query })}
        className={`rounded-xl border px-4 py-2 text-sm font-bold transition ${currentPage === totalPages ? 'pointer-events-none opacity-40' : 'hover:bg-white'}`}
        style={{ borderColor: '#E8DDD5', color: MID }}
      >
        Next
      </Link>
    </nav>
  );
}

function StickyCtaBar() {
  return (
    <div
      className="hidden fixed bottom-4 left-1/2 z-50 w-[80%] max-w-[720px] -translate-x-1/2 items-center gap-4 rounded-2xl border px-5 py-3 shadow-2xl md:flex"
      style={{ background: `linear-gradient(135deg, ${DARK}, ${MID})`, borderColor: `${ACCENT}40` }}
    >
      <div className="min-w-0 flex-1">
        <p className="text-sm font-black text-white">Join the next Cambridge Veritas programme</p>
        <div className="mt-0.5 flex items-center gap-2">
          <div className="flex">
            {[...Array(5)].map((_, index) => (
              <Star key={index} className="h-3 w-3 fill-current" style={{ color: ACCENT }} />
            ))}
          </div>
          <span className="text-xs text-white/65">Trusted by 14,000+ graduates worldwide</span>
        </div>
      </div>
      <Link
        href="/certifications"
        className="flex-shrink-0 rounded-xl px-5 py-2.5 text-xs font-black text-[#1C0A12] transition-all hover:scale-105"
        style={{ background: `linear-gradient(135deg, ${ACCENT}, #F5D060)` }}
      >
        View Programmes
      </Link>
      <a
        href="https://wa.me/message/SPLHYUJO22RDI1"
        target="_blank"
        rel="noreferrer"
        className="flex-shrink-0 rounded-xl border border-white/20 px-5 py-2.5 text-xs font-black text-white transition-all hover:bg-white/10"
      >
        WhatsApp Us
      </a>
    </div>
  );
}

export default async function BlogPage({ searchParams, categorySlug }) {
  const resolvedSearchParams = await searchParams;
  const selectedCategory = cleanText(categorySlug || resolvedSearchParams?.category, 'all');
  const query = cleanText(resolvedSearchParams?.q).toLowerCase();
  const requestedPage = Number(resolvedSearchParams?.page || 1);
  const [categories, databasePosts] = await Promise.all([getBlogCategories(), getBlogPosts()]);
  const posts = mergeStaticBlogPosts(databasePosts);

  const filteredPosts = posts.filter((post) => {
    const category = blogCategory(post);
    const matchesCategory = selectedCategory === 'all' || category.slug === selectedCategory;
    const haystack = `${post.title} ${post.summary} ${post.keywords}`.toLowerCase();
    return matchesCategory && (!query || haystack.includes(query));
  });

  const showFeatured = selectedCategory === 'all' && !query && filteredPosts.length > 0;
  const featured = showFeatured ? filteredPosts[0] : null;
  const listingPosts = showFeatured ? filteredPosts.slice(1) : filteredPosts;
  const totalPages = Math.max(1, Math.ceil(listingPosts.length / POSTS_PER_PAGE));
  const currentPage = Math.min(Math.max(1, requestedPage), totalPages);
  const gridPosts = listingPosts.slice((currentPage - 1) * POSTS_PER_PAGE, currentPage * POSTS_PER_PAGE);

  return (
    <div className="min-h-screen bg-[#FAF5F0] pb-24">
      <CVHeader />
      <div className="h-1 w-full" style={{ background: 'linear-gradient(90deg, #4A1429, #D4B038, #4A1429)' }} />

      <section
        className="relative overflow-hidden px-4 py-8 sm:py-10"
        style={{ background: `linear-gradient(160deg, ${DARK} 0%, ${MID} 60%, #6B1E3D 100%)` }}
      >
        <div className="relative mx-auto max-w-6xl text-center">
          <div
            className="mb-4 inline-flex items-center gap-2 rounded-full border px-4 py-1.5"
            style={{ background: `${ACCENT}18`, borderColor: `${ACCENT}40`, color: ACCENT }}
          >
            <span className="h-1.5 w-1.5 rounded-full" style={{ background: ACCENT }} />
            <span className="text-xs font-black uppercase tracking-[0.22em]">Cambridge Veritas · Learning Blog</span>
          </div>
          <p className="mb-1 text-3xl font-black leading-none text-white sm:text-5xl">Learn. Grow.</p>
          <h1 className="mb-4 text-4xl font-black leading-none sm:text-5xl lg:text-[4rem]" style={{ color: ACCENT }}>
            Communicate Better.
          </h1>
          <p className="mx-auto mb-6 max-w-3xl text-base font-semibold leading-relaxed text-white/75 sm:text-lg">
            Expert insights on English, IELTS, pronunciation, business communication, career growth, and teacher training.
          </p>

          <form action={selectedCategory !== 'all' ? `/blog/${selectedCategory}` : '/blog'} className="relative mx-auto mb-6 max-w-xl">
            <Search className="absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-[#7A5C65]" />
            <input
              name="q"
              defaultValue={resolvedSearchParams?.q || ''}
              placeholder="Search articles..."
              className="w-full rounded-3xl border-2 border-transparent bg-white px-6 py-3 pl-14 text-sm text-[#1C0A12] shadow-lg outline-none transition-all placeholder:text-[#7A5C65] focus:border-[#D4B038]"
            />
          </form>

          <div className="mx-auto flex max-w-6xl flex-wrap justify-center gap-2 px-1 pb-2">
            <Link
              href="/blog"
              className="inline-flex items-center gap-2 rounded-full border px-4 py-2.5 text-xs font-extrabold uppercase tracking-wide transition-all"
              style={
                selectedCategory === 'all'
                  ? { background: ACCENT, color: '#1C0A12', borderColor: ACCENT, boxShadow: `0 16px 42px ${ACCENT}35` }
                  : { background: 'rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.78)', borderColor: 'rgba(255,255,255,0.2)' }
              }
            >
              <BookOpen className="h-3.5 w-3.5" /> All Topics
            </Link>
            {categories.map((category) => (
              <Link
                key={category.id}
                href={`/blog/${category.slug}`}
                className="inline-flex items-center gap-2 rounded-full border px-4 py-2.5 text-xs font-extrabold uppercase tracking-wide transition-all hover:bg-white/20"
                style={
                selectedCategory === category.slug
                    ? HERO_CHIP_ACTIVE_STYLE
                    : HERO_CHIP_STYLE
                }
              >
                <span className="text-xs leading-none">{category.emoji || '📚'}</span> {category.name}
              </Link>
            ))}
          </div>
        </div>
      </section>

      <main className="mx-auto max-w-6xl px-4 pb-16 pt-10 sm:px-6 sm:pt-14">
        {featured ? (
          <section className="mb-12">
            <div className="mb-5 flex items-center gap-2">
              <div className="h-px flex-1 bg-[#E8DDD5]" />
              <span className="rounded-full px-4 py-1.5 text-xs font-extrabold uppercase tracking-widest" style={{ background: `${MID}10`, color: MID }}>
                Featured Article
              </span>
              <div className="h-px flex-1 bg-[#E8DDD5]" />
            </div>
            <FeaturedCard post={featured} />
          </section>
        ) : null}

        <section className="mb-10">
          <div className="mb-6 flex items-center justify-between gap-4">
            <h2 className="text-xl font-black text-[#1C0A12]">
              {selectedCategory === 'all' ? 'All Articles' : categories.find((item) => item.slug === selectedCategory)?.name || 'Articles'}
              <span className="ml-2 text-sm font-normal text-[#7A5C65]">({listingPosts.length})</span>
            </h2>
            <span className="text-xs text-[#7A5C65]">From Cambridge Veritas</span>
          </div>

          {gridPosts.length === 0 ? (
            <div className="rounded-3xl border bg-white py-20 text-center" style={{ borderColor: '#E8DDD5' }}>
              <p className="text-4xl">🔍</p>
              <p className="mt-4 font-semibold text-[#7A5C65]">No articles found. Try a different search.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 sm:gap-6 lg:grid-cols-3">
              {gridPosts.map((post) => (
                <BlogCard key={post.id} post={post} />
              ))}
            </div>
          )}
          <Pagination currentPage={currentPage} totalPages={totalPages} selectedCategory={selectedCategory} query={query} />
        </section>

        <section
          className="rounded-3xl border p-7 sm:p-10"
          style={{ background: `linear-gradient(135deg, ${DARK}, ${MID})`, borderColor: `${ACCENT}30` }}
        >
          <p className="mb-6 text-center text-xs font-extrabold uppercase tracking-widest" style={{ color: ACCENT }}>
            Why learners trust Cambridge Veritas
          </p>
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
            {TRUST.map((item) => {
              const Icon = item.icon;
              return (
                <div key={item.label} className="text-center">
                  <div
                    className="mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-xl"
                    style={{ background: `${item.color}20`, border: `1px solid ${item.color}30` }}
                  >
                    <Icon className="h-5 w-5" style={{ color: item.color }} />
                  </div>
                  <p className="text-xs font-bold text-white">{item.label}</p>
                  <p className="mt-0.5 text-[10px] text-white/50">{item.sub}</p>
                </div>
              );
            })}
          </div>
          <div className="mt-8 text-center">
            <Link
              href="/certifications"
              className="inline-flex items-center gap-2 rounded-2xl px-7 py-3.5 text-sm font-extrabold text-[#1C0A12] shadow-lg transition-all hover:scale-105"
              style={{ background: `linear-gradient(135deg, ${ACCENT}, #F5D060)` }}
            >
              View Upcoming Programmes <ArrowRight className="h-4 w-4" />
            </Link>
          </div>
        </section>
      </main>

      <StickyCtaBar />
      <CVFooter />
    </div>
  );
}
