import Link from "next/link";
import {
  ArrowRight,
  BookOpen,
  CheckCircle2,
  GraduationCap,
  Layers3,
  Lightbulb,
  ListChecks,
  Search,
  Target,
} from "lucide-react";
import { connection } from "next/server";
import CVHeader from "@/components/layout/CVHeader";
import CVFooter from "@/components/layout/CVFooter";
import GrammarLessonGrid from "@/components/grammar/GrammarLessonGrid";
import { getGrammarIndexData } from "@/lib/grammar";
import { MAIN_SITE_URL } from "@/lib/mainSiteUrl";

const GRAMMAR_URL = `${MAIN_SITE_URL}/grammar`;
const GRAMMAR_TITLE = "Free English Grammar Lessons & Exercises | Cambridge Veritas";
const GRAMMAR_DESCRIPTION =
  "Learn English grammar online with 107 free lessons from A1 to C2. Get clear explanations, real-life examples and interactive quizzes for every level.";
const GRAMMAR_KEYWORDS = [
  "English grammar lessons",
  "free English grammar lessons",
  "learn English grammar online",
  "English grammar exercises",
  "English grammar online",
  "CEFR grammar lessons",
  "English grammar A1 to C2",
  "ESL grammar resources",
];

const GRAMMAR_LEVELS = [
  {
    slug: "a1-a2-grammar",
    label: "A1-A2 English Grammar",
    title: "Beginner & Elementary",
    text: "Build foundations with present simple, past simple, articles, pronouns, basic modals, prepositions, and everyday sentence patterns.",
    cta: "Explore A1-A2 Grammar",
  },
  {
    slug: "b1-b2-grammar",
    label: "B1-B2 English Grammar",
    title: "Intermediate & Upper Intermediate",
    text: "Improve accuracy with present perfect, passive voice, conditionals, reported speech, relative clauses, and complex modal structures.",
    cta: "Explore B1-B2 Grammar",
  },
  {
    slug: "c1-grammar",
    label: "C1-C2 English Grammar",
    title: "Advanced",
    text: "Refine nuance, emphasis, register, advanced clause patterns, discourse grammar, and sophisticated sentence control.",
    cta: "Explore Advanced Grammar",
  },
];

const GRAMMAR_TOPICS = [
  ["English Tenses", "Tense forms for present, past, future, perfect, and continuous meanings.", "tenses"],
  ["Present Tenses", "Present simple, present continuous, present perfect, and present perfect continuous.", "present"],
  ["Past Tenses", "Past simple, past continuous, past perfect, used to, and narrative forms.", "past"],
  ["Future Forms", "Will, going to, present continuous for future, and future perfect patterns.", "future"],
  ["Modal Verbs", "Can, could, should, must, might, have to, and modal meanings.", "modal"],
  ["Articles & Determiners", "A, an, the, some, any, much, many, few, little, and quantifiers.", "article"],
  ["Pronouns", "Subject, object, possessive, reflexive, relative, and indefinite pronouns.", "pronoun"],
  ["Nouns", "Countable, uncountable, plural, compound, and abstract nouns.", "noun"],
  ["Adjectives & Adverbs", "Descriptions, comparisons, intensifiers, adverb position, and degree.", "adjective"],
  ["Prepositions", "Place, time, movement, fixed phrases, and common preposition mistakes.", "preposition"],
  ["Conditionals", "Zero, first, second, third, and mixed conditional forms.", "conditional"],
  ["Passive Voice", "Active/passive transformations, agent focus, reporting, and formal tone.", "passive"],
  ["Reported Speech", "Tense backshift, reporting verbs, questions, commands, and paraphrase.", "reported"],
  ["Questions", "Auxiliary questions, subject questions, embedded questions, and question tags.", "question"],
  ["Sentence Structure", "Word order, clauses, connectors, emphasis, and sentence variety.", "sentence"],
];

const TOPIC_QUERY_LOOKUP = Object.fromEntries(
  GRAMMAR_TOPICS.map(([title, , query]) => [toSlug(title), query])
);

