import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";

import { getDictionary, hasLocale } from "@/app/[lang]/dictionaries";
import { defaultLocale, locales, type Locale } from "@/lib/i18n";
import { localizedAlternates } from "@/lib/seo/alternates";
import {
  blogCategories,
  getCategoryName,
  getCategoryBlurb,
} from "@/lib/blog/categories";
import { getAllPosts, getByCategory, getFeatured } from "@/lib/blog/posts";
import { BlogGradientDefs, BlogThumb } from "@/components/blog/blog-thumb";
import { Carousel } from "@/components/blog/_components/carousel";
import { NewsletterForm } from "@/components/blog/_components/newsletter-form";
import { Reveal } from "@/components/blog/_components/reveal";
import { Tabs } from "@/components/blog/_components/tabs";
import { MiniItem, PostCard, formatDate } from "@/components/blog/post-card";
import { SiteSearch } from "@/components/shared/site-search";
import { buildMarketingSearchIndex } from "@/lib/search/marketing-index";
import styles from "@/components/blog/blog.module.css";

// Localized SEO copy for the blog index. The blog dictionary has no
// metadata title/description keys, so they live here as a locale fallback
// (mirror of the `lib/seo/pages.ts` pattern for non-blog pages).
const BLOG_INDEX_SEO: Record<Locale, { title: string; description: string }> = {
  en: {
    title: "Blog | SEO Insight",
    description:
      "Field-tested playbooks on technical SEO, Core Web Vitals, WordPress and ranking in the new world of AI search.",
  },
  fr: {
    title: "Blog | SEO Insight",
    description:
      "Des guides éprouvés sur le SEO technique, les Core Web Vitals, WordPress et le référencement à l'ère de la recherche par IA.",
  },
};

export async function generateMetadata({
  params,
}: PageProps<"/[lang]/blog">): Promise<Metadata> {
  const { lang } = await params;
  const locale: Locale = (locales as readonly string[]).includes(lang)
    ? (lang as Locale)
    : defaultLocale;
  const { title, description } = BLOG_INDEX_SEO[locale];
  const { canonical, languages } = localizedAlternates("/blog", locale);
  return {
    title,
    description,
    alternates: { canonical, languages },
    openGraph: {
      title,
      description,
      url: canonical,
      locale: locale === "fr" ? "fr_FR" : "en_US",
    },
  };
}

// Placeholder channel data — replace with real videos later.
const VIDEOS = [
  {
    title: "I audited 10 WordPress sites live: here's what broke",
    dur: "14:22",
    views: "18K",
    illust: "search",
    tint: "coral",
  },
  {
    title: "Passing Core Web Vitals in 9 minutes",
    dur: "9:08",
    views: "32K",
    illust: "bars",
    tint: "blue",
  },
  {
    title: "GEO: how to rank inside ChatGPT, explained",
    dur: "22:41",
    views: "27K",
    illust: "spark",
    tint: "violet",
  },
  {
    title: "Schema markup from scratch: full tutorial",
    dur: "17:30",
    views: "11K",
    illust: "grid",
    tint: "amber",
  },
] as const;

