import Link from 'next/link';
import {
  ArrowRight,
  BookOpenCheck,
  CheckCircle2,
  Clock3,
  ExternalLink,
  FileCheck2,
  GraduationCap,
  Lightbulb,
  ListChecks,
  ShieldCheck,
} from 'lucide-react';

import CVFooter from '@/components/layout/CVFooter';
import CVHeader from '@/components/layout/CVHeader';
import PrintResourceButton from '@/components/seo/PrintResourceButton';
import { MAIN_SITE_URL } from '@/lib/mainSiteUrl';

const THEMES = {
  cvaf: {
    eyebrow: 'Advanced English fluency and communication',
    accent: '#256E73',
    soft: '#EFF8F6',
    icon: BookOpenCheck,
  },
  tesol: {
    eyebrow: 'TESOL teacher-development resource',
    accent: '#8B1C1C',
    soft: '#FFFBEB',
    icon: GraduationCap,
  },
  algebra: {
    eyebrow: 'Algebra 1 learning resource',
    accent: '#256E73',
    soft: '#EFF8F6',
    icon: Lightbulb,
  },
};

function JsonLd({ data }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{
        __html: JSON.stringify(data).replace(/</g, '\\u003c'),
      }}
    />
  );
}

function InlineLink({ link }) {
  if (link.href.startsWith('/')) {
    return (
      <Link
        href={link.href}
        className="font-black text-[#8B1C1C] underline decoration-[#D4B038] underline-offset-4"
      >
        {link.label}
      </Link>
    );
  }

  return (
    <a
      href={link.href}
      target="_blank"
      rel="noopener noreferrer"
      className="inline-flex items-center gap-1 font-black text-[#8B1C1C] underline decoration-[#D4B038] underline-offset-4"
    >
      {link.label}
      <ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />
    </a>
  );
}

