/* 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,
} from 'lucide-react';
import CVHeader from '@/components/layout/CVHeader';
import CVFooter from '@/components/layout/CVFooter';
import CertificationClusterArticle from '@/components/blog/CertificationClusterArticle';
import TesolClusterArticle from '@/components/blog/TesolClusterArticle';
import SeoClusterArticle, { buildSeoArticleMetadata } from '@/components/seo/SeoClusterArticle';
import BlogPostClient from '../BlogPostClient';
import BlogPage, { getBlogHubMetadata } 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 { buildContentMetadata, getContentMetadataForRequest, getRequestMetadataInput } from '@/lib/siteSeo';
import { MAIN_SITE_URL } from '@/lib/mainSiteUrl';
import { CVAF_ARTICLES, CVAF_CATEGORIES, getCvafArticleBySlug } from '@/data/seo/cvafArticles';
import { STRATEGY_ARTICLES, STRATEGY_CATEGORIES, getStrategyArticleBySlug } from '@/data/seo/strategyArticles';
import { getTesolClusterPageBySlug } from '@/data/blog/tesolClusterPages';
import {
  CERTIFICATION_ARTICLE_CLUSTERS,
  getCertificationArticleBySlug,
} from '@/data/blog/certificationArticleClusters';
import {
  TESOL_GROWTH_ARTICLES,
  getTesolGrowthArticleBySlug,
} from '@/data/seo/tesolGrowthArticles';
import {
  ALGEBRA_BLOG_CATEGORY,
  ALGEBRA_GROWTH_ARTICLES,
  getAlgebraGrowthArticleBySlug,
} from '@/data/seo/algebraGrowthArticles';
import {
  applyTesolIndiaGuideArchitecture,
  TESOL_INDIA_GUIDE_PATH,
  TESOL_INDIA_GUIDE_SEO,
  TESOL_INDIA_GUIDE_SLUG,
} from '@/lib/tesolKeywordArchitecture';

const APP_URL = MAIN_SITE_URL;

export async function generateMetadata({ 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 strategyCategory = STRATEGY_CATEGORIES.find((category) => category.slug === postSlug);
    if (strategyCategory && !['ielts', 'career-english'].includes(postSlug)) return getBlogHubMetadata({ searchParams, categorySlug: postSlug, categoryName: strategyCategory.name });
    const cvafCategory = CVAF_CATEGORIES.find((category) => category.slug === postSlug);
    if (cvafCategory) return getBlogHubMetadata({ searchParams, categorySlug: postSlug, categoryName: cvafCategory.name });
    if (postSlug === ALGEBRA_BLOG_CATEGORY.slug) {
      return getBlogHubMetadata({
        searchParams,
        categorySlug: postSlug,
        categoryName: ALGEBRA_BLOG_CATEGORY.name,
      });
    }

    const certificationCluster = CERTIFICATION_ARTICLE_CLUSTERS.find(
      (cluster) => cluster.category.slug === postSlug
    );
    if (certificationCluster) {
      return getBlogHubMetadata({
        searchParams,
        categorySlug: postSlug,
        categoryName: certificationCluster.category.name,
      });
    }

    const categories = await getBlogCategories().catch(() => []);
    const category = categories.find((item) => item.slug === postSlug);
    if (category) {
      return getBlogHubMetadata({ searchParams, categorySlug: category.slug, categoryName: category.name });
    }
  }

  const growthArticle =
    getStrategyArticleBySlug(postSlug) || getTesolGrowthArticleBySlug(postSlug) || getAlgebraGrowthArticleBySlug(postSlug) || getCvafArticleBySlug(postSlug);
  if (growthArticle) return buildSeoArticleMetadata(growthArticle);

  const post = getStaticBlogPostBySlug(postSlug) || await getBlogPostBySlug(postSlug);
  if (!post) return {};

  const category = blogCategory(post);
  const image = blogImage(post);
  if (postSlug === TESOL_INDIA_GUIDE_SLUG) {
    return buildContentMetadata({
      ...getRequestMetadataInput(await headers(), {
        pathname: TESOL_INDIA_GUIDE_PATH,
      }),
      title: TESOL_INDIA_GUIDE_SEO.title,
      description: TESOL_INDIA_GUIDE_SEO.description,
      keywords: TESOL_INDIA_GUIDE_SEO.keywords,
      emitKeywords: false,
      image,
      imageAlt: cleanText(post.alt, TESOL_INDIA_GUIDE_SEO.heading),
      type: 'article',
      publishedTime: post.created_at ? new Date(post.created_at).toISOString() : undefined,
      modifiedTime: (post.updated_at || post.modify_at)
        ? new Date(post.updated_at || post.modify_at).toISOString()
        : undefined,
      section: category.name,
    });
  }

  const excerpt = cleanText(post.meta_description) || blogExcerpt(post, 155);
  const title = cleanText(post.meta_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),
    emitKeywords: false,
    image,
    imageAlt: cleanText(post.alt, post.title),
    type: 'article',
    publishedTime: post.created_at ? new Date(post.created_at).toISOString() : undefined,
    modifiedTime: (post.updated_at || post.modify_at) ? new Date(post.updated_at || post.modify_at).toISOString() : undefined,
    section: category.name,
  });
}

const DARK = '#2D0A18';
const MID = '#4A1429';
const ACCENT = '#D4B038';
const WA_LINK = 'https://wa.me/message/SPLHYUJO22RDI1';
const IELTS_PREPARATION_LINKS = {
  'ielts-wrong-essay-can-you-correct-it': 'IELTS preparation with writing feedback',
  'how-can-i-improve-my-ielts-writing-skills-simple-tricks-that-work': 'live IELTS course with trainer feedback',
  'understanding-the-cefr-alignment-with-ielts-scores-insights-for-institutions-and-test-takers': 'structured IELTS preparation',
  'strategies-to-ace-the-ielts-exam-tips-for-success': 'online IELTS preparation course',
};
const MEDICAL_ENGLISH_LINKS = {
  'clinical-communication-in-english-a-practical-guide-for-doctors': 'live medical English course for doctors',
  'medical-english-for-doctors-complete-guide-to-clinical-communication-125': 'structured medical English training',
  'why-english-fluency-is-a-game-changer-for-doctors-worldwide': 'English communication training for healthcare professionals',
};
const ESP_HUB_LINKS = {
  'understanding-english-for-specific-purposes-esp-a-comprehensive-guide': 'English for Specific Purposes courses',
};
const IELTS_STRATEGIES_SLUG = 'strategies-to-ace-the-ielts-exam-tips-for-success';

function correctIeltsStrategiesContent(value) {
  if (typeof value !== 'string') return value;

  return value
    .replace(
      /Scores depend on four rules:\s*Familiarity and Intelligence,\s*Lexical Asset,\s*Linguistic Reach and Exactness,\s*and Articulation\.\s*Every measure is scored on a size of 0-9,\s*and the scores are found the middle value of to give a general Speaking Band Score\.?/gi,
      'Scores are based on four assessment criteria: fluency and coherence, lexical resource, grammatical range and accuracy, and pronunciation. Each criterion is scored on a band scale from 0 to 9, and the four scores are averaged to calculate the overall Speaking band score.',
    )
    .replace(/Global English Language Testing Framework/gi, 'International English Language Testing System');
}

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>
  );
}

function editorialDate(value) {
  if (!value) return '';
  return new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(value));
}

function isoDate(value) {
  if (!value) return undefined;
  const parsed = new Date(value);
  return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();
}

function BlogStructuredData({ post }) {
  const category = blogCategory(post);
  const pageUrl = `${APP_URL}/blog/${category.slug}/${post.slug}`;
  const description = cleanText(post.meta_description) || blogExcerpt(post, 155);
  const image = blogImage(post) || undefined;
  const published = isoDate(post.created_at);
  const modified = isoDate(post.updated_at || post.modify_at || post.created_at);
  const articleSchema = {
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    '@id': `${pageUrl}#article`,
    url: pageUrl,
    headline: cleanText(post.title),
    description,
    ...(image ? { image } : {}),
    ...(published ? { datePublished: published } : {}),
    ...(modified ? { dateModified: modified } : {}),
    inLanguage: 'en',
    articleSection: category.name,
    isPartOf: { '@id': `${APP_URL}/#website` },
    mainEntityOfPage: { '@type': 'WebPage', '@id': pageUrl },
    author: { '@id': `${APP_URL}/#organization` },
    publisher: { '@id': `${APP_URL}/#organization` },
  };
  const breadcrumbSchema = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    '@id': `${pageUrl}#breadcrumb`,
    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: category.name, item: `${APP_URL}/blog/${category.slug}` },
      { '@type': 'ListItem', position: 4, name: cleanText(post.title), item: pageUrl },
    ],
  };
  const safeJsonLd = (value) => JSON.stringify(value).replace(/</g, '\\u003c');

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: safeJsonLd(articleSchema) }} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbSchema) }} />
    </>
  );
}

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);
  const ieltsPreparationLinkLabel = IELTS_PREPARATION_LINKS[postSlug];
  const medicalEnglishLinkLabel = MEDICAL_ENGLISH_LINKS[postSlug];
  const espHubLinkLabel = ESP_HUB_LINKS[postSlug];

  if (slugParts.length === 1) {
    if (CVAF_CATEGORIES.some((category) => category.slug === postSlug) || STRATEGY_CATEGORIES.some((category) => category.slug === postSlug)) {
      return <BlogPage searchParams={searchParams} categorySlug={postSlug} />;
    }
    const hasStaticCategory = CERTIFICATION_ARTICLE_CLUSTERS.some(
      (cluster) => cluster.category.slug === postSlug
    ) || postSlug === ALGEBRA_BLOG_CATEGORY.slug;
    const categories = hasStaticCategory
      ? []
      : await getBlogCategories().catch(() => []);
    if (hasStaticCategory || categories.some((category) => category.slug === postSlug)) {
      return <BlogPage searchParams={searchParams} categorySlug={postSlug} />;
    }
  }

  const staticPost = getStaticBlogPostBySlug(postSlug);
  const StaticBlogComponent = STATIC_BLOG_COMPONENTS[postSlug];
  const certificationArticle = getCertificationArticleBySlug(postSlug);
  const tesolClusterPage = getTesolClusterPageBySlug(postSlug);
  const growthArticle = getStrategyArticleBySlug(postSlug) || getTesolGrowthArticleBySlug(postSlug) || getAlgebraGrowthArticleBySlug(postSlug) || getCvafArticleBySlug(postSlug);

  if (staticPost && certificationArticle) {
    return <CertificationClusterArticle page={certificationArticle} />;
  }

  if (staticPost && tesolClusterPage) {
    return <TesolClusterArticle page={tesolClusterPage} />;
  }

  if (staticPost && growthArticle) {
    const allArticles = growthArticle.editorialSeries ? STRATEGY_ARTICLES : growthArticle.cluster === 'cvaf' ? CVAF_ARTICLES : growthArticle.cluster === 'algebra' ? ALGEBRA_GROWTH_ARTICLES : TESOL_GROWTH_ARTICLES;
    return <SeoClusterArticle article={growthArticle} allArticles={allArticles} />;
  }

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

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

  const [blocks, relatedPosts] = await Promise.all([getBlogBlocks(post.id), getRelatedBlogPosts(post)]);
  const optimizedArticle = applyTesolIndiaGuideArchitecture(post, blocks);
  const articleBlocks = postSlug === IELTS_STRATEGIES_SLUG
    ? optimizedArticle.blocks.map((block) => ({ ...block, content: correctIeltsStrategiesContent(block.content) }))
    : optimizedArticle.blocks;
  const articlePost = postSlug === IELTS_STRATEGIES_SLUG
    ? { ...optimizedArticle.post, content: correctIeltsStrategiesContent(optimizedArticle.post.content) }
    : optimizedArticle.post;
  const category = blogCategory(articlePost);
  const isTeacherTraining = category.slug === 'teacher-training';
  const isIndiaGuide = postSlug === TESOL_INDIA_GUIDE_SLUG;
  const image = blogImage(articlePost);
  const quickSummary = parseJsonList(articlePost.quick_summary);
  const recapPoints = parseJsonList(articlePost.recap_points);
  const toc = articleBlocks
    .filter((block) => block.block_type === 'heading')
    .map((block) => parseBlockContent(block.content))
    .filter((item) => item.id && (item.toc_label || item.title));

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      <BlogStructuredData post={articlePost} />
      <BlogPostClient postTitle={articlePost.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">{articlePost.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" />
          <Link href={`/blog/${category.slug}`} className="hidden hover:text-[#4A1429] sm:inline">{category.name}</Link>
          <ChevronRight className="hidden h-3 w-3 sm:block" />
          <span className="truncate font-semibold text-[#4A1429]">{articlePost.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(articlePost)} 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(articlePost)} min read
                </span>
                <span className="text-xs text-[#7A5C65]">{blogDate(articlePost)}</span>
              </div>

              <h1 className="mb-4 text-2xl font-black leading-tight text-[#1C0A12] sm:text-4xl">{articlePost.title}</h1>
              <p className="mb-7 text-base leading-relaxed text-[#7A5C65] sm:text-lg">{blogExcerpt(articlePost, 260)}</p>
              <div className="mb-7 flex items-start 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 Editorial Team</p>
                  {isTeacherTraining ? (
                    <p className="mt-1 text-[11px] leading-relaxed text-[#7A5C65]">
                      Reviewed by <a href="https://www.linkedin.com/in/krishnatrya/" target="_blank" rel="noreferrer" className="font-bold text-[#4A1429] underline">Dr Krishnatrya</a>, teacher educator with 15+ years of experience.
                    </p>
                  ) : <p className="mt-1 text-[11px] text-[#7A5C65]">English-language education editorial team</p>}
                  <p className="mt-1 text-[10px] text-[#7A5C65]">
                    Published {editorialDate(articlePost.created_at)}{(articlePost.updated_at || articlePost.modify_at) ? ` · Last reviewed ${editorialDate(articlePost.updated_at || articlePost.modify_at)}` : ''} · <Link href="/editorial-policy" className="font-bold text-[#4A1429] underline">Editorial policy</Link>
                  </p>
                </div>
              </div>
              </div>

              {image ? (
                <div className="cv-hero-image mb-8 overflow-hidden rounded-3xl shadow-lg">
                  <img src={image} alt={cleanText(articlePost.alt, articlePost.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(articlePost.alt, 'Cambridge Veritas learning article')}</p>
                  </div>
                </div>
              ) : null}

              <SummaryBox points={quickSummary} fallback={articlePost.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">
                {articleBlocks.length ? articleBlocks.map((block) => <BlockRenderer key={block.id} block={block} />) : <HtmlFallback post={articlePost} />}

                {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>

              {ieltsPreparationLinkLabel ? (
                <aside className="mt-10 rounded-3xl border-2 border-[#D4B038]/40 bg-[#FFFBEB] p-6 text-center">
                  <p className="text-xs font-black uppercase tracking-widest text-[#8B1C1C]">Continue Your IELTS Preparation</p>
                  <h2 className="mt-2 text-xl font-black text-[#1C0A12]">Practise with Live Trainer Guidance</h2>
                  <p className="mx-auto mt-3 max-w-xl text-sm leading-relaxed text-[#7A5C65]">
                    Compare the CVIP curriculum, writing and speaking feedback, course fee and current live batches.
                  </p>
                  <Link
                    href="/certifications/cambridge-veritas-certificate-for-ielts-preparation"
                    className="mt-5 inline-flex rounded-xl bg-[#4A1429] px-6 py-3 text-sm font-extrabold text-white transition-all hover:bg-[#6B1E3D]"
                  >
                    {ieltsPreparationLinkLabel}
                  </Link>
                </aside>
              ) : null}

              {medicalEnglishLinkLabel ? (
                <aside className="mt-10 rounded-3xl border-2 border-[#D4B038]/40 bg-[#FFFBEB] p-6 text-center">
                  <p className="text-xs font-black uppercase tracking-widest text-[#8B1C1C]">Continue Your Medical English Training</p>
                  <h2 className="mt-2 text-xl font-black text-[#1C0A12]">Practise Clinical Communication Live</h2>
                  <p className="mx-auto mt-3 max-w-xl text-sm leading-relaxed text-[#7A5C65]">
                    Compare the CVMP curriculum, patient-consultation practice, trainer feedback, certificate details and current cohort information.
                  </p>
                  <Link
                    href="/certifications/cambridge-veritas-certificate-for-medical-practitioners"
                    className="mt-5 inline-flex rounded-xl bg-[#4A1429] px-6 py-3 text-sm font-extrabold text-white transition-all hover:bg-[#6B1E3D]"
                  >
                    {medicalEnglishLinkLabel}
                  </Link>
                </aside>
              ) : null}

              {espHubLinkLabel ? (
                <aside className="mt-10 rounded-3xl border-2 border-[#D4B038]/40 bg-[#FFFBEB] p-6 text-center">
                  <p className="text-xs font-black uppercase tracking-widest text-[#8B1C1C]">Explore Professional English by Industry</p>
                  <h2 className="mt-2 text-xl font-black text-[#1C0A12]">Compare Live Online ESP Pathways</h2>
                  <p className="mx-auto mt-3 max-w-xl text-sm leading-relaxed text-[#7A5C65]">Compare professional English courses for nursing, law, engineering, aviation, finance, science, hospitality, HR, sales and customer service.</p>
                  <Link href="/specializations" className="mt-5 inline-flex rounded-xl bg-[#4A1429] px-6 py-3 text-sm font-extrabold text-white transition-all hover:bg-[#6B1E3D]">{espHubLinkLabel}</Link>
                </aside>
              ) : null}

              {isTeacherTraining ? (
                <aside className="mt-10 rounded-3xl border border-[#D4B038]/40 bg-[#FFFBEB] p-6">
                  <p className="text-xs font-black uppercase tracking-widest text-[#8B1C1C]">Continue your teacher-development journey</p>
                  <h2 className="mt-2 text-xl font-black text-[#1C0A12]">From TESOL resources to assessed practice</h2>
                  <p className="mt-3 max-w-2xl text-sm leading-relaxed text-[#7A5C65]">Explore more practical guidance, compare the Cambridge Veritas TESOL certificate, and see how live teaching practice supports professional evidence.</p>
                  <div className="mt-5 flex flex-wrap gap-2">
                    <Link href="/blog/teacher-training" className="rounded-xl bg-[#4A1429] px-4 py-2.5 text-xs font-extrabold text-white">Explore more TESOL resources</Link>
                    <Link href="/free-resources" className="rounded-xl border border-[#E8DDD5] bg-white px-4 py-2.5 text-xs font-extrabold text-[#4A1429]">Free teaching resources</Link>
                    <Link href="/certifications/cambridge-veritas-certificate-in-TESOL" className="rounded-xl border border-[#E8DDD5] bg-white px-4 py-2.5 text-xs font-extrabold text-[#4A1429]">{isIndiaGuide ? 'Compare the 120-hour online TESOL certification' : 'TESOL certificate'}</Link>
                    <Link href="/masterclass" className="rounded-xl border border-[#E8DDD5] bg-white px-4 py-2.5 text-xs font-extrabold text-[#4A1429]">Compare English teacher training</Link>
                    <Link href="/about-us" className="rounded-xl border border-[#E8DDD5] bg-white px-4 py-2.5 text-xs font-extrabold text-[#4A1429]">Cambridge Veritas and its training approach</Link>
                    <Link href="/introduction-class/tesol" className="rounded-xl border border-[#E8DDD5] bg-white px-4 py-2.5 text-xs font-extrabold text-[#4A1429]">TESOL introduction class</Link>
                    <Link href="/tesol-teaching-practice" className="rounded-xl border border-[#E8DDD5] bg-white px-4 py-2.5 text-xs font-extrabold text-[#4A1429]">TESOL teaching practice</Link>
                    <Link href="/reviews#tesol-reviews" className="rounded-xl border border-[#E8DDD5] bg-white px-4 py-2.5 text-xs font-extrabold text-[#4A1429]">TESOL graduate reviews</Link>
                  </div>
                </aside>
              ) : null}

              <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={isTeacherTraining ? '/blog/teacher-training' : '/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>
          <span className="mt-0.5 block text-xs text-white/60">Live, guided professional-learning pathways</span>
        </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>
          <span className="text-[10px] text-white/50">Professional learning pathways</span>
        </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>
  );
}