const GRAMMAR_FAQS = [
  [
    "Are the Cambridge Veritas English grammar lessons free?",
    "Yes. The grammar hub is designed as a free learning library with explanations, examples, and practice activities learners can use independently.",
  ],
  [
    "What English levels do the grammar lessons cover?",
    "The lessons are organised around CEFR progression from A1 and A2 foundations through B1 and B2 intermediate grammar to C1 and C2 advanced structures.",
  ],
  [
    "What grammar should I learn at A1 level?",
    "A1 learners should focus on basic sentence order, present simple, be, have, articles, singular and plural nouns, pronouns, simple questions, and essential prepositions.",
  ],
  [
    "What grammar should I know at B1 and B2 level?",
    "B1 and B2 learners usually need stronger control of perfect tenses, conditionals, passive voice, relative clauses, reported speech, modal verbs, and linking words.",
  ],
  [
    "What grammar should advanced C1-C2 learners study?",
    "Advanced learners should refine nuance, register, emphasis, complex clauses, inversion, discourse markers, modality, hedging, and sophisticated sentence structure.",
  ],
  [
    "How can I improve my English grammar online?",
    "Choose a CEFR level, study one grammar point at a time, read examples carefully, complete the quiz, write your own examples, and use the structure in speaking and writing.",
  ],
  [
    "Do the grammar lessons include quizzes?",
    "Many lessons include interactive quiz questions so you can check understanding immediately after reviewing the rule, examples, and common usage patterns.",
  ],
  [
    "Can I use these lessons to prepare for IELTS?",
    "Yes. Grammar accuracy supports IELTS writing and speaking, especially sentence control, tense accuracy, complex structures, punctuation, and error reduction.",
  ],
  [
    "Are these grammar lessons suitable for ESL and EFL learners?",
    "Yes. The lessons are written for English learners studying online, including ESL and EFL learners who want clear explanations and level-based practice.",
  ],
  [
    "Can English teachers use these lessons with students?",
    "Yes. Teachers can use individual lessons for revision, homework, classroom support, or short follow-up practice after introducing a grammar point.",
  ],
  [
    "Are the lessons useful for TESOL trainees?",
    "Yes. TESOL trainees can use the lessons to review grammar awareness and observe how grammar explanations can be connected to examples and practice.",
  ],
  [
    "How do I find my English CEFR level?",
    "Start with the Cambridge Veritas English level test or review the CEFR levels page, then choose grammar lessons that match your current band.",
  ],
];

export const metadata = {
  metadataBase: new URL(MAIN_SITE_URL),
  title: GRAMMAR_TITLE,
  description: GRAMMAR_DESCRIPTION,
  keywords: GRAMMAR_KEYWORDS,
  alternates: {
    canonical: GRAMMAR_URL,
  },
  robots: {
    index: true,
    follow: true,
    googleBot: {
      index: true,
      follow: true,
      "max-video-preview": -1,
      "max-image-preview": "large",
      "max-snippet": -1,
    },
  },
  openGraph: {
    title: GRAMMAR_TITLE,
    description: GRAMMAR_DESCRIPTION,
    url: GRAMMAR_URL,
    siteName: "Cambridge Veritas",
    type: "website",
    images: [
      {
        url: "/opengraph-image",
        width: 1200,
        height: 630,
        alt: GRAMMAR_TITLE,
      },
    ],
  },
  twitter: {
    card: "summary_large_image",
    title: GRAMMAR_TITLE,
    description: GRAMMAR_DESCRIPTION,
    images: ["/opengraph-image"],
  },
};

