'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import ProductCard from '../products/ProductCard';
import { getListings, getListingId, type Listing } from '@/state/listing';
import { getProductDetailUrl } from '@/lib/productUrl';
import { mapListingToCard } from '../products/ProductGrid';

const MAX_ITEMS = 3;
// Fetch a little more than needed: the current product and duplicates are filtered out
const FETCH_LIMIT = MAX_ITEMS + 3;

interface RelatedHardwareProps {
  /**
   * The product's category followed by its ancestors, closest first
   * (e.g. [sub-sub, sub, main]). Each category query includes its descendants,
   * so every step up widens the search.
   */
  categoryIds: string[];
  currentProductId?: string;
}

/**
 * Collects up to MAX_ITEMS related listings (new and used), starting from the product's
 * own category and falling back to ancestor categories until the list is full.
 */
async function fetchRelatedListings(categoryIds: string[], currentProductId?: string): Promise<Listing[]> {
  const collected: Listing[] = [];
  const seen = new Set<string>(currentProductId ? [currentProductId] : []);

  for (const categoryId of categoryIds) {
    const res = await getListings({ categoryId, sortBy: 'newest', limit: FETCH_LIMIT });
    const results: Listing[] = res.data?.data?.results || res.data?.results || [];

    for (const listing of results) {
      const id = getListingId(listing);
      if (!id || seen.has(id)) continue;
      seen.add(id);
      collected.push(listing);
      if (collected.length === MAX_ITEMS) return collected;
    }
  }

  return collected;
}

export default function RelatedHardwareSection({ categoryIds, currentProductId }: RelatedHardwareProps) {
  const [items, setItems] = useState<Listing[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // Stable dependency for the effect (a new array is passed on every render)
  const categoryKey = categoryIds.join(',');

  useEffect(() => {
    let isMounted = true;

    const load = async () => {
      if (!categoryKey) {
        setIsLoading(false);
        return;
      }
      try {
        setIsLoading(true);
        const related = await fetchRelatedListings(categoryKey.split(','), currentProductId);
        if (isMounted) setItems(related);
      } catch (err) {
        // Section is optional: log and render nothing rather than dummy products
        console.error('Failed to load related hardware:', err);
        if (isMounted) setItems([]);
      } finally {
        if (isMounted) setIsLoading(false);
      }
    };

    load();

    return () => {
      isMounted = false;
    };
  }, [categoryKey, currentProductId]);

  if (isLoading || items.length === 0) return null;

  return (
    <section className="py-10 md:py-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-10">
        <span className="font-helvetica text-xs md:text-sm font-medium uppercase tracking-wider text-[#1657D9]">
          Marketplace Spotlight
        </span>
        <h2 className="font-helvetica mt-2 text-2xl md:text-[32px] md:leading-10 font-medium text-[#0E1420]">
          Related Professional Broadcast Hardware
        </h2>

        <div className="mt-6 md:mt-8 grid gap-4 md:gap-5 md:grid-cols-2 xl:grid-cols-3">
          {items.map((raw) => {
            const card = mapListingToCard(raw);
            return (
              <Link key={card.id} href={getProductDetailUrl(raw)} className="block h-full">
                <ProductCard {...card} />
              </Link>
            );
          })}
        </div>
      </div>
    </section>
  );
}
