import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { MarkdownArticle } from "./MarkdownArticle";
import { brand, type Locale } from "@/content/site";
import { libraryPath } from "@/content/libraryPaths";
import { getArticle, getArticleTranslations, getRelatedArticles } from "@/lib/library";

const labels = {
  fr: { library: "Bibliothèque", contents: "Sommaire", published: "Publié le", updated: "Mis à jour le", author: "Auteur", related: "À lire ensuite", ctaTitle: "Vous cherchez une agence de communication à Fès ?", ctaText: "YASHAL réunit stratégie, production vidéo, web, SEO et contenu pour construire une présence capable d’attirer l’attention et de soutenir votre croissance.", ctaButton: "Parlons de votre projet", temporary: "Visuel temporaire", home: "Accueil" },
  en: { library: "Knowledge", contents: "Contents", published: "Published", updated: "Updated", author: "Author", related: "Read next", ctaTitle: "Looking for a Marketing Agency in Fez?", ctaText: "YASHAL combines strategy, video production, web design, SEO and content to build a presence that earns attention and supports growth.", ctaButton: "Discuss Your Project", temporary: "Temporary visual", home: "Home" },
  ar: { library: "المعرفة", contents: "المحتويات", published: "نُشر في", updated: "حُدّث في", author: "الكاتب", related: "اقرأ أيضاً", ctaTitle: "هل تبحث عن وكالة تسويق في فاس؟", ctaText: "تجمع YASHAL بين الاستراتيجية وإنتاج الفيديو وتصميم المواقع وتحسين الظهور والمحتوى لبناء حضور يجذب الانتباه ويدعم النمو.", ctaButton: "لنتحدث عن مشروعك", temporary: "صورة مؤقتة", home: "الرئيسية" },
} satisfies Record<Locale, Record<string, string>>;

