// /opt/newsoras/app/main/frontend/app/[locale]/section/[section]/page.tsx
import { sectionLabel } from "@/lib/sections";
import { listArticles, getSections } from "@/lib/api";
import ArticleCard from "@/components/ArticleCard";
import Sidebar from "@/components/Sidebar";
import type { SectionId, ArticleMeta } from "@/lib/types";
import { isLocale } from "@/lib/i18n";
import type { Locale } from "@/lib/i18n";
import type { Metadata } from "next";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://newsoras.com";

// 👇 NUEVO: SEO para secciones
export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; section: SectionId }>;
}): Promise<Metadata> {
  const { locale: rawLocale, section } = await params;
  const locale: Locale = isLocale(rawLocale) ? rawLocale : "en";

  const sectionName = sectionLabel(locale, section);

  const baseDescByLocale: Record<Locale, string> = {
    es: `Noticias y análisis de ${sectionName} en Newsoras, con contexto histórico y enfoque en el futuro.`,
    en: `News and analysis about ${sectionName} at Newsoras, with historical context and future focus.`,
    zh: `关于 ${sectionName} 的新闻与分析，提供背景与前瞻视角。`,
  };

  const title = `${sectionName} | Newsoras`;
  const description = baseDescByLocale[locale] ?? baseDescByLocale.en;

  const url = `${SITE_URL}/${locale}/section/${section}`;

  return {
    title,
    description,
    alternates: {
      canonical: url,
      languages: {
        es: `${SITE_URL}/es/section/${section}`,
        en: `${SITE_URL}/en/section/${section}`,
        zh: `${SITE_URL}/zh/section/${section}`,
      },
    },
    openGraph: {
      url,
      title,
      description,
      type: "website",
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
    },
  };
}

export default async function SectionPage({
  params,
}: {
  params: Promise<{ locale: string; section: SectionId }>;
}) {
  const { locale: rawLocale, section } = await params;
  const locale: Locale = isLocale(rawLocale) ? rawLocale : "en";

  const sections = await getSections();

  const rawItems = await listArticles({ section, limit: 20, offset: 0, locale });
  const rawLatest = await listArticles({ limit: 12, offset: 0, locale });
  const rawHot = await listArticles({
    section: "entretenimiento",
    limit: 8,
    offset: 0,
    locale,
  });

  const sameLocale = (a: ArticleMeta) => a.locale === locale;
  const items = rawItems.filter(sameLocale);
  const latest = rawLatest.filter(sameLocale);
  const hot = rawHot.filter(sameLocale);

  const copy =
    locale === "es"
      ? {
        subtitle: "Actualizaciones y artículos seleccionados.",
        emptyTitle: "Todavía no hay artículos en esta sección",
        emptyBody: `Agregá un .md en backend/content/${section}/`,
      }
      : locale === "zh"
        ? {
          subtitle: "更新与精选文章。",
          emptyTitle: "该分类暂时没有文章",
          emptyBody: `把 .md 放到 backend/content/${section}/`,
        }
        : {
          subtitle: "Updates and curated articles.",
          emptyTitle: "No articles in this section yet",
          emptyBody: `Add a .md in backend/content/${section}/`,
        };

  return (
    <main className="container">
      <div style={{ marginBottom: 18 }}>
        <h1 className="h1">{sectionLabel(locale, section)}</h1>
        <p className="p">{copy.subtitle}</p>
      </div>

      <div className="grid-main">
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          {items.length === 0 ? (
            <div className="card">
              <h2 className="h2">{copy.emptyTitle}</h2>
              <p className="p">{copy.emptyBody}</p>
            </div>
          ) : (
            items.map((a) => (
              <ArticleCard key={a.slug} a={a} locale={locale} variant="teaser" />
            ))
          )}
        </div>

        <Sidebar sections={sections} latest={latest} hot={hot} locale={locale} />
      </div>
    </main>
  );
}
