import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { Breadcrumbs } from "./Breadcrumbs";
import { LibraryFilters, type LibraryCardData } from "./LibraryFilters";
import { brand, type Locale } from "@/content/site";
import { libraryPath } from "@/content/libraryPaths";
import { getArticleSummaries } from "@/lib/library";

export const libraryLabels = {
  fr: {
    eyebrow: "LA BIBLIOTHÈQUE YASHAL",
    title: "Des idées pour faire avancer les marques.",
    description: "Des conseils concrets sur le marketing, la vidéo, le SEO, le branding et la croissance digitale.",
    breadcrumb: "Bibliothèque",
    featured: "Article à la une",
    allArticles: "Tous les articles",
    allDescription: "Explorez les ressources publiées et filtrez-les selon le sujet qui vous intéresse.",
    read: "Lire l’article",
    temporary: "Visuel temporaire",
    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",
  },
  en: {
    eyebrow: "YASHAL KNOWLEDGE",
    title: "Ideas built to move brands forward.",
    description: "Practical insights on marketing, video, SEO, branding and digital growth.",
    breadcrumb: "Knowledge",
    featured: "Featured article",
    allArticles: "All articles",
    allDescription: "Explore published resources and filter them by the subject most relevant to you.",
    read: "Read article",
    temporary: "Temporary visual",
    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",
  },
  ar: {
    eyebrow: "معرفة YASHAL",
    title: "أفكار تدفع العلامات إلى الأمام.",
    description: "رؤى عملية حول التسويق وإنتاج الفيديو وتحسين الظهور والعلامة والنمو الرقمي.",
    breadcrumb: "المعرفة",
    featured: "مقال مميّز",
    allArticles: "كل المقالات",
    allDescription: "ستظهر هنا فقط المقالات العربية التي خضعت لمراجعة تحريرية مهنية.",
    read: "اقرأ المقال",
    temporary: "صورة مؤقتة",
    ctaTitle: "هل تبحث عن وكالة تسويق في فاس؟",
    ctaText: "تجمع YASHAL بين الاستراتيجية وإنتاج الفيديو وتصميم المواقع وتحسين الظهور والمحتوى لبناء حضور يجذب الانتباه ويدعم النمو.",
    ctaButton: "لنتحدث عن مشروعك",
  },
} satisfies Record<Locale, Record<string, string>>;

export function createLibraryMetadata(locale: Locale): Metadata {
  const copy = libraryLabels[locale];
  const canonical = libraryPath(locale);
  return {
    title: copy.title,
    description: copy.description,
    alternates: {
      canonical,
      languages: {
        fr: libraryPath("fr"),
        en: libraryPath("en"),
        ar: libraryPath("ar"),
        "x-default": libraryPath("fr"),
      },
    },
    openGraph: {
      type: "website",
      title: copy.title,
      description: copy.description,
      url: canonical,
      images: [{ url: "/social/yashal-og.png", width: 1200, height: 630 }],
    },
    twitter: {
      card: "summary_large_image",
      title: copy.title,
      description: copy.description,
      images: ["/social/yashal-og.png"],
    },
  };
}

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 LibraryPage({ locale }: { locale: Locale }) {
  const copy = libraryLabels[locale];
  const articles = getArticleSummaries(locale);
  const featured = articles.find((article) => article.featured) ?? articles[0];
  const cardData: LibraryCardData[] = articles.map((article) => ({
    slug: article.slug,
    title: article.title,
    excerpt: article.excerpt,
    category: article.category,
    tags: article.tags,
    coverImage: article.coverImage,
    coverImageAlt: article.coverImageAlt,
    publishedAt: article.publishedAt,
    readingTime: article.readingTime,
    href: libraryPath(locale, article.slug),
  }));
  const canonical = `https://${brand.domain}${libraryPath(locale)}`;
  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: locale === "fr" ? "Accueil" : locale === "ar" ? "الرئيسية" : "Home", item: `https://${brand.domain}/${locale}/` },
      { "@type": "ListItem", position: 2, name: copy.breadcrumb, item: canonical },
    ],
  };

  return (
    <main id="main" className="library-page">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }} />
      <header className="library-hero shell">
        <Breadcrumbs locale={locale} current={copy.breadcrumb} />
        <p className="kicker">{copy.eyebrow}</p>
        <h1>{copy.title}</h1>
        <p>{copy.description}</p>
      </header>

      {featured && (
        <section className="library-featured shell" aria-labelledby="featured-title">
          <p className="kicker">{copy.featured}</p>
          <article>
            <div className="library-featured-media">
              <Image src={featured.coverImage} alt={featured.coverImageAlt} fill priority sizes="(max-width: 64rem) 100vw, 55vw" />
              {!featured.coverImage.startsWith("/assets/images/library/") && <small>{copy.temporary}</small>}
            </div>
            <div className="library-featured-copy">
              <div className="library-card-meta"><span>{featured.category}</span><span><time dateTime={featured.publishedAt}>{formatDate(locale, featured.publishedAt)}</time> · {featured.readingTime}</span></div>
              <h2 id="featured-title">{featured.title}</h2>
              <p>{featured.excerpt}</p>
              <Link className="text-link" href={libraryPath(locale, featured.slug)}>{copy.read}</Link>
            </div>
          </article>
        </section>
      )}

      <section className="library-all shell" aria-labelledby="library-all-title">
        <div className="section-heading">
          <div><p className="kicker">{copy.eyebrow}</p><h2 id="library-all-title">{copy.allArticles}</h2></div>
          <p>{copy.allDescription}</p>
        </div>
        <LibraryFilters locale={locale} articles={cardData} />
      </section>

      <section className="library-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>
    </main>
  );
}
