"use client";

import Fuse from "fuse.js";
import { type Locale, useLocale, useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import { type ReactNode, useMemo } from "react";
import JrPostCard from "@/components/blog/JrPostCard";
import { categoryIdFromSlug } from "@/config/blog/categories";
import type { PostMeta } from "@/lib/blog/schema";

export default function BlogIndexView({
  posts,
  children,
}: {
  posts: PostMeta[];
  // Server-rendered unfiltered grid (all posts), passed as children so it is
  // prerendered for SEO and reused as the Suspense fallback. Category pills and
  // the search field live in the sticky sub-nav (BlogSubNav), not here.
  children: ReactNode;
}) {
  const t = useTranslations("BlogPage");
  const locale = useLocale() as Locale;
  const params = useSearchParams();
  const query = params.get("q")?.trim() ?? "";
  const categoryParam = params.get("category");
  const activeCategory = categoryParam ? categoryIdFromSlug(categoryParam, locale) : null;

  const fuse = useMemo(
    () => new Fuse(posts, { keys: ["title", "description"], threshold: 0.3, ignoreLocation: true }),
    [posts],
  );

  const isFiltered = query.length > 0 || activeCategory !== null;

  const filtered = useMemo(() => {
    if (!isFiltered) return [];
    const base = query ? fuse.search(query).map((r) => r.item) : posts;
    return activeCategory ? base.filter((p) => p.category === activeCategory) : base;
  }, [isFiltered, query, activeCategory, fuse, posts]);

  return (
    <section
      id="topics"
      className="scroll-mt-[140px] border-t border-hairline bg-surface-container-low px-6 py-[76px] lg:px-16 lg:py-[104px]"
    >
      <div className="mx-auto max-w-[1440px]">
        <h2 className="font-display text-[31px] font-normal leading-[1.18] text-foreground lg:text-[40px] lg:leading-[1.15]">
          {t("topics.title")}
        </h2>
        <p className="mt-4 max-w-[560px] text-base leading-[1.7] text-on-surface-variant">
          {t("topics.intro")}
        </p>

        <div className="mt-10">
          {isFiltered ? (
            filtered.length === 0 ? (
              <p className="text-on-surface-variant">{t("topics.noResults")}</p>
            ) : (
              <>
                <p className="mb-6 text-[13px] text-on-surface-variant">
                  {t("topics.resultsFor", { count: filtered.length, query })}
                </p>
                <div className="grid gap-6 [grid-template-columns:repeat(auto-fill,minmax(320px,1fr))]">
                  {filtered.map((p) => (
                    <JrPostCard key={p.postId} post={p} locale={locale} variant="standard" />
                  ))}
                </div>
              </>
            )
          ) : (
            children
          )}
        </div>
      </div>
    </section>
  );
}
