import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import {
  CATEGORIES,
  CATEGORY_PATH,
  categoryLabel,
  isLocale,
  type Category,
} from '@ai-radar/shared';
import { getCategory } from '@/lib/api';
import { getDictionary } from '@/lib/dictionary';
import { SITE, absoluteUrl, localeAlternates } from '@/lib/site';
import { StandardCard } from '@/components/cards/StoryCards';
import { RowList, EmptyState } from '@/components/sections/Section';
import { AdSlot } from '@/components/ads/AdSlot';

const SEGMENT_TO_CATEGORY = Object.fromEntries(
  CATEGORIES.map((c) => [CATEGORY_PATH[c], c]),
) as Record<string, Category>;

type Params = Promise<{ lang: string; category: string }>;

export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
  const { lang, category } = await params;
  const resolved = SEGMENT_TO_CATEGORY[category];
  if (!isLocale(lang) || !resolved) return {};

  const label = categoryLabel(resolved, lang);
  const path = `/${category}`;

  return {
    title: label,
    description: `${label} — ${SITE[lang].tagline}`,
    alternates: {
      canonical: absoluteUrl(`/${lang}${path}`),
      languages: localeAlternates(path),
    },
  };
}

/**
 * A category archive.
 *
 * Deliberately simpler than the homepage: three standard cards for the
 * most recent, then rows. No hero — an archive has no "today", so
 * promoting one item would be arbitrary.
 */
export default async function CategoryPage({ params }: { params: Params }) {
  const { lang, category } = await params;
  if (!isLocale(lang)) notFound();

  const resolved = SEGMENT_TO_CATEGORY[category];
  if (!resolved) notFound();

  const dict = getDictionary(lang);
  const { posts } = await getCategory(resolved, lang, 40);
  const label = categoryLabel(resolved, lang);

  return (
    <main id="main" className="page" style={{ paddingBlock: 'var(--s10)' }}>
      <header style={{ maxWidth: 'var(--measure)' }}>
        <h1 className="t-h1">{label}</h1>
      </header>

      {posts.length === 0 ? (
        <EmptyState title={dict.home.emptyTitle} body={dict.home.emptyBody} />
      ) : (
        <>
          {/* Most recent get a card; the tail becomes rows. Same
              decreasing-weight principle as the homepage. */}
          <div className="grid-2" style={{ marginTop: 'var(--s8)' }}>
            {posts.slice(0, 2).map((post) => (
              <StandardCard key={post.id} post={post} locale={lang} dict={dict} />
            ))}
          </div>

          {posts.length > 2 && (
            <div style={{ marginTop: 'var(--s10)' }}>
              <RowList posts={posts.slice(2)} locale={lang} />
            </div>
          )}

          <AdSlot slotKey="home_between_sections" label={dict.meta.advertisement} />
        </>
      )}
    </main>
  );
}
