"use client";

import { useBreakpoint } from "./partnerCarousel";
import { useTranslation } from "react-i18next";
import "react-multi-carousel/lib/styles.css";
import { useQuery } from "@tanstack/react-query";
import { getSponsors } from "@/features/partners/services/partnersApi";
import { getDropdownChoices } from "@/features/shared/services/dropdowns";
import { useLanguageStore } from "@/store/languageStore";
import {
  toSponsorTile,
  type SponsorRecord,
} from "@/features/partners/sponsorRecord";

/** The label a financial tier is distinguished by, on `_type_of_support`. */
function financialTier(tier: string) {
  return (sponsor: SponsorRecord) =>
    sponsor._sponsor_type?.value_en === "Financial sponsor" &&
    sponsor._type_of_support?.value_en === tier;
}

/** A sponsor type matched on a substring of its English label. */
function sponsorTypeContains(fragment: string) {
  return (sponsor: SponsorRecord) =>
    sponsor._sponsor_type?.value_en?.toLowerCase().includes(fragment) ?? false;
}

const SPONSOR_CATEGORIES: Array<{
  type: string;
  subtitleKey: string;
  matches: (sponsor: SponsorRecord) => boolean;
}> = [
  {
    type: "media",
    subtitleKey: "COMMON.ADS_MEDIA.SPONSOR",
    matches: sponsorTypeContains("media"),
  },
  {
    type: "gold",
    subtitleKey: "COMMON.GOLD.SPONSOR",
    matches: financialTier("Gold"),
  },
  {
    type: "silver",
    subtitleKey: "COMMON.SILVER.SPONSOR",
    matches: financialTier("Silver"),
  },
  {
    type: "bronze",
    subtitleKey: "COMMON.BRONZE.SPONSOR",
    matches: financialTier("Bronze"),
  },
  {
    type: "in-kind",
    subtitleKey: "COMMON.IN-KIND SUPPORT.SPONSOR",
    matches: sponsorTypeContains("supporting"),
  },
];

/**
 * The partners page's sponsor list, grouped into its display categories.
 *
 * The category colours are keyed off the sponsor type's label, which is why
 * the mapping is a lookup rather than an index.
 */
export function usePartnerSponsors() {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: ["sponsors"],
    queryFn: getSponsors,
  });

  const { isLoading: sponsorTypeLoading } = useQuery({
    queryKey: ["dropdownChoices", "sponsor_type"],
    queryFn: () => getDropdownChoices("sponsor_type"),
    enabled: !!selectedLanguage,
  });

  const { items: itemsPerBreakpoint } = useBreakpoint();

  const getColorForSponsorType = (type: string) => {
    switch (type.toLowerCase()) {
      case "media":
        return "#5271FF";
      case "gold":
        return "#29246D";
      case "silver":
        return "#FC9555";
      case "bronze":
        return "#70B4C2";
      case "in-kind":
        return "#6D429ADB";
      default:
        return "#5271FF";
    }
  };

  /**
   * The five display categories, as a table.
   *
   * Was five copies of the same filter-then-map block, each annotating its
   * predicate `(sponsor: any)` and its projection with a two-field inline
   * shape that declared both fields non-null. The only thing that actually
   * varied between them was the predicate, so that is all the table carries.
   *
   * The two shapes of predicate are deliberate and come from the data: the
   * media and in-kind rows match a *substring* of the sponsor type ("Media
   * sponsor", "Supporting sponsor"), while the three financial tiers all share
   * one sponsor type and are told apart by `_type_of_support`.
   */
  const sponsorCategories = SPONSOR_CATEGORIES.map((category) => ({
    title: t("COMMON.FORSA.SPONSOR"),
    subtitle: t(category.subtitleKey),
    type: category.type,
    sponsors: (data?.data ?? []).filter(category.matches).map(toSponsorTile),
  }));

  const filteredSponsorCategories = sponsorCategories.filter(
    (category) => category.sponsors.length > 0
  );

  return {
    selectedLanguage,
    data,
    isLoading,
    /** A failed load is an error, not "no sponsors" (p.37). */
    loadError: isError ? error : null,
    retry: () => void refetch(),
    sponsorTypeLoading,
    itemsPerBreakpoint,
    getColorForSponsorType,
    sponsorCategories,
    filteredSponsorCategories,
  };
}
