'use client'; import { getAllProducts } from '@/lib/mdx'; import { mapFileSlugToTranslated } from '@/lib/slugs'; import { getTranslations } from 'next-intl/server'; import Image from 'next/image'; import Link from 'next/link'; import { useAnalytics } from './analytics/useAnalytics'; import { AnalyticsEvents } from './analytics/analytics-events'; import { useEffect, useState } from 'react'; interface RelatedProductsProps { currentSlug: string; categories: string[]; locale: string; } export default function RelatedProducts({ currentSlug, categories, locale }: RelatedProductsProps) { const { trackEvent } = useAnalytics(); const [allProducts, setAllProducts] = useState([]); const [t, setT] = useState(null); useEffect(() => { async function load() { const products = await getAllProducts(locale); const translations = await getTranslations('Products'); setAllProducts(products); setT(() => translations); } load(); }, [locale]); if (!t) return null; // Filter products: same category, not current product const related = allProducts .filter( (p) => p.slug !== currentSlug && p.frontmatter.categories.some((cat) => categories.includes(cat)), ) .slice(0, 3); // Limit to 3 for better spacing if (related.length === 0) return null; return (

{t('relatedProductsTitle') || 'Related Products'}

{related.map((product) => { // Find the category slug for the link const categorySlugs = [ 'low-voltage-cables', 'medium-voltage-cables', 'high-voltage-cables', 'solar-cables', ]; const catSlug = categorySlugs.find((slug) => { const key = slug .replace(/-cables$/, '') .replace(/-([a-z])/g, (g) => g[1].toUpperCase()); const title = t(`categories.${key}.title`); return product.frontmatter.categories.some( (cat) => cat.toLowerCase().replace(/\s+/g, '-') === slug || cat === title, ); }) || 'low-voltage-cables'; // Note: Since this is now client-side, we can't easily use mapFileSlugToTranslated // if it's a server-only lib. Let's assume for now the slugs are compatible or // we'll need to pass translated slugs from parent if needed. // For now, let's just use the product slug as is, or if we want to be safe, // we should have kept this a server component and used a client wrapper for the link. return ( trackEvent(AnalyticsEvents.PRODUCT_VIEW, { product_id: product.slug, product_name: product.frontmatter.title, location: 'related_products', }) } >
{product.frontmatter.images?.[0] ? ( <> {product.frontmatter.title}
) : (
No Image
)}
{product.frontmatter.categories.slice(0, 1).map((cat: any, idx: number) => ( {cat} ))}

{product.frontmatter.title}

{t('details')}
); })}
); }