function toSlug(value) {
  return String(value || "")
    .toLowerCase()
    .replace(/&/g, "and")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function firstParam(value) {
  return Array.isArray(value) ? value[0] : value;
}

function getInitialPage(searchParams) {
  const page = Number.parseInt(String(firstParam(searchParams?.page) || "1"), 10);
  return Number.isFinite(page) && page > 0 ? page : 1;
}

function getInitialQuery(searchParams) {
  const topic = String(firstParam(searchParams?.topic) || "").trim().toLowerCase();
  const search = String(firstParam(searchParams?.search) || "").trim();

  if (topic && TOPIC_QUERY_LOOKUP[topic]) {
    return TOPIC_QUERY_LOOKUP[topic];
  }

  return search;
}

function getLevelCards(categories, posts) {
  return GRAMMAR_LEVELS.map((level) => {
    const category = categories.find((item) => item.slug === level.slug);
    const slug = category?.slug || level.slug;
    const lessonCount = posts.filter((post) => post.category_slug === slug).length;

    return {
      ...level,
      href: `/grammar/${slug}`,
      lessonCount,
      displayLabel: category?.label || level.label,
    };
  });
}

function buildGrammarJsonLd(levelCards) {
  return {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "CollectionPage",
        "@id": `${GRAMMAR_URL}#webpage`,
        url: GRAMMAR_URL,
        name: "Free English Grammar Lessons & Exercises (A1-C2)",
        description:
          "Free English grammar lessons from A1 to C2 with clear explanations, real-life examples and interactive quizzes.",
        publisher: {
          "@id": `${MAIN_SITE_URL}/#organization`,
        },
        mainEntity: {
          "@id": `${GRAMMAR_URL}#levels`,
        },
      },
      {
        "@type": "ItemList",
        "@id": `${GRAMMAR_URL}#levels`,
        name: "English Grammar Lessons by CEFR Level",
        numberOfItems: levelCards.length,
        itemListElement: levelCards.map((level, index) => ({
          "@type": "ListItem",
          position: index + 1,
          name: `${level.label} Lessons`,
          url: `${MAIN_SITE_URL}${level.href}`,
        })),
      },
      {
        "@type": "BreadcrumbList",
        "@id": `${GRAMMAR_URL}#breadcrumb`,
        itemListElement: [
          {
            "@type": "ListItem",
            position: 1,
            name: "Home",
            item: `${MAIN_SITE_URL}/`,
          },
          {
            "@type": "ListItem",
            position: 2,
            name: "English Grammar",
            item: GRAMMAR_URL,
          },
        ],
      },
    ],
  };
}

function StructuredData({ data }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{
        __html: JSON.stringify(data).replace(/</g, "\\u003c"),
      }}
    />
  );
}

