"use client";

import { useTranslation } from "react-i18next";
import Loader from "@/components/ui/Loader";
import Button from "@/components/ui/Button";
import ListingCard from "./ProfileListingCard";
import CertificatesGrid from "./ProfileCertificatesGrid";
import {
  type CertificateItem,
  type OpportunityItem,
} from "./commonProfileTypes";

/**
 * The results: a loader, the certificates grid, the listing cards, or the empty
 * message.
 *
 * Card keys combine the kind with the id on purpose — volunteer and learn-serve
 * opportunities are separate backend models with their own id sequences, so a
 * plain `item.id` collides between the two.
 */
export default function ProfileListingsGrid({
  loading,
  section,
  certificates,
  items,
  error, retry, hasMore, loadingMore, loadMore,
}: {
  loading: boolean;
  section: string;
  certificates: CertificateItem[];
  items: OpportunityItem[];
  error: string | null;
  retry: () => void;
  hasMore: boolean;
  loadingMore: boolean;
  loadMore: () => void;
}) {
  const { t } = useTranslation();

  return (
    <>
        {error && <div role="alert" className="space-y-3 py-6 text-center">
          <p className="text-red-600">{error}</p>
          <Button onClick={retry}>{t("COMMON.RETRY")}</Button>
        </div>}
        {loading ? (
          <Loader inline className="py-20" />
        ) : section === "certificates" ? (
          <CertificatesGrid certificates={certificates} />
        ) : items.length ? (
          <div className="listing-card-grid grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4">
            {items.map((item) => (
              // Volunteer and learn-serve opportunities are separate backend
              // models with their own id sequences, so a plain `item.id` can
              // collide between the two (e.g. a volunteer_opportunity #18 and
              // a learn_serve_opportunity #18) once the "All" tab combines
              // them — React then reuses that DOM node across tab switches
              // instead of rendering the new item, which looked like the
              // first card getting "stuck" duplicated across tabs.
              <ListingCard
                key={`${item.opportunity_type ?? "item"}-${item.id}`}
                item={item}
                isEvent={section === "events"}
              />
            ))}
          </div>
        ) : !error ? (
          <p className="py-8 text-center text-lg text-secondary-102">
            {t(
              section === "events"
                ? "COMMON.NO_EVENTS_AVAILABLE"
                : "COMMON.NO_VOLUNTEER_OPPORTUNITIES_AVAILABLE"
            )}
          </p>
        ) : null}
        {hasMore && !error && <div className="flex justify-center py-6"><Button onClick={loadMore} disabled={loadingMore}>
          {t(loadingMore ? "COMMON.LOADING" : "COMMON.VIEW_MORE")}
        </Button></div>}
    </>
  );
}