export default async function BlogIndexPage({
  params,
}: PageProps<"/[lang]/blog">) {
  const { lang } = await params;
  if (!hasLocale(lang)) notFound();
  const fullDict = await getDictionary(lang);
  const dict = fullDict.blog;
  const searchRecords = buildMarketingSearchIndex(fullDict, lang);

  const all = getAllPosts(lang);
  const featured = getFeatured(lang);
  const big = featured[0] ?? all[0];
  const smalls = all.filter((p) => p.href !== big?.href).slice(0, 2);
  const ranked = all.slice(0, 5);
  const rows = blogCategories
    .map((c) => ({ category: c, posts: getByCategory(lang, c.slug) }))
    .filter((r) => r.posts.length > 0);
  const tabCats = rows.slice(0, 4);

  return (
    <div className={styles.scope}>
      <BlogGradientDefs />

      {/* hero + featured grid */}
      <section className={styles.blogHero}>
        <div className={styles.wrap}>
          <Reveal className={styles.reveal}>
            <span className={styles.eyebrow}>
              <span className={styles.dot} />
              {dict.eyebrow}
            </span>
            <h1>
              {dict.heroTitleLead}
              <br />
              <span className="text-gradient-brand">
                {dict.heroTitleAccent}
              </span>
            </h1>
            <p className={styles.lede}>{dict.heroLede}</p>
            <div className={styles.heroSearch}>
              <SiteSearch
                variant="bar"
                records={searchRecords}
                lang={lang}
                label={fullDict.nav.searchLabel}
                placeholder={fullDict.nav.searchPlaceholder}
              />
            </div>
          </Reveal>

          <div className={styles.featGrid}>
            <Reveal
              className={`${styles.featCol} ${styles.reveal}`}
              delay={0.07}
            >
              {smalls.map((post) => (
                <Link
                  key={post.href}
                  href={`/${lang}${post.href}`}
                  className={styles.featSm}
                >
                  <BlogThumb
                    illust={post.thumb.illust}
                    tint={post.tint}
                    badge={post.tags?.[0]}
                  />
                  <h3>{post.title}</h3>
                </Link>
              ))}
            </Reveal>

            {big ? (
              <Reveal className={styles.reveal} delay={0.14}>
                <Link href={`/${lang}${big.href}`} className={styles.featBig}>
                  <BlogThumb
                    illust={big.thumb.illust}
                    tint={big.tint}
                    badge={big.tags?.[0]}
                  />
                  <h2>{big.title}</h2>
                  <p>{big.excerpt}</p>
                  <div className={styles.pcFoot}>
                    <span className={styles.avatar}>{big.author.initials}</span>
                    <span>{big.author.name}</span>
                    <span className={styles.dotSep} />
                    <span>{formatDate(big.date, lang, true)}</span>
                    <span className={styles.dotSep} />
                    <span>
                      {big.readingMinutes} {dict.minRead}
                    </span>
                  </div>
                </Link>
              </Reveal>
            ) : null}

            <Reveal
              className={`${styles.featCol} ${styles.featColRight} ${styles.reveal}`}
              delay={0.21}
            >
              <div className={styles.featList}>
                <div className={styles.flHead}>{dict.mostRead}</div>
                {ranked.map((post, i) => (
                  <MiniItem
                    key={post.href}
                    post={post}
                    lang={lang}
                    rank={i + 1}
                  />
                ))}
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* topic rows */}
      {rows.map((row) => (
        <section key={row.category.slug} className={styles.block}>
          <div className={styles.wrap}>
            <Reveal className={styles.reveal}>
              <Carousel
                title={getCategoryName(row.category, lang)}
                blurb={getCategoryBlurb(row.category, lang)}
                viewAllHref={`/${lang}/blog/${row.category.slug}`}
                viewAllLabel={dict.viewAll}
              >
                {row.posts.map((post) => (
                  <PostCard key={post.href} post={post} lang={lang} />
                ))}
              </Carousel>
            </Reveal>
          </div>
        </section>
      ))}

      {/* youtube band */}
      <section className={styles.ytBand}>
        <div className={styles.wrap}>
          <Reveal className={styles.reveal}>
            <Carousel title={dict.ytTitle} blurb={dict.ytLede}>
              {VIDEOS.map((v) => (
                <article key={v.title} className={styles.ytCard}>
                  <BlogThumb
                    illust={v.illust}
                    tint={v.tint}
                    className={styles.ytThumb}
                  >
                    <span className={styles.play}>
                      <svg
                        width="20"
                        height="20"
                        viewBox="0 0 24 24"
                        fill="currentColor"
                        aria-hidden="true"
                      >
                        <path d="M8 5v14l11-7z" />
                      </svg>
                    </span>
                    <span className={styles.dur}>{v.dur}</span>
                  </BlogThumb>
                  <h4>{v.title}</h4>
                  <div className={styles.ytMeta}>
                    <span>SEO Insight</span>
                    <span className={styles.dotSep} />
                    <span>
                      {v.views} {dict.views}
                    </span>
                  </div>
                </article>
              ))}
            </Carousel>
          </Reveal>
        </div>
      </section>

      {/* browse by topic tabs */}
      <section className={styles.block}>
        <div className={styles.wrap}>
          <Reveal className={styles.reveal}>
            <div className={styles.sectionHead}>
              <span className={styles.eyebrow}>
                <span className={styles.dot} />
                {dict.browseEyebrow}
              </span>
              <h2 style={{ fontSize: "clamp(28px,3.4vw,40px)", marginTop: 16 }}>
                {dict.browseTitle}
              </h2>
            </div>
            <Tabs
              tabs={tabCats.map((row) => ({
                id: row.category.slug,
                label: getCategoryName(row.category, lang),
                panel: (
                  <div className={styles.tabGrid}>
                    {row.posts.slice(0, 3).map((post) => (
                      <PostCard key={post.href} post={post} lang={lang} />
                    ))}
                  </div>
                ),
              }))}
            />
          </Reveal>
        </div>
      </section>

      {/* newsletter */}
      <section className={styles.block} style={{ paddingTop: 10 }}>
        <div className={styles.wrap}>
          <Reveal className={styles.reveal}>
            <div className={styles.nlBand}>
              <div className={styles.glow} />
              <div>
                <div className={styles.nlIc}>
                  <svg
                    width="22"
                    height="22"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    aria-hidden="true"
                  >
                    <rect x="2" y="4" width="20" height="16" rx="2" />
                    <path d="m22 7-10 5L2 7" />
                  </svg>
                </div>
                <h2>{dict.newsletterTitle}</h2>
                <p>{dict.newsletterBody}</p>
              </div>
              <div>
                <NewsletterForm
                  placeholder={dict.newsletterPlaceholder}
                  ariaLabel={dict.newsletterLabel}
                  submitLabel={dict.subscribe}
                  submittedLabel={dict.subscribed}
                />
                <p className={styles.nlNote}>{dict.newsletterNote}</p>
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      {/* cta */}
      <section className={styles.block} style={{ paddingTop: 20 }}>
        <div className={styles.wrap}>
          <Reveal className={styles.reveal}>
            <div className={styles.ctaBand}>
              <div className={styles.glow} />
              <h2>{dict.ctaTitle}</h2>
              <p>{dict.ctaBody}</p>
              <div className={styles.ctaRow}>
                <Link
                  href={`/${lang}/contact`}
                  className={`${styles.btn} ${styles.btnPrimary}`}
                >
                  {dict.ctaPrimary}
                </Link>
                <Link
                  href={`/${lang}/services`}
                  className={`${styles.btn} ${styles.btnGhost}`}
                >
                  {dict.ctaSecondary}
                </Link>
              </div>
            </div>
          </Reveal>
        </div>
      </section>
    </div>
  );
}