export default async function GrammarPage({ searchParams }) {
  await connection();

  const queryParams = await searchParams;
  const initialPage = getInitialPage(queryParams);
  const initialQuery = getInitialQuery(queryParams);
  const { categories, posts, quizQuestionCount } = await getGrammarIndexData();
  const levelCards = getLevelCards(categories, posts);
  const quizLessons = posts.filter((post) => post.quiz_id).length;
  const grammarJsonLd = buildGrammarJsonLd(levelCards);

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      <StructuredData data={grammarJsonLd} />
      <CVHeader />

      <main className="bg-[#FAF5F0]">
        <div className="h-1 bg-gradient-to-r from-[#4A1429] via-[#D4B038] to-[#4A1429]" />

        <section className="mx-auto max-w-[1100px] px-4 py-8 sm:px-6 sm:py-12">
          <div className="mb-10 text-center">
            <div className="inline-flex items-center gap-2 rounded-full border border-[#4A1429]/20 bg-[#4A1429]/5 px-3.5 py-1.5 text-[11px] font-black uppercase tracking-widest text-[#4A1429]">
              <span className="h-1.5 w-1.5 rounded-full bg-[#D4B038]" />
              Cambridge Veritas - Free Grammar Hub
            </div>
            <h1 className="mt-4 text-4xl font-black leading-tight text-[#1C0A12] sm:text-5xl">
              Free English Grammar Lessons & Exercises (A1-C2)
            </h1>
            <div className="mx-auto mt-4 max-w-4xl space-y-3 text-base leading-relaxed text-[#7A5C65] sm:text-lg">
              <p>
                Learn English grammar online with {posts.length} free lessons covering beginner to advanced levels from
                A1 to C2. Each Cambridge Veritas grammar lesson combines a clear explanation, real-life examples, common
                mistakes, and an interactive quiz so you can understand the rule and practise using it.
              </p>
              <p>
                Choose your CEFR level or search for a grammar topic such as English tenses, articles, prepositions,
                modal verbs, conditionals, passive voice, reported speech, or sentence structure. Whether you are
                improving your own English, preparing for an exam, or teaching ESL learners, you can use the lessons
                independently and revisit them whenever you need.
              </p>
              <p>
                Not sure where to begin? Check your English level first, then follow the grammar lessons for your CEFR
                band.
              </p>
            </div>

            <div className="mt-5 inline-flex flex-wrap justify-center gap-5 rounded-2xl border border-[#E8DDD5] bg-white px-5 py-3 shadow-sm">
              {[
                [posts.length, "Free lessons"],
                [quizQuestionCount || quizLessons, quizQuestionCount ? "Quiz questions" : "Quiz lessons"],
                ["6", "CEFR levels"],
                ["Free", "Online access"],
              ].map(([value, label]) => (
                <div key={label} className="text-center">
                  <div className="text-2xl font-black text-[#4A1429]">{value}</div>
                  <div className="text-[10px] font-bold uppercase tracking-widest text-[#7A5C65]">
                    {label}
                  </div>
                </div>
              ))}
            </div>

            <div className="mt-6 flex flex-col justify-center gap-3 sm:flex-row">
              <a
                href="#lessons"
                className="inline-flex items-center justify-center gap-2 rounded-2xl bg-[#4A1429] px-6 py-3 text-sm font-black text-white shadow-lg transition hover:bg-[#5F1B35]"
              >
                Browse Grammar Lessons <ArrowRight className="h-4 w-4" />
              </a>
              <Link
                href="/level-test"
                className="inline-flex items-center justify-center gap-2 rounded-2xl border border-[#D4B038]/40 bg-white px-6 py-3 text-sm font-black text-[#4A1429] shadow-sm transition hover:border-[#D4B038]"
              >
                Check Your English Level
              </Link>
            </div>
          </div>

          <section className="mb-12 rounded-[28px] border border-[#E8DDD5] bg-white p-6 shadow-sm sm:p-8">
            <SectionHeading
              eyebrow="Learn English Grammar Online for Free"
              title="Clear Grammar Explanations, Examples and Practice"
              text="Use the hub as a step-by-step grammar library or as a quick reference when you already know the topic you need."
            />
            <div className="grid gap-4 md:grid-cols-4">
              {[
                [BookOpen, "Learn the rule", "Read a plain-English explanation before you practise."],
                [Lightbulb, "Study examples", "See how the structure works in real sentences."],
                [ListChecks, "Take a quiz", "Check whether you can recognise and use the form."],
                [Target, "Apply it", "Move from grammar knowledge into speaking and writing."],
              ].map(([Icon, title, text]) => (
                <InfoCard key={title} Icon={Icon} title={title} text={text} />
              ))}
            </div>
          </section>

          <section className="mb-12">
            <SectionHeading
              eyebrow="Choose Your English Grammar Level"
              title="Grammar Lessons by CEFR Level"
              text="Start with the level closest to your current English ability, then move upward when the examples and quizzes feel comfortable."
            />
            <div className="grid gap-5 md:grid-cols-3">
              {levelCards.map((level) => (
                <LevelCard key={level.slug} level={level} />
              ))}
            </div>
          </section>

          <section className="mb-12 rounded-[28px] border border-[#E8DDD5] bg-white p-6 shadow-sm sm:p-8">
            <SectionHeading
              eyebrow="Browse English Grammar by Topic"
              title="Find the Grammar Point You Need"
              text="Use these topic links when you already know the area you want to study. They open the grammar library with a matching search."
            />
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {GRAMMAR_TOPICS.map(([title, text]) => (
                <TopicLink key={title} title={title} text={text} />
              ))}
            </div>
          </section>

          <section className="mb-12 grid gap-5 lg:grid-cols-[0.95fr_1.05fr]">
            <div className="rounded-[28px] border border-[#D4B038]/30 bg-gradient-to-br from-[#4A1429] to-[#6B1E3D] p-6 text-white shadow-lg sm:p-8">
              <p className="mb-2 text-xs font-black uppercase tracking-widest text-[#D4B038]">
                Practise English Grammar With Interactive Quizzes
              </p>
              <h2 className="mb-4 text-3xl font-black">Learn, Check, Repeat</h2>
              <p className="mb-6 leading-relaxed text-white/75">
                Grammar improves fastest when explanation is followed by active recall. Many Cambridge Veritas lessons
                include short quizzes so you can test the rule immediately and return to the explanation when needed.
              </p>
              <div className="grid gap-3 sm:grid-cols-2">
                {[
                  "Topic-focused questions",
                  "Instant answer feedback",
                  "Short practice sessions",
                  "Useful for revision",
                ].map((item) => (
                  <div key={item} className="flex items-center gap-2 rounded-2xl border border-white/15 bg-white/10 px-4 py-3 text-sm font-bold">
                    <CheckCircle2 className="h-4 w-4 text-[#D4B038]" />
                    {item}
                  </div>
                ))}
              </div>
            </div>
            <div className="rounded-[28px] border border-[#E8DDD5] bg-white p-6 shadow-sm sm:p-8">
              <SectionHeading
                eyebrow="How to Use These Grammar Lessons"
                title="A Simple Study Routine"
                text="Keep each session focused on one grammar point so practice leads to real control."
                compact
              />
              <div className="space-y-3">
                {[
                  ["1", "Choose your level", "Start with the CEFR level closest to your current ability."],
                  ["2", "Learn one grammar point", "Read the rule and study the examples before moving on."],
                  ["3", "Take the quiz", "Check whether you can recognise the correct structure."],
                  ["4", "Create your own examples", "Write sentences connected to your life, work, or study."],
                  ["5", "Use it in communication", "Bring the structure into speaking and writing practice."],
                ].map(([number, title, text]) => (
                  <StepRow key={number} number={number} title={title} text={text} />
                ))}
              </div>
            </div>
          </section>

          <section className="mb-12">
            <SectionHeading
              eyebrow="English Grammar for IELTS, Work and Everyday Communication"
              title="Use Grammar Where It Matters"
              text="Choose lessons that support the communication goal in front of you."
            />
            <div className="grid gap-5 md:grid-cols-3">
              {[
                [
                  GraduationCap,
                  "IELTS preparation",
                  "Work on sentence variety, tense control, linking words, clauses, and accuracy for IELTS writing and speaking.",
                  "/masterclass/cambridge-veritas-certificate-in-ielts-masterclass",
                  "Explore IELTS Masterclass",
                ],
                [
                  Target,
                  "Workplace English",
                  "Use grammar to make emails, meetings, presentations, and professional conversations clearer and more precise.",
                  "/masterclass/cambridge-veritas-certificate-in-business-english",
                  "Explore Business English",
                ],
                [
                  BookOpen,
                  "Everyday fluency",
                  "Build confidence with structures you can use in daily conversation, study, travel, and independent learning.",
                  "/certifications/cambridge-veritas-certificate-in-advanced-fluency",
                  "Explore Advanced Fluency",
                ],
              ].map(([Icon, title, text, href, cta]) => (
                <LinkedCard key={title} Icon={Icon} title={title} text={text} href={href} cta={cta} />
              ))}
            </div>
          </section>

          <section className="mb-12 rounded-[28px] border border-[#D4B038]/30 bg-gradient-to-br from-[#4A1429] to-[#6B1E3D] p-6 text-white shadow-lg sm:p-8">
            <div className="grid gap-8 lg:grid-cols-[0.9fr_1.1fr] lg:items-center">
              <div>
                <p className="mb-2 text-xs font-black uppercase tracking-widest text-[#D4B038]">
                  English Grammar Resources for Teachers & TESOL Trainees
                </p>
                <h2 className="mb-4 text-3xl font-black">Support Lessons, Revision and Independent Practice</h2>
                <p className="leading-relaxed text-white/75">
                  Cambridge Veritas grammar lessons can support lesson planning, revision, and independent practice for
                  ESL/EFL learners. Teachers can use individual pages to introduce or review language forms, identify
                  common errors, and assign short quizzes for follow-up practice.
                </p>
              </div>
              <div className="rounded-3xl border border-white/15 bg-white/10 p-6">
                <h3 className="mb-3 text-xl font-black text-[#F5EFE8]">Training to become an English teacher?</h3>
                <p className="mb-5 text-sm leading-relaxed text-white/70">
                  Connect grammar awareness with lesson planning, learner support, and evidence-based teaching practice
                  through the Cambridge Veritas TESOL pathway.
                </p>
                <Link
                  href="/certifications/cambridge-veritas-certificate-in-TESOL"
                  className="inline-flex items-center gap-2 rounded-2xl bg-[#D4B038] px-5 py-3 text-sm font-black text-[#4A1429] transition hover:bg-[#F5D060]"
                >
                  Explore 120-Hour TESOL Certification <ArrowRight className="h-4 w-4" />
                </Link>
              </div>
            </div>
          </section>

          <section className="mb-12 grid gap-5 md:grid-cols-2">
            <div className="rounded-[28px] border border-[#E8DDD5] bg-white p-6 shadow-sm sm:p-8">
              <SectionHeading
                eyebrow="Not Sure of Your English Level?"
                title="Find Your Starting Point"
                text="Take the free online English level test first, then continue with grammar lessons for your CEFR band."
                compact
              />
              <Link
                href="/level-test"
                className="inline-flex items-center gap-2 rounded-2xl bg-[#4A1429] px-5 py-3 text-sm font-black text-white transition hover:bg-[#5F1B35]"
              >
                Take the Free Level Test <ArrowRight className="h-4 w-4" />
              </Link>
            </div>
            <div className="rounded-[28px] border border-[#E8DDD5] bg-white p-6 shadow-sm sm:p-8">
              <SectionHeading
                eyebrow="How Cambridge Veritas Grammar Lessons Are Created"
                title="Level-Based, Practice-Oriented Grammar"
                text="The hub is organised around CEFR progression, practical grammar explanations, real examples, common learner errors, and short checks for understanding. Hub content reviewed: October 2026."
                compact
              />
              <Link
                href="/cefr-levels"
                className="inline-flex items-center gap-2 rounded-2xl border border-[#D4B038]/40 bg-[#FFFBEB] px-5 py-3 text-sm font-black text-[#4A1429] transition hover:border-[#D4B038]"
              >
                Review CEFR Levels <ArrowRight className="h-4 w-4" />
              </Link>
            </div>
          </section>

          <section id="lessons" className="scroll-mt-24">
            <SectionHeading
              eyebrow="All Free Grammar Lessons"
              title="Search and Browse the Lesson Library"
              text="Use search, level filters, and crawlable pagination to move through the full grammar library."
            />
            <GrammarLessonGrid
              key={`${initialQuery}-${initialPage}`}
              categories={categories}
              posts={posts}
              initialPage={initialPage}
              initialQuery={initialQuery}
              basePath="/grammar"
            />
          </section>

          <section className="mt-14 rounded-[28px] border border-[#E8DDD5] bg-white p-6 shadow-sm sm:p-8">
            <SectionHeading title="Frequently Asked Questions" text="Quick answers about using the Cambridge Veritas grammar hub." />
            <div className="space-y-3">
              {GRAMMAR_FAQS.map(([question, answer], index) => (
                <details
                  key={question}
                  className="rounded-2xl border border-[#E8DDD5] bg-[#FFFCF8] transition hover:border-[#D4B038]/50"
                  open={index === 0}
                >
                  <summary className="cursor-pointer px-5 py-4 text-sm font-black text-[#1C0A12]">
                    {question}
                  </summary>
                  <p className="border-t border-[#E8DDD5] px-5 pb-5 pt-4 text-sm leading-relaxed text-[#7A5C65]">
                    {answer}
                  </p>
                </details>
              ))}
            </div>
          </section>
        </section>
      </main>

      <CVFooter />
    </div>
  );
}

