/* eslint-disable @next/next/no-img-element */
import Link from 'next/link';
import { headers } from 'next/headers';
import { notFound } from 'next/navigation';
import {
  ArrowLeft,
  ArrowRight,
  BookOpen,
  Bookmark,
  CheckCircle,
  ChevronRight,
  Clock,
  FileText,
  MessageCircle,
  Mic,
  Share2,
  Sparkles,
  Star,
} from 'lucide-react';
import CVHeader from '@/components/layout/CVHeader';
import CVFooter from '@/components/layout/CVFooter';
import BlogPostClient from '../BlogPostClient';
import BlogPage from '../page';
import { STATIC_BLOG_COMPONENTS } from '@/components/blog/custom';
import {
  blogCategory,
  blogDate,
  blogExcerpt,
  blogImage,
  blogPostUrl,
  blogReadTime,
  blogSmallImage,
  cleanText,
  getBlogBlocks,
  getBlogCategories,
  getBlogPostBySlug,
  getRelatedBlogPosts,
  parseJsonList,
  postSections,
} from '@/lib/blogPosts';
import { getStaticBlogPostBySlug } from '@/lib/staticBlogPosts';
import { getContentMetadataForRequest, getRequestMetadataInput } from '@/lib/siteSeo';
import { MAIN_SITE_URL } from '@/lib/mainSiteUrl';

const APP_URL = MAIN_SITE_URL;

export async function generateMetadata({ params }) {
  const resolvedParams = await params;
  const slugParts = Array.isArray(resolvedParams.slug) ? resolvedParams.slug : [resolvedParams.slug];
  const postSlug = slugParts.at(-1);
  const post = await getBlogPostBySlug(postSlug) || getStaticBlogPostBySlug(postSlug);
  if (!post) return {};

  const category = blogCategory(post);
  const image = blogImage(post);
  const excerpt = blogExcerpt(post, 155);
  const title = `${cleanText(post.title)} | Cambridge Veritas`;
  return getContentMetadataForRequest({
    ...getRequestMetadataInput(await headers(), {
      pathname: `/blog/${category.slug}/${post.slug}`,
    }),
    title,
    description: excerpt,
    keywords: cleanText(post.keywords).split(',').map((k) => k.trim()).filter(Boolean),
    image,
    imageAlt: cleanText(post.alt, post.title),
    type: 'article',
    publishedTime: post.created_at ? new Date(post.created_at).toISOString() : undefined,
    modifiedTime: post.updated_at ? new Date(post.updated_at).toISOString() : undefined,
    section: category.name,
  });
}

const DARK = '#2D0A18';
const MID = '#4A1429';
const ACCENT = '#D4B038';
const WA_LINK = 'https://wa.me/message/SPLHYUJO22RDI1';

function parseBlockContent(content) {
  try {
    return JSON.parse(content || '{}');
  } catch {
    return { text: cleanText(content) };
  }
}