function ContentSection({ section, accent }) {
  return (
    <section
      id={section.id}
      className="scroll-mt-28 border-b border-[#E8DDD5] py-9 first:pt-0 last:border-b-0"
    >
      <h2 className="text-2xl font-black leading-tight text-[#1C0A12] sm:text-3xl">
        {section.title}
      </h2>

      {section.lede ? (
        <p className="mt-4 text-lg font-semibold leading-8 text-[#5D3A22]">{section.lede}</p>
      ) : null}

      {section.paragraphs?.map((paragraph) => (
        <p key={paragraph} className="mt-5 text-[15px] leading-8 text-[#3D2030] sm:text-base">
          {paragraph}
        </p>
      ))}

      {section.links?.length ? (
        <p className="mt-5 flex flex-wrap gap-x-5 gap-y-2 text-sm leading-7">
          {section.links.map((link) => (
            <InlineLink key={`${link.href}-${link.label}`} link={link} />
          ))}
        </p>
      ) : null}

      {section.bullets?.length ? (
        <ul className="mt-6 grid gap-3 sm:grid-cols-2">
          {section.bullets.map((item) => (
            <li
              key={item}
              className="flex items-start gap-3 rounded-2xl border border-[#E8DDD5] bg-[#FAF5F0] p-4 text-sm leading-6 text-[#3D2030]"
            >
              <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" style={{ color: accent }} aria-hidden="true" />
              <span>{item}</span>
            </li>
          ))}
        </ul>
      ) : null}

      {section.steps?.length ? (
        <ol className="mt-6 space-y-3">
          {section.steps.map((item, index) => (
            <li key={item} className="flex gap-4 rounded-2xl border border-[#E8DDD5] bg-white p-4">
              <span
                className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-black text-white"
                style={{ background: accent }}
              >
                {index + 1}
              </span>
              <span className="pt-1 text-sm leading-6 text-[#3D2030]">{item}</span>
            </li>
          ))}
        </ol>
      ) : null}

      {section.table ? (
        <div className="mt-7 overflow-x-auto rounded-2xl border border-[#E8DDD5] bg-white">
          <table className="w-full min-w-[680px] border-collapse text-left text-sm">
            <thead className="bg-[#4A1429] text-white">
              <tr>
                {section.table.headers.map((header) => (
                  <th key={header} scope="col" className="px-5 py-4 text-xs font-black uppercase tracking-[0.12em]">
                    {header}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {section.table.rows.map((row, rowIndex) => (
                <tr key={`${rowIndex}-${row.join('-')}`} className={rowIndex % 2 === 0 ? 'bg-white' : 'bg-[#FAF5F0]'}>
                  {row.map((cell, cellIndex) => (
                    <td
                      key={`${cellIndex}-${cell}`}
                      className={`whitespace-pre-line border-t border-[#E8DDD5] px-5 py-4 align-top leading-6 ${
                        cellIndex === 0 ? 'font-black text-[#1C0A12]' : 'text-[#5F4650]'
                      }`}
                    >
                      {cell}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}

      {section.examples?.length ? (
        <div className="mt-7 grid gap-4">
          {section.examples.map((example, index) => (
            <article key={`${example.problem}-${index}`} className="rounded-2xl border border-[#E8DDD5] bg-[#FAF5F0] p-5 sm:p-6">
              <p className="text-xs font-black uppercase tracking-[0.16em]" style={{ color: accent }}>
                {example.label || `Worked example ${index + 1}`}
              </p>
              <h3 className="mt-2 text-lg font-black text-[#1C0A12]">{example.problem}</h3>
              {example.steps?.length ? (
                <ol className="mt-4 space-y-2 text-sm leading-7 text-[#3D2030]">
                  {example.steps.map((step, stepIndex) => (
                    <li key={step}>
                      <span className="mr-2 font-black" style={{ color: accent }}>{stepIndex + 1}.</span>
                      {step}
                    </li>
                  ))}
                </ol>
              ) : null}
              {example.answer ? (
                <p className="mt-4 rounded-xl bg-white px-4 py-3 text-sm font-black text-[#1C0A12]">
                  Answer: {example.answer}
                </p>
              ) : null}
              {example.check ? <p className="mt-3 text-xs leading-6 text-[#6F5660]">Check: {example.check}</p> : null}
            </article>
          ))}
        </div>
      ) : null}

      {section.note ? (
        <div className="mt-7 flex gap-4 rounded-2xl border border-[#D4B038]/45 bg-[#FFFBEB] p-5">
          <FileCheck2 className="mt-0.5 h-5 w-5 shrink-0 text-[#8B1C1C]" aria-hidden="true" />
          <p className="text-sm font-semibold leading-7 text-[#5D3A22]">{section.note}</p>
        </div>
      ) : null}
    </section>
  );
}

function RelatedResources({ article, allArticles, accent }) {
  const related = article.relatedPaths
    .map((path) => allArticles.find((item) => item.path === path))
    .filter(Boolean)
    .slice(0, 4);

  if (!related.length) return null;

  return (
    <section className="mt-12" aria-labelledby="related-resources-title">
      <p className="text-xs font-black uppercase tracking-[0.18em]" style={{ color: accent }}>
        Continue the cluster
      </p>
      <h2 id="related-resources-title" className="mt-2 text-3xl font-black text-[#1C0A12]">
        Related guides and resources
      </h2>
      <div className="mt-7 grid gap-5 sm:grid-cols-2">
        {related.map((item) => (
          <Link
            key={item.path}
            href={item.path}
            className="group rounded-3xl border border-[#E8DDD5] bg-white p-6 shadow-sm transition hover:-translate-y-1 hover:border-[#D4B038] hover:shadow-lg"
          >
            <BookOpenCheck className="h-7 w-7" style={{ color: accent }} aria-hidden="true" />
            <p className="mt-4 text-[10px] font-black uppercase tracking-[0.16em]" style={{ color: accent }}>
              {item.id} · {item.intent}
            </p>
            <h3 className="mt-2 font-black leading-6 text-[#1C0A12]">{item.title}</h3>
            <span className="mt-5 inline-flex items-center gap-2 text-xs font-black" style={{ color: accent }}>
              Open resource <ArrowRight className="h-3.5 w-3.5 transition group-hover:translate-x-1" aria-hidden="true" />
            </span>
          </Link>
        ))}
      </div>
    </section>
  );
}

export function buildSeoArticleMetadata(article) {
  const canonical = `${MAIN_SITE_URL}${article.path}`;
  const image = `${MAIN_SITE_URL}/opengraph-image`;
  return {
    metadataBase: new URL(MAIN_SITE_URL),
    title: article.metaTitle,
    description: article.metaDescription,
    keywords: null,
    alternates: { canonical },
    openGraph: {
      type: 'article',
      url: canonical,
      siteName: 'Cambridge Veritas',
      title: article.metaTitle,
      description: article.metaDescription,
      images: [{ url: image, width: 1200, height: 630, alt: article.title }],
    },
    twitter: {
      card: 'summary_large_image',
      title: article.metaTitle,
      description: article.metaDescription,
      images: [image],
    },
  };
}

export default function SeoClusterArticle({ article, allArticles }) {
  const theme = article.editorialSeries
    ? { ...THEMES.tesol, eyebrow: article.categoryName }
    : THEMES[article.cluster] || THEMES.tesol;
  const ThemeIcon = theme.icon;
  const pageUrl = `${MAIN_SITE_URL}${article.path}`;
  const publishedAt = article.publishedAt || '2026-10-09T06:00:00.000Z';
  const articleSchema = {
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    '@id': `${pageUrl}#article`,
    headline: article.title,
    url: pageUrl,
    description: article.metaDescription,
    datePublished: publishedAt,
    dateModified: article.modifiedAt || publishedAt,
    inLanguage: article.cluster === 'algebra' ? 'en-US' : 'en',
    articleSection: article.categoryName || (article.cluster === 'algebra' ? 'Algebra 1' : 'Teacher Training'),
    isPartOf: { '@id': `${MAIN_SITE_URL}/#website` },
    mainEntityOfPage: { '@type': 'WebPage', '@id': pageUrl },
    ...(article.cluster === 'cvaf' || article.editorialSeries ? { image: `${MAIN_SITE_URL}/opengraph-image` } : {}),
    author: { '@id': `${MAIN_SITE_URL}/#organization` },
    publisher: { '@id': `${MAIN_SITE_URL}/#organization` },
    about: [article.primaryKeyword, ...article.secondaryKeywords],
    citation: article.sources.map((source) => source.href),
  };
  const breadcrumbSchema = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    '@id': `${pageUrl}#breadcrumb`,
    itemListElement: article.breadcrumbs.map((item, index) => ({
      '@type': 'ListItem',
      position: index + 1,
      name: item.label,
      item: `${MAIN_SITE_URL}${item.href}`,
    })),
  };

  return (
    <div className="min-h-screen bg-[#FAF5F0] text-[#1C0A12] print:bg-white">
      <JsonLd data={articleSchema} />
      <JsonLd data={breadcrumbSchema} />
      <div className="print:hidden"><CVHeader /></div>

      <main>
        <header className="relative overflow-hidden border-b-4 border-[#D4B038] bg-[linear-gradient(145deg,#2D0A18_0%,#4A1429_58%,#741F41_100%)] text-white print:border-b print:border-black print:bg-white print:text-black">
          <div className="absolute -right-20 -top-24 h-72 w-72 rounded-full border border-white/10 print:hidden" />
          <div className="relative mx-auto max-w-6xl px-4 py-12 sm:px-6 sm:py-16 lg:px-8 lg:py-20 print:px-0 print:py-6">
            <nav aria-label="Breadcrumb" className="flex flex-wrap items-center gap-2 text-xs font-bold text-white/60 print:hidden">
              {article.breadcrumbs.map((item, index) => (
                <span key={item.href} className="contents">
                  {index ? <span>/</span> : null}
                  <Link href={item.href} className="hover:text-white">{item.label}</Link>
                </span>
              ))}
            </nav>

            <div className="mt-8 max-w-4xl print:mt-0">
              <div className="flex flex-wrap items-center gap-3 print:hidden">
                <span className="rounded-full border border-[#D4B038]/45 bg-[#D4B038]/10 px-4 py-2 text-xs font-black uppercase tracking-[0.18em] text-[#F3D675]">
                  {theme.eyebrow}
                </span>
                <span className="inline-flex items-center gap-2 text-sm text-white/65">
                  <Clock3 className="h-4 w-4" aria-hidden="true" /> {article.readTime} min read
                </span>
              </div>
              <h1 className="mt-6 text-4xl font-black leading-[1.08] sm:text-5xl lg:text-6xl print:mt-0 print:text-3xl">
                {article.title}
              </h1>
              <p className="mt-6 max-w-3xl text-base leading-8 text-white/76 sm:text-lg print:text-black">
                {article.summary}
              </p>
              {article.cluster === 'cvaf' || article.editorialSeries ? (
                <p className="mt-4 text-sm text-white/70 print:text-black">
                  By Cambridge Veritas · Published <time dateTime={publishedAt}>3 November 2026</time>
                </p>
              ) : null}
              <div className="mt-7 flex flex-wrap items-center gap-3 print:hidden">
                {article.printable ? <PrintResourceButton label={article.printLabel} /> : null}
                <Link
                  href={article.hubPath}
                  className="algebra-resource-cta inline-flex min-h-11 items-center justify-center gap-2 rounded-xl border border-white/25 px-4 py-2.5 text-xs font-black text-white hover:bg-white/10"
                >
                  Browse the complete cluster <ArrowRight className="h-4 w-4" aria-hidden="true" />
                </Link>
              </div>
            </div>
          </div>
        </header>

        <div className="mx-auto grid max-w-6xl gap-8 px-4 py-12 sm:px-6 lg:grid-cols-[230px_minmax(0,1fr)] lg:px-8 lg:py-16 print:block print:max-w-none print:px-0 print:py-6">
          <aside className="hidden lg:block print:hidden">
            <div className="sticky top-24 rounded-3xl border border-[#E8DDD5] bg-white p-5 shadow-sm">
              <p className="text-[11px] font-black uppercase tracking-[0.18em]" style={{ color: theme.accent }}>In this guide</p>
              <nav className="mt-4 space-y-1">
                {article.sections.map((section) => (
                  <a key={section.id} href={`#${section.id}`} className="block rounded-xl px-3 py-2 text-xs font-bold leading-5 text-[#6F5660] transition hover:bg-[#F6EFE9] hover:text-[#4A1429]">
                    {section.title}
                  </a>
                ))}
                {article.faqs.length ? <a href="#faq" className="block rounded-xl px-3 py-2 text-xs font-bold leading-5 text-[#6F5660] transition hover:bg-[#F6EFE9] hover:text-[#4A1429]">Frequently asked questions</a> : null}
              </nav>
            </div>
          </aside>

          <article className="min-w-0">
            <details className="mb-6 rounded-2xl border border-[#E8DDD5] bg-white p-5 lg:hidden print:hidden">
              <summary className="cursor-pointer font-bold">In this guide</summary>
              <nav aria-label="Article contents" className="mt-3 space-y-3">
                {article.sections.map((section) => (
                  <a key={section.id} href={`#${section.id}`} className="block text-sm text-[#4A1429] underline">{section.title}</a>
                ))}
              </nav>
            </details>
            <section className="rounded-[28px] border p-6 sm:p-8 print:break-inside-avoid" style={{ background: theme.soft, borderColor: `${theme.accent}55` }}>
              <div className="flex items-center gap-3">
                <ThemeIcon className="h-6 w-6" style={{ color: theme.accent }} aria-hidden="true" />
                <h2 className="text-xl font-black">What you will be able to do</h2>
              </div>
              <ul className="mt-5 space-y-3">
                {article.quickAnswers.map((answer) => (
                  <li key={answer} className="flex items-start gap-3 text-sm leading-7 text-[#5D3A22]">
                    <CheckCircle2 className="mt-1 h-4 w-4 shrink-0" style={{ color: theme.accent }} aria-hidden="true" />
                    <span>{answer}</span>
                  </li>
                ))}
              </ul>
            </section>

            <div className="mt-10 rounded-[32px] border border-[#E8DDD5] bg-white px-6 py-2 shadow-sm sm:px-9 print:border-0 print:px-0 print:shadow-none">
              {article.sections.map((section) => (
                <ContentSection key={section.id} section={section} accent={theme.accent} />
              ))}
            </div>

            <section className="mt-10 overflow-hidden rounded-[32px] border border-[#D4B038]/35 bg-[#4A1429] text-white shadow-xl print:hidden">
              <div className="grid gap-7 p-7 sm:p-9 lg:grid-cols-[1fr_auto] lg:items-center">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.2em] text-[#D4B038]">{article.ctaEyebrow}</p>
                  <h2 className="mt-3 text-2xl font-black sm:text-3xl">{article.ctaTitle}</h2>
                  <p className="mt-4 max-w-2xl text-sm leading-7 text-white/72">{article.ctaText}</p>
                </div>
                <Link href={article.ctaPath} className="algebra-resource-cta inline-flex min-h-13 items-center justify-center gap-2 rounded-2xl bg-[#D4B038] px-6 py-4 text-center text-sm font-black text-[#2D0A18] transition hover:bg-[#E6C75A]">
                  {article.ctaLabel} <ArrowRight className="h-4 w-4 shrink-0" aria-hidden="true" />
                </Link>
              </div>
            </section>

            {article.faqs.length ? (
              <section id="faq" className="mt-12 scroll-mt-28 rounded-[32px] border border-[#E8DDD5] bg-white p-6 shadow-sm sm:p-9 print:break-before-page print:border-0 print:px-0 print:shadow-none">
                <div className="flex items-center gap-3">
                  <ListChecks className="h-7 w-7" style={{ color: theme.accent }} aria-hidden="true" />
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.18em]" style={{ color: theme.accent }}>Useful answers</p>
                    <h2 className="mt-2 text-3xl font-black">Frequently asked questions</h2>
                  </div>
                </div>
                <div className="mt-7 divide-y divide-[#E8DDD5]">
                  {article.faqs.map(([question, answer]) => (
                    <details key={question} className="py-5">
                      <summary className="cursor-pointer list-none pr-8 font-black leading-6 marker:content-none">{question}</summary>
                      <p className="mt-3 max-w-3xl text-sm leading-7 text-[#6F5660]">{answer}</p>
                    </details>
                  ))}
                </div>
              </section>
            ) : null}

            <section className="mt-10 rounded-[28px] border border-[#E8DDD5] bg-[#F6EFE9] p-6 sm:p-8 print:break-inside-avoid">
              <div className="flex items-center gap-3">
                <ShieldCheck className="h-6 w-6 text-[#8B1C1C]" aria-hidden="true" />
                <h2 className="text-xl font-black">Sources, scope and accuracy</h2>
              </div>
              <p className="mt-4 text-sm leading-7 text-[#6F5660]">{article.sourceNote}</p>
              <ul className="mt-5 space-y-3">
                {article.sources.map((source) => (
                  <li key={source.href}><InlineLink link={source} /></li>
                ))}
                <li><Link href="/editorial-policy" className="font-black text-[#8B1C1C] underline decoration-[#D4B038] underline-offset-4">Cambridge Veritas editorial policy</Link></li>
              </ul>
            </section>

            <div className="print:hidden">
              <RelatedResources article={article} allArticles={allArticles} accent={theme.accent} />
            </div>
          </article>
        </div>
      </main>

      <div className="print:hidden"><CVFooter /></div>
    </div>
  );
}