function SectionHeading({ eyebrow, title, text, compact = false }) {
  return (
    <div className={compact ? "mb-5" : "mx-auto mb-7 max-w-3xl text-center"}>
      {eyebrow ? (
        <p className="mb-2 text-xs font-black uppercase tracking-widest text-[#8B1C1C]">
          {eyebrow}
        </p>
      ) : null}
      <h2 className={`${compact ? "text-2xl" : "text-3xl sm:text-4xl"} font-black leading-tight text-[#1C0A12]`}>
        {title}
      </h2>
      {text ? <p className="mt-3 text-base leading-relaxed text-[#7A5C65]">{text}</p> : null}
    </div>
  );
}

function InfoCard({ Icon, title, text }) {
  return (
    <div className="rounded-2xl border border-[#E8DDD5] bg-[#FFFCF8] p-5">
      <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-2xl bg-[#4A1429]/10">
        <Icon className="h-5 w-5 text-[#4A1429]" />
      </div>
      <h3 className="mb-2 text-base font-black text-[#1C0A12]">{title}</h3>
      <p className="text-sm leading-relaxed text-[#7A5C65]">{text}</p>
    </div>
  );
}

function LevelCard({ level }) {
  return (
    <Link
      href={level.href}
      className="group block rounded-[26px] border border-[#E8DDD5] bg-white p-6 shadow-sm transition hover:-translate-y-0.5 hover:border-[#D4B038] hover:shadow-lg"
    >
      <div className="mb-4 flex items-start justify-between gap-3">
        <div>
          <p className="text-xs font-black uppercase tracking-widest text-[#8B1C1C]">{level.displayLabel}</p>
          <h3 className="mt-2 text-2xl font-black text-[#1C0A12]">{level.title}</h3>
        </div>
        <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[#FFFBEB]">
          <Layers3 className="h-6 w-6 text-[#D4B038]" />
        </div>
      </div>
      <p className="mb-5 text-sm leading-relaxed text-[#7A5C65]">{level.text}</p>
      <div className="mb-5 rounded-2xl border border-[#E8DDD5] bg-[#FAF5F0] px-4 py-3 text-sm font-bold text-[#4A1429]">
        {level.lessonCount || "Multiple"} lessons in this level
      </div>
      <span className="inline-flex items-center gap-2 text-sm font-black text-[#8B1C1C]">
        {level.cta} <ArrowRight className="h-4 w-4 transition group-hover:translate-x-1" />
      </span>
    </Link>
  );
}

function TopicLink({ title, text }) {
  return (
    <Link
      href={`/grammar?topic=${toSlug(title)}#lessons`}
      className="group rounded-2xl border border-[#E8DDD5] bg-[#FFFCF8] p-4 transition hover:border-[#D4B038] hover:bg-white"
    >
      <div className="mb-2 flex items-center gap-2 text-sm font-black text-[#4A1429]">
        <Search className="h-4 w-4 text-[#D4B038]" />
        {title}
      </div>
      <p className="text-xs leading-relaxed text-[#7A5C65]">{text}</p>
    </Link>
  );
}

function StepRow({ number, title, text }) {
  return (
    <div className="flex gap-3 rounded-2xl border border-[#E8DDD5] bg-[#FFFCF8] p-4">
      <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-[#4A1429] text-sm font-black text-white">
        {number}
      </div>
      <div>
        <h3 className="text-sm font-black text-[#1C0A12]">{title}</h3>
        <p className="mt-1 text-sm leading-relaxed text-[#7A5C65]">{text}</p>
      </div>
    </div>
  );
}

function LinkedCard({ Icon, title, text, href, cta }) {
  return (
    <div className="rounded-[26px] border border-[#E8DDD5] bg-white p-6 shadow-sm">
      <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-[#4A1429]/10">
        <Icon className="h-6 w-6 text-[#4A1429]" />
      </div>
      <h3 className="mb-3 text-xl font-black text-[#1C0A12]">{title}</h3>
      <p className="mb-5 text-sm leading-relaxed text-[#7A5C65]">{text}</p>
      <Link href={href} className="inline-flex items-center gap-2 text-sm font-black text-[#8B1C1C]">
        {cta} <ArrowRight className="h-4 w-4" />
      </Link>
    </div>
  );
}