function formatDate(locale: Locale, value: string) {
  return new Intl.DateTimeFormat(locale === "ar" ? "ar-MA" : locale === "fr" ? "fr-FR" : "en-GB", { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" }).format(new Date(`${value}T00:00:00Z`));
}

export function createArticleMetadata(locale: Locale, slug: string): Metadata {
  const article = getArticle(locale, slug);
  if (!article) return {};
  const translations = getArticleTranslations(article.translationKey);
  const canonical = libraryPath(locale, article.slug);
  const languages = Object.fromEntries(translations.map((entry) => [entry.locale, libraryPath(entry.locale, entry.slug)]));
  const french = translations.find((entry) => entry.locale === "fr");
  if (french) languages["x-default"] = libraryPath("fr", french.slug);
  return {
    title: article.seoTitle,
    description: article.seoDescription,
    alternates: { canonical, languages },
    openGraph: { type: "article", title: article.seoTitle, description: article.seoDescription, url: canonical, publishedTime: article.publishedAt, modifiedTime: article.updatedAt ?? article.publishedAt, authors: [article.author], images: [{ url: article.coverImage, width: 1200, height: 630, alt: article.coverImageAlt }] },
    twitter: { card: "summary_large_image", title: article.seoTitle, description: article.seoDescription, images: [article.coverImage] },
  };
}

export function LibraryArticlePage({ locale, slug }: { locale: Locale; slug: string }) {
  const article = getArticle(locale, slug);
  if (!article) notFound();
  const copy = labels[locale];
  const canonical = `https://${brand.domain}${libraryPath(locale, article.slug)}`;
  const related = getRelatedArticles(article);
  const faqStart = article.blocks.findIndex((block) => block.type === "heading" && block.level === 2 && /^(FAQ|Frequently asked questions)/i.test(block.text));
  const faqItems: { question: string; answer: string }[] = [];
  if (faqStart >= 0) {
    for (let index = faqStart + 1; index < article.blocks.length; index += 1) {
      const block = article.blocks[index];
      if (block.type === "heading" && block.level === 2) break;
      if (block.type === "heading" && block.level === 3) {
        const answer: string[] = [];
        for (let answerIndex = index + 1; answerIndex < article.blocks.length; answerIndex += 1) {
          const answerBlock = article.blocks[answerIndex];
          if (answerBlock.type === "heading") break;
          if (answerBlock.type === "paragraph" || answerBlock.type === "blockquote") answer.push(answerBlock.text);
          if (answerBlock.type === "list") answer.push(answerBlock.items.join(" "));
        }
        if (answer.length) faqItems.push({ question: block.text, answer: answer.join(" ") });
      }
    }
  }
  const graph = {
    "@context": "https://schema.org",
    "@graph": [
      { "@type": "BlogPosting", headline: article.title, description: article.description, image: [`https://${brand.domain}${article.coverImage}`], datePublished: article.publishedAt, dateModified: article.updatedAt ?? article.publishedAt, author: { "@type": "Organization", name: article.author, url: `https://${brand.domain}` }, publisher: { "@type": "Organization", name: brand.name, logo: { "@type": "ImageObject", url: `https://${brand.domain}/brand/yashal-logo-dark.png` } }, mainEntityOfPage: { "@type": "WebPage", "@id": canonical }, inLanguage: locale },
      { "@type": "BreadcrumbList", itemListElement: [
        { "@type": "ListItem", position: 1, name: copy.home, item: `https://${brand.domain}/${locale}/` },
        { "@type": "ListItem", position: 2, name: copy.library, item: `https://${brand.domain}${libraryPath(locale)}` },
        { "@type": "ListItem", position: 3, name: article.title, item: canonical },
      ] },
      ...(faqItems.length > 0 ? [{ "@type": "FAQPage", mainEntity: faqItems.map((item) => ({ "@type": "Question", name: item.question, acceptedAnswer: { "@type": "Answer", text: item.answer } })) }] : []),
    ],
  };

  return (
    <main id="main" className="library-article-page">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(graph) }} />
      <header className="library-article-header shell">
        <nav className="breadcrumbs" aria-label={locale === "fr" ? "Fil d’Ariane" : locale === "ar" ? "مسار الصفحة" : "Breadcrumb"}>
          <Link href={`/${locale}/`}>{copy.home}</Link><span aria-hidden="true">/</span><Link href={libraryPath(locale)}>{copy.library}</Link><span aria-hidden="true">/</span><span aria-current="page">{article.title}</span>
        </nav>
        <p className="kicker">{article.category}</p>
        <h1>{article.title}</h1>
        <p className="library-article-description">{article.description}</p>
        <div className="library-article-meta">
          <span>{copy.author} · {article.author}</span>
          <span>{copy.published} · <time dateTime={article.publishedAt}>{formatDate(locale, article.publishedAt)}</time></span>
          {article.updatedAt && article.updatedAt !== article.publishedAt && <span>{copy.updated} · <time dateTime={article.updatedAt}>{formatDate(locale, article.updatedAt)}</time></span>}
          <span>{article.readingTime}</span>
        </div>
      </header>

      <figure className="library-article-cover shell">
        <Image src={article.coverImage} alt={article.coverImageAlt} width={1200} height={630} priority sizes="(max-width: 90rem) 100vw, 1360px" />
        {!article.coverImage.startsWith("/assets/images/library/") && <figcaption>{copy.temporary}</figcaption>}
      </figure>

      <div className="library-article-layout shell">
        <aside className="library-toc" aria-label={copy.contents}>
          <strong>{copy.contents}</strong>
          <nav>{article.tableOfContents.map((item) => <a className={item.level === 3 ? "is-subsection" : undefined} key={item.id} href={`#${item.id}`}>{item.text}</a>)}</nav>
        </aside>
        <article className="library-article-body"><MarkdownArticle blocks={article.blocks} /></article>
      </div>

      <section className="library-article-cta shell">
        <div><p className="kicker">YASHAL STUDIOS</p><h2>{copy.ctaTitle}</h2><p>{copy.ctaText}</p></div>
        <Link className="button button-light" href={`/${locale}/contact/`}>{copy.ctaButton}</Link>
      </section>

      {related.length > 0 && (
        <section className="library-related shell" aria-labelledby="related-title">
          <p className="kicker">{copy.library}</p><h2 id="related-title">{copy.related}</h2>
          <div>{related.map((item) => <article key={item.slug}><span>{item.category} · {item.readingTime}</span><h3><Link href={libraryPath(locale, item.slug)}>{item.title}</Link></h3><p>{item.excerpt}</p></article>)}</div>
        </section>
      )}
    </main>
  );
}
