"use client";

import { useQuery } from "@tanstack/react-query";
import { FileText, FolderOpen, BookOpen } from "lucide-react";
import { publicApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";

/**
 * Exactly what GET /public/stats returns.
 *
 * <p>This used to name three fields the endpoint has never sent —
 * totalPapers, totalCategories, publishedPapers — so all three read as
 * undefined and the "?? 0" beneath them turned the journal's own front page
 * into a row of zeros: no papers, no categories, nothing published.
 */
interface PublicStats {
  /** Published through this platform. The archive is counted separately. */
  papers: number;
  categories: number;
  /** Distinct volumes in the legacy archive (Vols 1-17). */
  archiveVolumes: number;
  /** Articles imported from the legacy site. */
  archiveArticles: number;
}

export function StatsBar() {
  const { t } = useTranslation("LANDING");

  const { data: stats, isLoading } = useQuery<PublicStats>({
    queryKey: ["public-stats"],
    queryFn: async () => {
      const res = await publicApi.stats();
      return res.data;
    },
    staleTime: 5 * 60 * 1000,
  });

  const items = [
    {
      label: t("stats.total_papers_label", "Total Papers"),
      // Everything the journal has published, the seventeen archived volumes
      // included — not just what has come through this platform.
      value: (stats?.archiveArticles ?? 0) + (stats?.papers ?? 0),
      icon: FileText,
    },
    {
      label: t("stats.categories_label", "Categories"),
      value: stats?.categories ?? 0,
      icon: FolderOpen,
    },
    {
      label: t("stats.published_papers_label", "Published Papers"),
      value: stats?.papers ?? 0,
      icon: BookOpen,
    },
  ];

  return (
    <section className="bg-indigo-600">
      <div className="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-3">
          {items.map((item) => {
            const Icon = item.icon;
            return (
              <div
                key={item.label}
                className="flex flex-col items-center gap-2 rounded-xl bg-indigo-500/30 p-6 text-center backdrop-blur-sm"
              >
                <Icon className="h-8 w-8 text-indigo-200" />
                <span className="text-3xl font-bold text-white">
                  {isLoading ? (
                    <span className="inline-block h-8 w-16 animate-pulse rounded bg-indigo-400/50" />
                  ) : (
                    item.value.toLocaleString()
                  )}
                </span>
                <span className="text-sm font-medium text-indigo-100">
                  {item.label}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
