"use client";

import { useMemo } from "react";
import type { Partner } from "@/types/data";
import type { Translations } from "@/lib/translations";
import type { LanguageCode } from "@/types/language";
import type { ThemeId } from "@/types/theme";
import { PartnerCard } from "./PartnerCard";

interface PartnerShowcaseProps {
  readonly partners: readonly Partner[];
  readonly licensedPartners: readonly Partner[];
  readonly initialShowAll: boolean;
  readonly gclid: string | null;
  readonly accountCode: string;
  readonly partnersToShow?: readonly Partner[];
  readonly translations: Translations;
  readonly language: LanguageCode;
  readonly theme: ThemeId;
}

export function PartnerShowcase({
  partners,
  licensedPartners,
  initialShowAll,
  gclid,
  accountCode,
  partnersToShow,
  translations,
  language,
  theme,
}: PartnerShowcaseProps) {
  // Memoize client-side check to avoid re-evaluation
  const hasNavigatorUserAgent = useMemo(
    () => typeof navigator === "undefined" ? true : Boolean(navigator.userAgent),
    []
  );
  const showAll = initialShowAll && hasNavigatorUserAgent;

  // Memoize partner cards with affiliate links
  // gclid is used ONLY for affiliate tracking, never exposed in HTML attributes or metadata
  const partnerCards = useMemo(() => {
    const gclidValue = gclid ?? "organic";
    // If partnersToShow is provided, use it (server-side filtered)
    // Otherwise, use the existing logic (showAll ? partners : licensedPartners)
    const list = partnersToShow ?? (showAll ? partners : licensedPartners);
    return list.map((partner) => {
      const linkWithAccount = partner.affiliateLink.replace(
        "{AccountCode}",
        accountCode,
      );
      // gclid is only appended to affiliate links (external), never to internal URLs
      const affiliateHref = `${linkWithAccount}${encodeURIComponent(gclidValue)}`;
      return { partner, affiliateHref };
    });
  }, [accountCode, gclid, licensedPartners, partners, partnersToShow, showAll]);

  return (
    <section aria-labelledby="partners-heading" className="space-y-2 sm:space-y-6">
      <div className="grid gap-2.5 sm:gap-6 md:grid-cols-2 lg:gap-8">
        {partnerCards.map(({ partner, affiliateHref }, index) => (
          <PartnerCard
            key={partner.name}
            partner={partner}
            affiliateHref={affiliateHref}
            index={index}
            translations={translations}
            language={language}
            theme={theme}
          />
        ))}
      </div>
    </section>
  );
}
