"use client";

/**
 * SponsorsClient — client-side sponsors section.
 *
 * Use this component when you need Sponsors inside a "use client" component
 * (e.g. the Opportunities page, HomepageAuthenticated).
 *
 * For the public homepage, use `Sponsors` (async Server Component) instead,
 * which fetches data server-side with ISR caching.
 */
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { getSponsors } from "@/features/partners/services/partnersApi";
import { toSponsorItems } from "@/features/partners/sponsorRecord";
import SponsorsMarquee from "./SponsorsMarquee";
import Title from "@/components/shared/Title";

export default function SponsorsClient() {
  const { t } = useTranslation();

  /*
   * Same key, same query function and so the same cached shape as the partners
   * page (`usePartnerSponsors`). This used to cache the bare array under
   * `["sponsors"]` while the partners page cached the whole envelope there, so
   * whichever screen ran second read the other's shape: the partners page then
   * said «لا يوجد رعاة» and the list pages dropped their logos. `select` keeps
   * the per-screen shape out of the cache.
   */
  const { data: sponsors = [], isLoading } = useQuery({
    queryKey: ["sponsors"],
    queryFn: getSponsors,
    select: (response) => toSponsorItems(response?.data),
    staleTime: 5 * 60 * 1000,
  });

  // Admin-managed content: with no approved sponsor the section is hidden,
  // heading included, rather than shown empty.
  if (!isLoading && sponsors.length === 0) return null;

  return (
    <div className="w-full relative home-section-spacing mx-auto 2xl:px-0 sponsors">
      <div className="home-section-heading-gap">
        <Title text={t("COMMON.FORSA.SPONSOR")} variant="default" hasMargin={false} />
      </div>

      {isLoading ? (
        <p className="text-center mb-5">{t("COMMON.LOADING")}</p>
      ) : (
        <SponsorsMarquee sponsors={sponsors} />
      )}
    </div>
  );
}
