// app/[locale]/page.tsx
import { isLocale } from "@/lib/i18n";
import type { Locale } from "@/lib/i18n";

import { getSections, listArticles } from "@/lib/api";
import ArticleCard from "@/components/ArticleCard";
import Sidebar from "@/components/Sidebar";
import type { ArticleMeta } from "@/lib/types";

type Params = { locale: string };
type ParamsPromise = Promise<Params>;

export default async function HomePage({
  params,
}: {
  params: ParamsPromise;
}) {
  // 👇 leemos locale REAL de la ruta: /es, /en, /zh
  const { locale: rawLocale } = await params;
  const locale: Locale = isLocale(rawLocale) ? rawLocale : "en";

  const sections = await getSections();

  // 👇 pedimos artículos filtrados en backend por locale
  const rawItems = await listArticles({ limit: 20, offset: 0, locale });

  // 👇 defensa extra: si alguno viene sin locale, lo tiramos
  const sameLocale = (a: ArticleMeta) => !a.locale || a.locale === locale;
  const items = rawItems.filter(sameLocale);

  const hero = items[0];
  const rest = items.slice(1);

  const latest = items.slice(0, 12);

  const rawHot = await listArticles({
    section: "entretenimiento",
    limit: 8,
    offset: 0,
    locale,
  });
  const hot = rawHot.filter(sameLocale);

  return (
    <main className="container">
      {hero ? (
        <div className="news-hero">
          <ArticleCard a={hero} locale={locale} variant="hero" />
        </div>
      ) : null}

      <div className="grid-main">
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          {items.length === 0 ? (
            <div className="card">
              <h2 className="h2">
                {locale === "es"
                  ? "Todavía no hay artículos"
                  : locale === "zh"
                    ? "暂时没有文章"
                    : "No articles yet"}
              </h2>
              <p className="p">
                {locale === "es"
                  ? "Agregá un .md en backend/content/..."
                  : locale === "zh"
                    ? "请在 backend/content/... 中添加 .md 文件"
                    : "Add a .md in backend/content/..."}
              </p>
            </div>
          ) : (
            <div className="news-grid">
              {rest.map((x) => (
                <ArticleCard
                  key={x.slug}
                  a={x}
                  locale={locale}
                  variant="teaser"
                />
              ))}
            </div>
          )}
        </div>

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