import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import { ChevronRight } from "lucide-react";
import { findGroup, toolsByGroup, TOOL_GROUPS } from "@/lib/tool-catalog";
import { ToolGrid } from "@/components/tool-grid";
import { buildBreadcrumbs, jsonLdScript } from "@/lib/seo";
import { getSetting } from "@/lib/settings";

// Reads site.url from DB at request time (matches root layout) so /admin/site
// domain changes propagate to JSON-LD without rebuild.
export const dynamic = "force-dynamic";

export async function generateStaticParams() {
  return TOOL_GROUPS.map((g) => ({ group: g.slug }));
}

type Props = { params: Promise<{ group: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { group } = await params;
  const g = findGroup(group);
  if (!g) return { title: "Không tìm thấy — Tử Vi Số" };
  return {
    title: `${g.title} — Tử Vi Số`,
    description: g.intro.slice(0, 160),
    openGraph: {
      title: g.title,
      description: g.intro.slice(0, 200),
      type: "website",
    },
  };
}

export default async function ToolGroupLandingPage({ params }: Props) {
  const { group } = await params;
  const g = findGroup(group);
  if (!g) notFound();

  const tools = toolsByGroup(g.key);
  const otherGroups = TOOL_GROUPS.filter((x) => x.slug !== g.slug);
  const siteUrl = await getSetting("site.url");

  const breadcrumbLd = buildBreadcrumbs(siteUrl, [
    { name: "Trang chủ", href: "/" },
    { name: g.label, href: `/${g.slug}` },
  ]);
  const itemListLd = {
    "@context": "https://schema.org",
    "@type": "ItemList",
    name: g.title,
    numberOfItems: tools.length,
    itemListElement: tools.map((t, i) => ({
      "@type": "ListItem",
      position: i + 1,
      url: `${siteUrl}/${t.slug}`,
      name: t.title,
    })),
  };

  return (
    <div className="bg-bg-base min-h-screen">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: jsonLdScript(breadcrumbLd) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: jsonLdScript(itemListLd) }}
      />
      <div className="mx-auto max-w-5xl px-4 py-8 lg:py-14">
        {/* Breadcrumb */}
        <nav aria-label="Đường dẫn" className="text-ink-muted mb-6 flex items-center gap-2 text-xs">
          <Link href="/" className="hover:text-brand-gold">
            Trang chủ
          </Link>
          <ChevronRight className="h-3 w-3" aria-hidden="true" />
          <span className="text-ink-secondary">{g.label}</span>
        </nav>

        {/* Header */}
        <header className="mb-10 text-center lg:mb-14">
          <div className="ornament-line text-brand-gold-soft mb-3 text-xs tracking-[0.22em] uppercase">
            {g.ornament}
          </div>
          <h1 className="font-display text-ink-primary text-3xl font-semibold lg:text-5xl">
            {g.title}
          </h1>
          <p className="text-ink-secondary mx-auto mt-4 max-w-[60ch] text-sm leading-relaxed lg:text-base">
            {g.intro}
          </p>
        </header>

        {/* Tool grid */}
        <ToolGrid tools={tools} />

        {/* Other groups */}
        <section className="mt-16 lg:mt-24">
          <h2 className="font-display text-ink-primary mb-6 text-xl font-semibold lg:text-2xl">
            Khám phá nhóm khác
          </h2>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {otherGroups.map((og) => (
              <Link
                key={og.slug}
                href={`/${og.slug}`}
                className="group border-stroke-subtle bg-bg-elevated/40 hover:border-brand-gold/40 rounded-xl border p-4 transition lg:p-5"
              >
                <div className="text-brand-gold-soft text-xs tracking-[0.18em] uppercase">
                  {og.ornament}
                </div>
                <div className="font-display text-ink-primary group-hover:text-brand-gold mt-1 text-base font-semibold">
                  {og.label}
                </div>
                <p className="text-ink-muted mt-1 line-clamp-2 text-xs">{og.intro}</p>
              </Link>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}
