import { getDictionary } from "@/i18n";
import { sanityFetch } from "@/sanity/client";
import { POSTS_QUERY } from "@/sanity/queries";
import { PageHeader, Container, SectionHeading, JoinCta } from "@/components/ui";
import { Reveal } from "@/components/reveal";
import { PostCard, FeaturedPostCard, PostListItem } from "@/components/cards";

/* eslint-disable @typescript-eslint/no-explicit-any */

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const d = getDictionary(locale);
  return { title: d.blog.title, description: d.blog.lead };
}

export default async function BlogPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const dict = getDictionary(locale);
  const posts = await sanityFetch<any[]>(POSTS_QUERY, {}, []);

  const featured = posts?.[0];
  const sideList = (posts || []).slice(1, 5);
  const rest = (posts || []).slice(5);

  return (
    <>
      <PageHeader eyebrow={dict.nav.blog} title={dict.blog.title} lead={dict.blog.lead} />

      {posts.length ? (
        <>
          {/* Featured + latest list */}
          <section className="py-16 sm:py-20">
            <Container>
              <div className="grid gap-8 lg:grid-cols-[1.1fr_1fr]">
                <Reveal>
                  <FeaturedPostCard post={featured} locale={locale} dict={dict} />
                </Reveal>
                {sideList.length > 0 && (
                  <Reveal delay={0.1}>
                    <div className="flex flex-col divide-y divide-line rounded-3xl border border-line bg-surface p-2">
                      {sideList.map((p) => (
                        <PostListItem key={p._id} post={p} locale={locale} dict={dict} />
                      ))}
                    </div>
                  </Reveal>
                )}
              </div>
            </Container>
          </section>

          {/* Remaining posts grid */}
          {rest.length > 0 && (
            <section className="bg-surface py-16 sm:py-20">
              <Container>
                <SectionHeading title={dict.blog.latest} />
                <div className="mt-10 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                  {rest.map((p, i) => (
                    <Reveal key={p._id} delay={(i % 3) * 0.06}>
                      <PostCard post={p} locale={locale} dict={dict} />
                    </Reveal>
                  ))}
                </div>
              </Container>
            </section>
          )}
        </>
      ) : (
        <Container>
          <p className="py-20 text-center text-muted">{dict.empty.posts}</p>
        </Container>
      )}

      <JoinCta locale={locale} dict={dict} />
    </>
  );
}
