"use client"; import React, { useMemo } from "react"; import ArticleProductCard from "./ArticleProductCard"; interface ArticleContentRendererProps { contentHtml: string; relatedProducts?: any[]; } export function parseContentWithProducts( html: string, relatedProducts: any[] = [] ): Array<{ type: "html" | "product"; content?: string; product?: any }> { if (!html) return []; // Match tags like [product slug_or_id], [محصول slug_or_id] // or HTML elements like
// or const markerRegex = /(?:]*>\s*)?(?:\[(?:product|محصول)\s+([a-zA-Z0-9_-]+)\]|<(?:div|span)[^>]*data-product=["']([a-zA-Z0-9_-]+)["'][^>]*>(?:<\/(?:div|span)>)?)(?:\s*<\/p>)?/gi; const parts: Array<{ type: "html" | "product"; content?: string; product?: any }> = []; let lastIndex = 0; let match: RegExpExecArray | null; // Build product lookup map (by slug, id) const productMap = new Map(); for (const prod of relatedProducts) { if (prod.slug) productMap.set(String(prod.slug).toLowerCase(), prod); if (prod.id) productMap.set(String(prod.id).toLowerCase(), prod); } while ((match = markerRegex.exec(html)) !== null) { const matchedText = match[0]; const identifier = (match[1] || match[2] || "").trim(); const startIndex = match.index; // Push preceding HTML if (startIndex > lastIndex) { const htmlSlice = html.slice(lastIndex, startIndex); if (htmlSlice.trim()) { parts.push({ type: "html", content: htmlSlice }); } } const matchedProduct = productMap.get(identifier.toLowerCase()); if (matchedProduct) { parts.push({ type: "product", product: matchedProduct }); } else { // If product not found in map, attempt fallback with slug info parts.push({ type: "product", product: { id: identifier, slug: identifier, nameFa: `محصول ${identifier}`, category: "مکمل دارویی کنینا", }, }); } lastIndex = startIndex + matchedText.length; } // Push remaining HTML if (lastIndex < html.length) { const trailingHtml = html.slice(lastIndex); if (trailingHtml.trim()) { parts.push({ type: "html", content: trailingHtml }); } } if (parts.length === 0 && html) { parts.push({ type: "html", content: html }); } return parts; } export default function ArticleContentRenderer({ contentHtml, relatedProducts = [], }: ArticleContentRendererProps) { const sections = useMemo( () => parseContentWithProducts(contentHtml, relatedProducts), [contentHtml, relatedProducts] ); // If there are no product cards inserted, preserve the exact original markup structure const hasProducts = sections.some((s) => s.type === "product"); if (!hasProducts) { return (
); } return (
{sections.map((section, idx) => { if (section.type === "product" && section.product) { return ( ); } return (
); })}
); }