function SummaryBox({ points, fallback }) {
  const items = points.length ? points : [fallback].filter(Boolean);
  if (!items.length) return null;

  return (
    <div className="cv-summary mb-7 rounded-2xl border p-5" style={{ background: '#FFFBEB', borderColor: '#FDE68A' }}>
      <p className="mb-3 text-xs font-extrabold uppercase tracking-widest text-[#B45309]">Quick Summary</p>
      <ul className="space-y-1.5">
        {items.map((point) => (
          <li key={point} className="flex items-start gap-2 text-sm text-amber-800">
            <CheckCircle className="mt-0.5 h-4 w-4 flex-shrink-0 text-amber-500" />
            <span>{point}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function BlockRenderer({ block }) {
  const data = parseBlockContent(block.content);

  if (block.block_type === 'heading') {
    return (
      <section id={data.id || undefined} className="scroll-mt-28">
        <h2 className="mt-10 text-xl font-black leading-snug text-[#1C0A12] sm:text-2xl">{data.title || data.toc_label}</h2>
      </section>
    );
  }

  if (block.block_type === 'paragraph') {
    return <p>{data.text}</p>;
  }

  if (block.block_type === 'key_takeaway') {
    return (
      <div className="my-7 flex gap-4 rounded-2xl border p-5" style={{ background: `${ACCENT}0E`, borderColor: `${ACCENT}40` }}>
        <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-xl" style={{ background: `${ACCENT}20` }}>
          <Sparkles className="h-4 w-4" style={{ color: ACCENT }} />
        </div>
        <div>
          <p className="mb-1.5 text-xs font-extrabold uppercase tracking-widest" style={{ color: ACCENT }}>
            {data.label || 'Teacher Insight'}
          </p>
          <p className="text-sm font-semibold leading-relaxed text-[#1C0A12]">{data.text}</p>
        </div>
      </div>
    );
  }

  if (block.block_type === 'quote') {
    return (
      <blockquote className="my-8 border-l-4 py-2 pl-6" style={{ borderColor: ACCENT }}>
        <p className="mb-2 text-lg font-bold italic leading-relaxed text-[#1C0A12]">{`"${data.text}"`}</p>
        {data.author ? <p className="text-xs font-semibold text-[#7A5C65]">- {data.author}</p> : null}
      </blockquote>
    );
  }

  if (block.block_type === 'common_mistake') {
    return (
      <div className="my-7 overflow-hidden rounded-2xl border border-red-200">
        <div className="bg-red-50 px-5 py-3">
          <p className="text-xs font-extrabold uppercase tracking-widest text-red-600">Common Mistake</p>
        </div>
        <div className="grid sm:grid-cols-2">
          <div className="border-b border-red-100 bg-red-50/50 px-5 py-4 sm:border-b-0 sm:border-r">
            <p className="mb-1.5 text-[10px] font-bold uppercase text-red-400">What students say</p>
            <p className="text-sm font-medium italic text-red-700">{`"${data.mistake}"`}</p>
          </div>
          <div className="bg-emerald-50/50 px-5 py-4">
            <p className="mb-1.5 text-[10px] font-bold uppercase text-emerald-500">What confident speakers say</p>
            <p className="text-sm font-medium italic text-emerald-700">{`"${data.fix}"`}</p>
          </div>
        </div>
      </div>
    );
  }

  if (block.block_type === 'try_this' || block.block_type === 'student_tip') {
    const studentTip = block.block_type === 'student_tip';
    return (
      <div
        className="my-7 rounded-2xl border p-5"
        style={studentTip ? { background: '#F5F3FF', borderColor: '#DDD6FE' } : { background: '#ECFDF5', borderColor: '#A7F3D0' }}
      >
        <p className={`mb-3 text-xs font-extrabold uppercase tracking-widest ${studentTip ? 'text-violet-600' : 'text-emerald-600'}`}>
          {studentTip ? 'Student Tip' : 'Try This Today'}
        </p>
        <p className={`text-sm leading-relaxed ${studentTip ? 'text-violet-800 italic' : 'text-emerald-800'}`}>{data.text}</p>
      </div>
    );
  }

  if (block.block_type === 'feature_grid' && Array.isArray(data.items)) {
    return (
      <div className="my-7 grid gap-4 sm:grid-cols-2">
        {data.items.map(([title, text]) => (
          <div key={title} className="rounded-2xl border bg-white p-5" style={{ borderColor: '#E8DDD5' }}>
            <h3 className="mb-1 font-black text-[#1C0A12]">{title}</h3>
            <p className="text-sm leading-relaxed text-[#7A5C65]">{text}</p>
          </div>
        ))}
      </div>
    );
  }

  if (block.block_type === 'data_table' && Array.isArray(data.rows)) {
    const headers = data.headers || [];
    const columnCount = Math.max(2, Math.min(4, Number(data.columns || headers.length || data.rows?.[0]?.length || 3)));
    const gridClass = columnCount >= 3 ? 'sm:grid-cols-3' : 'sm:grid-cols-[0.75fr_1.45fr]';
    return (
      <div className="my-7 overflow-hidden rounded-2xl border bg-white" style={{ borderColor: '#E8DDD5' }}>
        {headers.length ? (
          <div
            className={`grid grid-cols-1 gap-2 px-4 py-3 text-[10px] font-black uppercase tracking-widest text-white ${gridClass}`}
            style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}
          >
            {headers.slice(0, columnCount).map((header) => (
              <span key={header}>{header}</span>
            ))}
          </div>
        ) : null}
        {data.rows.map((row, index) => (
          <div
            key={`${row[0]}-${index}`}
            className={`grid grid-cols-1 gap-2 border-b px-4 py-4 text-sm last:border-b-0 ${gridClass}`}
            style={{ borderColor: '#E8DDD5', background: index % 2 === 0 ? '#FAF5F0' : '#fff' }}
          >
            {row.slice(0, columnCount).map((cell, cellIndex) => (
              <p key={`${cell}-${cellIndex}`} className={cellIndex === 0 ? 'font-black text-[#1C0A12]' : 'text-[#7A5C65]'}>
                {cell}
              </p>
            ))}
          </div>
        ))}
      </div>
    );
  }

  if (block.block_type === 'correction_table' && Array.isArray(data.rows)) {
    return (
      <div className="my-7 overflow-hidden rounded-2xl border bg-white" style={{ borderColor: '#E8DDD5' }}>
        <div className="grid grid-cols-1 gap-2 px-4 py-3 text-[10px] font-black uppercase tracking-widest text-white sm:grid-cols-[0.85fr_0.85fr_1.2fr]" style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}>
          <span>{data.heading_wrong || 'Original'}</span>
          <span>{data.heading_right || 'Correction'}</span>
          <span>{data.heading_reason || 'Why'}</span>
        </div>
        {data.rows.map((row, index) => (
          <div key={`${row[0]}-${index}`} className="grid grid-cols-1 gap-2 border-b px-4 py-4 text-sm last:border-b-0 sm:grid-cols-[0.85fr_0.85fr_1.2fr]" style={{ borderColor: '#E8DDD5', background: index % 2 === 0 ? '#FAF5F0' : '#fff' }}>
            <p className="font-bold text-red-700">{row[0]}</p>
            <p className="font-bold text-emerald-700">{row[1]}</p>
            <p className="text-[#7A5C65]">{row[2]}</p>
          </div>
        ))}
      </div>
    );
  }

  if (block.block_type === 'phrase_table' && Array.isArray(data.items)) {
    return (
      <div className="my-5 overflow-hidden rounded-2xl border" style={{ borderColor: '#E8DDD5' }}>
        {data.items.map((item, index) => (
          <div key={`${item[0]}-${index}`} className="flex items-start gap-4 border-b px-5 py-3.5 last:border-b-0" style={{ borderColor: '#E8DDD5', background: index % 2 === 0 ? '#FAF5F0' : '#fff' }}>
            <p className="flex-1 text-sm font-bold italic text-[#1C0A12]">{`"${item[0]}"`}</p>
            <p className="w-48 flex-shrink-0 text-xs text-[#7A5C65]">{item[1]}</p>
          </div>
        ))}
      </div>
    );
  }

  if (block.block_type === 'progress_bars' && Array.isArray(data.items)) {
    return (
      <div className="my-8 rounded-3xl border bg-white p-5 sm:p-6" style={{ borderColor: '#E8DDD5' }}>
        <h3 className="font-black text-[#1C0A12]">{data.title || 'Trend'}</h3>
        {data.subtitle ? <p className="mt-1 text-xs text-[#7A5C65]">{data.subtitle}</p> : null}
        <div className="mt-5 space-y-4">
          {data.items.map((item) => {
            const percent = Math.max(0, Math.min(100, Number(String(item[1] || '').replace('%', '')) || 0));
            return (
              <div key={item[0]}>
                <div className="mb-1 flex justify-between gap-3 text-xs font-bold">
                  <span className="text-[#1C0A12]">{item[0]}</span>
                  <span style={{ color: MID }}>{item[1]}</span>
                </div>
                <div className="h-3 overflow-hidden rounded-full bg-[#E8DDD5]">
                  <div className="cv-progress-bar h-full rounded-full" data-width={percent} style={{ width: '0%', background: `linear-gradient(90deg, ${MID}, ${ACCENT})`, transition: 'width 1.1s cubic-bezier(.22,.9,.28,1)' }} />
                </div>
                {item[2] ? <p className="mt-1.5 text-[11px] leading-relaxed text-[#7A5C65]">{item[2]}</p> : null}
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  if (block.block_type === 'essay_box' && Array.isArray(data.paragraphs)) {
    return (
      <div className="my-5 space-y-4 rounded-3xl border bg-white p-5 sm:p-6" style={{ borderColor: '#E8DDD5' }}>
        {data.paragraphs.map((paragraph) => (
          <p key={paragraph} className="leading-relaxed text-[#3D2030]">{paragraph}</p>
        ))}
      </div>
    );
  }

  if (block.block_type === 'simple_rows' && Array.isArray(data.rows)) {
    return (
      <div className="my-7 overflow-hidden rounded-2xl border bg-white" style={{ borderColor: '#E8DDD5' }}>
        {data.rows.map((row, index) => (
          <div
            key={`${row[0]}-${index}`}
            className="grid gap-3 border-b px-5 py-4 last:border-b-0 sm:grid-cols-[0.7fr_1.5fr]"
            style={{ borderColor: '#E8DDD5', background: index % 2 === 0 ? '#fff' : '#FFFBEB' }}
          >
            <p className="font-black text-[#1C0A12]">{row[0]}</p>
            <p className="text-sm text-[#7A5C65]">{row[1]}</p>
          </div>
        ))}
      </div>
    );
  }

  if (block.block_type === 'numbered_list' && Array.isArray(data.items)) {
    return (
      <ol className="my-6 space-y-3">
        {data.items.map((item, index) => (
          <li key={item} className="flex gap-3 rounded-2xl border bg-white p-4" style={{ borderColor: '#E8DDD5' }}>
            <span className="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-full text-xs font-black text-white" style={{ background: MID }}>
              {index + 1}
            </span>
            <span className="text-sm leading-relaxed text-[#3D2030]">{item}</span>
          </li>
        ))}
      </ol>
    );
  }

  if (block.block_type === 'mini_practice') {
    return (
      <div id="cvMiniPractice" className="my-10 overflow-hidden rounded-[28px] border bg-white" style={{ borderColor: `${MID}30` }}>
        <div className="flex items-center gap-3 px-6 py-5" style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}>
          <FileText className="h-5 w-5" style={{ color: ACCENT }} />
          <p className="text-sm font-black uppercase tracking-widest text-white sm:text-base">{data.label || data.title || 'Mini Practice'}</p>
        </div>
        <div id="cvMiniPracticeBody" className="p-6 sm:p-8">
          <p className="text-lg font-black leading-snug text-[#1C0A12] sm:text-xl">{data.prompt || data.text || data.sentence}</p>
          {data.hint ? <p className="mt-3 text-sm text-[#7A5C65]">{data.hint}</p> : null}
          <textarea
            id="cvPracticeAnswer"
            className="mt-5 w-full resize-none rounded-xl border px-4 py-3 text-sm text-[#1C0A12] outline-none transition-colors placeholder:text-[#7A5C65] focus:border-[#4A1429]"
            rows={3}
            placeholder={data.placeholder || 'Type your answer here...'}
            style={{ borderColor: '#E8DDD5', background: '#FAF5F0' }}
          />
          <button id="cvPracticeBtn" type="button" className="mt-3 rounded-xl px-5 py-2.5 text-xs font-extrabold text-white transition-all hover:scale-105" style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}>
            Submit Answer
          </button>
        </div>
      </div>
    );
  }

  if (block.block_type === 'practice_plan' && Array.isArray(data.items)) {
    return (
      <div className="my-5 overflow-hidden rounded-2xl border" style={{ borderColor: '#E8DDD5' }}>
        {data.items.map((item, index) => (
          <div key={`${item[0]}-${index}`} className="flex items-center gap-4 border-b px-5 py-4 last:border-b-0" style={{ borderColor: '#E8DDD5', background: index % 2 === 0 ? '#FAF5F0' : '#fff' }}>
            <div className="flex h-8 w-14 flex-shrink-0 items-center justify-center rounded-lg text-xs font-extrabold" style={{ background: `${ACCENT}20`, color: MID }}>{item[0]}</div>
            <p className="text-sm text-[#1C0A12]">{item[1]}</p>
          </div>
        ))}
      </div>
    );
  }

  if (block.block_type === 'before_after') {
    return (
      <div className="my-7 overflow-hidden rounded-2xl border" style={{ borderColor: '#E8DDD5' }}>
        <div className="border-b bg-gray-50 px-4 py-2.5" style={{ borderColor: '#E8DDD5' }}>
          <p className="text-xs font-extrabold uppercase tracking-widest text-[#7A5C65]">Before vs After</p>
        </div>
        <div className="grid sm:grid-cols-2">
          <div className="border-b p-5 sm:border-b-0 sm:border-r" style={{ borderColor: '#E8DDD5' }}>
            <p className="mb-2 text-[10px] font-bold uppercase text-red-400">Before</p>
            <p className="text-sm italic leading-relaxed text-[#7A5C65]">{`"${data.before}"`}</p>
          </div>
          <div className="p-5">
            <p className="mb-2 text-[10px] font-bold uppercase text-emerald-500">After</p>
            <p className="text-sm font-semibold italic leading-relaxed text-[#1C0A12]">{`"${data.after}"`}</p>
          </div>
        </div>
      </div>
    );
  }

  if (block.block_type === 'cta' || block.block_type === 'ai_practice_cta') {
    const ai = block.block_type === 'ai_practice_cta';
    return (
      <div className="my-10 overflow-hidden rounded-3xl border shadow-lg" style={{ borderColor: '#D4B03840' }}>
        <div className="px-6 py-7 text-center" style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}>
          {ai ? <Mic className="mx-auto mb-3 h-9 w-9" style={{ color: ACCENT }} /> : null}
          <h3 className="mb-2 text-xl font-extrabold text-white">{data.title || (ai ? 'Put This Into Practice - Right Now' : 'Want to improve faster?')}</h3>
          <p className="mx-auto mb-5 max-w-md text-sm leading-relaxed text-white/70">{data.text || 'Live programmes, AI speaking practice, certified trainers, and a global community.'}</p>
          <div className="flex flex-col items-center justify-center gap-3 sm:flex-row">
            <a href={data.primary_url || '/certifications'} target="_blank" rel="noreferrer" className="flex items-center gap-2.5 rounded-2xl px-6 py-3.5 text-sm font-extrabold text-[#4A1429] shadow-lg transition-all hover:scale-105" style={{ background: `linear-gradient(135deg, ${ACCENT}, #F5D060)` }}>
              {data.primary_label || (ai ? 'Start Speaking Practice' : 'View Programmes')}
            </a>
            <a href={data.secondary_url || WA_LINK} target="_blank" rel="noreferrer" className="flex items-center gap-2.5 rounded-2xl border border-white/20 px-6 py-3.5 text-sm font-bold text-white transition-all hover:bg-white/10">
              {data.secondary_label || 'Ask Us on WhatsApp'}
            </a>
          </div>
          {data.footnote ? <p className="mt-4 text-xs text-white/30">{data.footnote}</p> : null}
        </div>
        {ai ? (
          <div className="flex items-center justify-between gap-4 px-6 py-4" style={{ background: '#FFFBEB', borderTop: '1px solid #FDE68A' }}>
            <p className="text-xs font-semibold text-amber-800">Know someone who needs this? Share this article.</p>
            <button type="button" data-cv-share className="flex flex-shrink-0 items-center gap-1.5 rounded-xl px-3 py-2 text-xs font-extrabold text-white transition-all hover:opacity-80" style={{ background: '#25D366' }}>
              <Share2 className="h-3 w-3" /> WhatsApp
            </button>
          </div>
        ) : null}
      </div>
    );
  }

  return data.text ? <p>{data.text}</p> : null;
}

function HtmlFallback({ post }) {
  const sections = postSections(post);
  if (sections.length) {
    return sections.map((section) => (
      <section key={section.id} id={section.id}>
        {section.heading ? <h2>{section.heading}</h2> : null}
        <div dangerouslySetInnerHTML={{ __html: section.body }} />
      </section>
    ));
  }

  return <div dangerouslySetInnerHTML={{ __html: post.content || '<p>Article content coming soon.</p>' }} />;
}

function RelatedCard({ post }) {
  const image = blogSmallImage(post);
  const category = blogCategory(post);

  return (
    <article className="overflow-hidden rounded-2xl border bg-white shadow-sm transition hover:shadow-lg" style={{ borderColor: '#E8DDD5' }}>
      <Link href={blogPostUrl(post)} className="block">
        <div className="h-40 bg-[#F5EFE8]">
          {image ? <img src={image} alt={cleanText(post.alt, post.title)} className="h-full w-full object-cover" /> : null}
        </div>
        <div className="p-5">
          <span className="text-xs font-black uppercase tracking-widest" style={{ color: category.color }}>
            {category.emoji} {category.name}
          </span>
          <h3 className="mt-2 line-clamp-2 text-base font-black leading-tight text-[#1C0A12]">{post.title}</h3>
          <p className="mt-3 line-clamp-2 text-sm leading-relaxed text-[#7A5C65]">{blogExcerpt(post, 110)}</p>
        </div>
      </Link>
    </article>
  );
}

export default async function BlogPostPage({ params, searchParams }) {
  const resolvedParams = await params;
  const slugParts = Array.isArray(resolvedParams.slug) ? resolvedParams.slug : [resolvedParams.slug];
  const postSlug = slugParts.at(-1);

  if (slugParts.length === 1) {
    const categories = await getBlogCategories();
    if (categories.some((category) => category.slug === postSlug)) {
      return <BlogPage searchParams={searchParams} categorySlug={postSlug} />;
    }
  }

  const staticPost = getStaticBlogPostBySlug(postSlug);
  const StaticBlogComponent = STATIC_BLOG_COMPONENTS[postSlug];

  if (staticPost && StaticBlogComponent) {
    return <StaticBlogComponent />;
  }

  const post = await getBlogPostBySlug(postSlug);
  if (!post) notFound();

  const [blocks, relatedPosts] = await Promise.all([getBlogBlocks(post.id), getRelatedBlogPosts(post)]);
  const category = blogCategory(post);
  const image = blogImage(post);
  const quickSummary = parseJsonList(post.quick_summary);
  const recapPoints = parseJsonList(post.recap_points);
  const toc = blocks
    .filter((block) => block.block_type === 'heading')
    .map((block) => parseBlockContent(block.content))
    .filter((item) => item.id && (item.toc_label || item.title));

  const articleSchema = {
    '@context': 'https://schema.org',
    '@type': 'Article',
    headline: cleanText(post.title),
    description: blogExcerpt(post, 155),
    image: blogImage(post) || undefined,
    datePublished: post.created_at ? new Date(post.created_at).toISOString() : undefined,
    dateModified: (post.updated_at || post.created_at) ? new Date(post.updated_at || post.created_at).toISOString() : undefined,
    author: { '@type': 'Organization', name: 'Cambridge Veritas', url: 'https://cambridgeveritas.com' },
    publisher: {
      '@type': 'Organization',
      name: 'Cambridge Veritas',
      logo: { '@type': 'ImageObject', url: 'https://cambridgeveritas.com/logo/White%20logo.png' },
    },
    mainEntityOfPage: { '@type': 'WebPage', '@id': `${APP_URL}/blog/${blogCategory(post).slug}/${post.slug}` },
  };

  const breadcrumbSchema = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      { '@type': 'ListItem', position: 1, name: 'Home', item: APP_URL },
      { '@type': 'ListItem', position: 2, name: 'Blog', item: `${APP_URL}/blog` },
      { '@type': 'ListItem', position: 3, name: cleanText(post.title), item: `${APP_URL}/blog/${blogCategory(post).slug}/${post.slug}` },
    ],
  };

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(articleSchema) }} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }} />
      <BlogPostClient postTitle={post.title} />
      <style>{`
        .cv-progress-fill,.cv-mini-progress-fill,.cv-toc-progress-fill{width:0%}
        .cv-bookmark-saved{border-color:${ACCENT}!important;background:${ACCENT}15!important}
        .cv-bookmark-saved svg{color:${ACCENT}!important;fill:${ACCENT}!important}
        .cv-toc-link.active{color:${MID}!important;background:${MID}10!important;border-left:2px solid ${ACCENT}!important}
        .cv-scroll-reveal{opacity:0;transform:translateY(18px);transition:opacity .55s ease,transform .55s ease;will-change:opacity,transform}
        .cv-scroll-reveal.cv-revealed{opacity:1;transform:translateY(0)}
        @media (prefers-reduced-motion:reduce){.cv-scroll-reveal{opacity:1;transform:none;transition:none}}
      `}</style>
      <CVHeader />
      <div className="h-1 w-full" style={{ background: `linear-gradient(90deg, ${MID}, ${ACCENT}, ${category.color})` }} />
      <div className="fixed left-0 right-0 top-0 z-50 h-0.5 bg-transparent">
        <div className="cv-progress-fill h-full" style={{ background: `linear-gradient(90deg, ${MID}, ${ACCENT})` }} />
      </div>

      <div className="sticky top-0 z-30 border-b bg-white/95 backdrop-blur-sm" style={{ borderColor: '#E8DDD5' }}>
        <div className="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3 sm:px-6">
          <div className="flex min-w-0 items-center gap-3 text-sm text-[#7A5C65]">
            <Link href="/blog" className="flex flex-shrink-0 items-center gap-1.5 font-semibold transition-colors hover:text-[#4A1429]">
              <ArrowLeft className="h-4 w-4" /> All Blogs
            </Link>
            <ChevronRight className="hidden h-3.5 w-3.5 flex-shrink-0 text-[#E8DDD5] sm:block" />
            <span className="hidden truncate text-xs font-medium text-[#4A1429] sm:block">{post.title}</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="hidden items-center gap-1.5 text-xs font-semibold text-[#7A5C65] sm:flex">
              <div className="h-1 w-20 rounded-full bg-[#E8DDD5]">
                <div className="cv-mini-progress-fill h-full rounded-full transition-all duration-300" style={{ background: ACCENT }} />
              </div>
              <span className="cv-progress-text">0%</span>
            </div>
            <button id="cvBookmark" type="button" className="rounded-xl border p-2 transition-all" style={{ borderColor: '#E8DDD5', background: 'white' }}>
              <Bookmark className="h-4 w-4 text-[#7A5C65]" />
            </button>
            <button id="cvShare" type="button" data-cv-share className="flex items-center gap-1.5 rounded-xl border px-3 py-2 text-xs font-bold transition-all hover:scale-105" style={{ borderColor: '#25D36630', background: '#25D36610', color: '#128C7E' }}>
              <Share2 className="h-3.5 w-3.5" /> Share
            </button>
          </div>
        </div>
        <div className="mx-auto flex max-w-7xl items-center gap-1 px-4 pb-2 text-[10px] text-[#7A5C65] sm:px-6">
          <Link href="/" className="hover:text-[#4A1429]">Home</Link>
          <ChevronRight className="h-3 w-3" />
          <Link href="/blog" className="hover:text-[#4A1429]">Blogs</Link>
          <ChevronRight className="h-3 w-3" />
          <span className="truncate font-semibold text-[#4A1429]">{post.title}</span>
        </div>
      </div>

      <main className="mx-auto max-w-7xl px-4 py-8 sm:px-6 sm:py-12">
        <div className="flex gap-8">
          <aside className="hidden w-60 flex-shrink-0 xl:block">
            <div className="sticky top-28 rounded-2xl border bg-white p-5" style={{ borderColor: '#E8DDD5' }}>
              <p className="mb-4 text-[10px] font-extrabold uppercase tracking-widest text-[#7A5C65]">In This Article</p>
              <nav className="space-y-1">
                {toc.length ? (
                  toc.map((item) => (
                    <a
                      key={item.id}
                      href={`#${item.id}`}
                      data-toc-link={item.id}
                      className="cv-toc-link block rounded-lg px-3 py-1.5 text-xs font-medium text-[#7A5C65] transition-all hover:bg-[#F5EFE8] hover:text-[#4A1429]"
                    >
                      {item.toc_label || item.title}
                    </a>
                  ))
                ) : (
                  <span className="text-xs text-[#7A5C65]">Article</span>
                )}
              </nav>
              <div className="mt-5 border-t pt-5" style={{ borderColor: '#E8DDD5' }}>
                <p className="mb-2 text-[10px] text-[#7A5C65]">Reading time</p>
                <div className="flex items-center gap-2">
                  <Clock className="h-3.5 w-3.5 text-[#7A5C65]" />
                  <span className="text-xs font-bold text-[#1C0A12]">{blogReadTime(post)} min</span>
                </div>
                <div className="mt-3 h-1.5 rounded-full bg-[#E8DDD5]">
                  <div className="cv-toc-progress-fill h-full rounded-full transition-all" style={{ background: ACCENT }} />
                </div>
              </div>
            </div>
          </aside>

          <article id="cvArticle" className="min-w-0 flex-1">
            <div className="max-w-3xl">
              <div className="cv-enter">
              <div className="mb-4 flex flex-wrap items-center gap-2">
                <span
                  className="inline-flex items-center gap-1 rounded-full px-3 py-1.5 text-xs font-extrabold uppercase tracking-widest"
                  style={{ background: `${category.color}15`, color: category.color, border: `1px solid ${category.color}30` }}
                >
                  {category.emoji} {category.name}
                </span>
                <span className="flex items-center gap-1 text-xs text-[#7A5C65]">
                  <Clock className="h-3.5 w-3.5" /> {blogReadTime(post)} min read
                </span>
                <span className="text-xs text-[#7A5C65]">{blogDate(post)}</span>
              </div>

              <h1 className="mb-4 text-2xl font-black leading-tight text-[#1C0A12] sm:text-4xl">{post.title}</h1>
              <p className="mb-7 text-base leading-relaxed text-[#7A5C65] sm:text-lg">{blogExcerpt(post, 260)}</p>
              <div className="mb-7 flex items-center gap-3 border-b pb-7" style={{ borderColor: '#E8DDD5' }}>
                <div className="flex h-9 w-9 items-center justify-center rounded-full text-sm font-black text-white" style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}>CV</div>
                <div>
                  <p className="text-xs font-bold text-[#1C0A12]">Cambridge Veritas Team</p>
                  <p className="text-[10px] text-[#7A5C65]">English & IELTS Specialists</p>
                </div>
              </div>
              </div>

              {image ? (
                <div className="cv-hero-image mb-8 overflow-hidden rounded-3xl shadow-lg">
                  <img src={image} alt={cleanText(post.alt, post.title)} className="h-56 w-full object-cover sm:h-80" />
                  <div className="border-t bg-white px-4 py-2.5" style={{ borderColor: '#E8DDD5' }}>
                    <p className="text-xs italic text-[#7A5C65]">{cleanText(post.alt, 'Cambridge Veritas learning article')}</p>
                  </div>
                </div>
              ) : null}

              <SummaryBox points={quickSummary} fallback={post.summary} />

              <div className="prose-custom space-y-5 text-[15px] leading-[1.85] text-[#3D2030] [&_a]:font-bold [&_a]:text-[#4A1429] [&_h2]:mt-10 [&_h2]:text-xl [&_h2]:font-black [&_h2]:leading-snug [&_h2]:text-[#1C0A12] [&_h3]:mt-7 [&_h3]:font-black [&_h3]:text-[#1C0A12] [&_li]:mb-2 [&_ol]:ml-5 [&_ul]:ml-5">
                {blocks.length ? blocks.map((block) => <BlockRenderer key={block.id} block={block} />) : <HtmlFallback post={post} />}

                {recapPoints.length ? (
                  <div className="mt-10 rounded-2xl border p-6" style={{ background: `${MID}08`, borderColor: `${MID}25` }}>
                    <p className="mb-4 text-xs font-extrabold uppercase tracking-widest" style={{ color: MID }}>Article Recap</p>
                    <div className="space-y-2">
                      {recapPoints.map((point, index) => (
                        <div key={point} className="flex items-center gap-3">
                          <div className="flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full text-[10px] font-extrabold text-white" style={{ background: MID }}>{index + 1}</div>
                          <p className="text-sm text-[#1C0A12]">{point}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : null}
              </div>

              <div className="mt-10 overflow-hidden rounded-3xl border shadow-lg" style={{ borderColor: '#D4B03840' }}>
                <div className="px-6 py-7 text-center" style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)' }}>
                  <BookOpen className="mx-auto mb-3 h-9 w-9" style={{ color: ACCENT }} />
                  <h3 className="mb-2 text-xl font-extrabold text-white">Build stronger English with Cambridge Veritas</h3>
                  <p className="mx-auto mb-5 max-w-md text-sm leading-relaxed text-white/70">
                    Explore certifications, live classes, AI practice tools, and expert support for your next step.
                  </p>
                  <div className="flex flex-col items-center justify-center gap-3 sm:flex-row">
                    <Link
                      href="/certifications"
                      className="flex items-center gap-2.5 rounded-2xl px-6 py-3.5 text-sm font-extrabold text-[#4A1429] shadow-lg transition-all hover:scale-105"
                      style={{ background: 'linear-gradient(135deg, #D4B038, #F5D060)' }}
                    >
                      <BookOpen className="h-4 w-4" /> View Programmes
                    </Link>
                    <a
                      href={WA_LINK}
                      target="_blank"
                      rel="noreferrer"
                      className="flex items-center gap-2.5 rounded-2xl border border-white/20 px-6 py-3.5 text-sm font-bold text-white transition-all hover:bg-white/10"
                    >
                      <MessageCircle className="h-4 w-4" /> Ask Us
                    </a>
                  </div>
                </div>
              </div>

              <div className="mt-12 border-t pt-8 text-center" style={{ borderColor: '#E8DDD5' }}>
                <Link
                  href="/blog"
                  className="inline-flex items-center gap-2 rounded-2xl px-7 py-3.5 text-sm font-extrabold text-white transition-all hover:scale-105"
                  style={{ background: `linear-gradient(135deg, ${MID}, #6B1E3D)` }}
                >
                  <BookOpen className="h-4 w-4" /> Browse All Articles
                </Link>
              </div>
            </div>
          </article>
        </div>

        {relatedPosts.length ? (
          <section className="mt-14 border-t pt-10" style={{ borderColor: '#E8DDD5' }}>
            <div className="mb-6 flex items-end justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-widest text-[#8B1C1C]">Recommended</p>
                <h2 className="mt-2 text-2xl font-black text-[#1C0A12]">Related articles</h2>
              </div>
              <Link href="/blog" className="hidden items-center gap-2 text-sm font-black text-[#4A1429] sm:inline-flex">
                Show all <ArrowRight className="h-4 w-4" />
              </Link>
            </div>
            <div className="grid gap-6 md:grid-cols-3">
              {relatedPosts.map((item) => (
                <RelatedCard key={item.id} post={item} />
              ))}
            </div>
          </section>
        ) : null}
      </main>

      <div
        className="hidden fixed bottom-6 left-1/2 z-50 w-[90%] max-w-[760px] -translate-x-1/2 items-center gap-5 rounded-2xl px-6 py-4 shadow-2xl md:flex"
        style={{ background: `linear-gradient(135deg, ${DARK}, ${MID})`, border: `1px solid ${ACCENT}40` }}
      >
        <div className="min-w-0 flex-1">
          <p className="text-sm font-extrabold 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/60">Trusted by 14,000+ graduates worldwide</span>
          </div>
        </div>
        <Link
          href="/certifications"
          className="flex-shrink-0 whitespace-nowrap rounded-xl px-5 py-2.5 text-xs font-extrabold text-[#1C0A12] transition-all hover:scale-105"
          style={{ background: `linear-gradient(135deg, ${ACCENT}, #F5D060)` }}
        >
          View Programmes
        </Link>
      </div>
      <div className="fixed bottom-0 left-0 right-0 z-50 flex items-center gap-3 px-4 py-3 md:hidden" style={{ background: `linear-gradient(135deg, ${DARK}, ${MID})`, borderTop: `1px solid ${ACCENT}40` }}>
        <div className="min-w-0 flex-1">
          <p className="truncate text-xs font-bold text-white">Join Cambridge Veritas</p>
          <div className="flex items-center gap-1">
            {[...Array(5)].map((_, index) => (
              <Star key={index} className="h-2.5 w-2.5 fill-current" style={{ color: ACCENT }} />
            ))}
            <span className="ml-1 text-[10px] text-white/50">14k+ graduates</span>
          </div>
        </div>
        <Link href="/certifications" className="flex-shrink-0 rounded-xl px-4 py-2 text-xs font-extrabold text-[#1C0A12]" style={{ background: `linear-gradient(135deg, ${ACCENT}, #F5D060)` }}>
          Programmes
        </Link>
        <a href={WA_LINK} target="_blank" rel="noreferrer" className="flex-shrink-0 rounded-xl border border-white/30 px-3 py-2 text-xs font-bold text-white">
          Chat
        </a>
      </div>

      <CVFooter />
    </div>
  );
}
