"use client"; import { useState, useEffect, useMemo } from "react"; import { Product, IngredientInfo } from "../lib/data/products"; import { motion } from "motion/react"; import { FlaskConical, CheckCircle2, ChevronLeft, ChevronDown, Beaker, Search } from "lucide-react"; import { productService } from "../lib/services/productService"; import Link from "next/link"; import Image from "next/image"; import { useRouter, useSearchParams } from 'next/navigation'; import api from "../lib/services/api"; import { Ingredient } from "../lib/types"; // Keywords map for connecting ingredients to products const INGREDIENT_MATCH_KEYWORDS: Record = { "green-mussel": ["صدف", "mussel", "gag", "perna", "canhydrox", "velox", "flexan", "gelenkenergie"], "hydroxyapatite": ["هیدروکسی", "آپاتیت", "hydroxyapatite", "canhydrox"], "collagen": ["کلاژن", "collagen", "flexan"], "colostrum": ["آغوز", "colostrum", "immun-booster", "ایمون بوستر"], "silver": ["نقره", "میکروسیلور", "silver", "zahngel", "ژل دندان", "دندان"], "peat-extract": ["پیت", "moor", "moortranke", "هومیک", "عصاره پیت", "گوارش"], "salmon-oil": ["سالمون", "ماهی", "salmon", "lachs", "امگا", "marine", "welpenmilch", "katzenmilch"], "black-cumin": ["سیاه دانه", "سیاهدانه", "زیره", "cumin", "schwarz", "kummel"], "eggshell": ["پوسته", "تخم مرغ", "تخم‌مرغ", "eggshell", "eierschalen"], "biotin": ["بیوتین", "biotin", "vitamin h", "ویتامین h"], "taurin": ["تورین", "taurin", "taurine", "katzenmilch"], "seaweed": ["جلبک", "seaweed", "seealgen", "seelgen", "ascophyllum", "canhydrox"], "l-carnitine": ["کارنیتین", "carnitine", "herz-vital", "هرز ویتال", "قلب"], "hawthorn": ["زالزالک", "hawthorn", "crataegus", "herz-vital", "هرز ویتال", "قلب"], "brewer-yeast": ["مخمر", "yeast", "hefe", "b-complex", "canhydrox", "mineral-tabs", "vitamin-tabs", "taurin", "hefe-tabletten"], "bovine-blood": ["خون", "rinderblut", "blood", "آهن", "هموگلوبین", "سرم"], "bovine-fat": ["چربی", "rinderfett", "fat", "کالری", "گوشت گاو", "energy-gel", "immun-booster", "katzenmilch", "welpenmilch"], "willow-bark": ["بید", "willow", "salix", "arthro", "آرترو"], "ginger": ["زنجبیل", "ginger", "zingiber", "arthro", "آرترو"], "hyaluronic": ["هیالورونات", "hyaluron", "augenpflege", "چشم"], "calendula-sea-buckthorn": ["کالاندولا", "سنجد", "خولان", "pfotenpflege", "پنجه", "همیشه‌بهار", "پوست"], "dodecanoic": ["دودکانوئیک", "مارگوسا", "insect", "کک", "کنه", "حشرات", "ضد انگل", "پپت-پروتکت", "pet-protect", "اسپری"], "calcium-carbonate": ["کربنات کلسیم", "کلسیم", "calcium-carbonat", "mineral-tabs", "welpenkalk", "gag", "vitamin-tabs", "ballaststoff"], "vitamin-c": ["ویتامین c", "ویتامین سی", "ascorbic", "vitamin-c", "zahngel", "canhydrox"], "vitamin-e": ["ویتامین e", "ویتامین ای", "tocopherol", "vitamin-e", "canhydrox", "immun-booster", "energy-gel", "gag", "arthro"], "vitamin-d3": ["ویتامین d3", "ویتامین دی", "cholecalciferol", "d3", "immun-booster", "mineral-tabs", "vitamin-tabs", "welpenmilch"], "dextrose": ["دکستروز", "dextrose", "گلوکز", "biotin-tabs", "herz-vital", "energy-gel"], "marine-oils": ["گردو", "آرگان", "گل رز", "marine-ol", "olmischung", "روغن دریایی", "روغن"], "apple-fiber": ["سیب", "پکتین", "فیبر", "ballaststoff", "fiber", "یونجه", "هویج", "نخود"], "zinc": ["روی", "zinc", "کلات", "arthro", "seealgen", "biotin", "mineral-tabs"] }; // Formatter to prevent duplicate English names like "آغوز (Colostrum) (Colostrum)" function formatIngredientDisplayName(item: { nameFa?: string; scientificName?: string; nameEn?: string; name?: string; slug?: string }): string { const rawName = item.nameFa || item.name || ''; const cleanFa = rawName.replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim(); const sub = (item.scientificName || item.nameEn || '').replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim(); if (!cleanFa) return sub || rawName || item.slug || ''; if (!sub || cleanFa.toLowerCase() === sub.toLowerCase() || /[\u0600-\u06FF]/.test(sub)) { return cleanFa; } return `${cleanFa} (${sub})`; } export default function IngredientWiki() { const router = useRouter(); const searchParams = useSearchParams(); const termParam = searchParams.get('term'); const [ingredientsWiki, setIngredientsWiki] = useState([]); const [products, setProducts] = useState([]); const [searchQuery, setSearchQuery] = useState(""); const [visibleCount, setVisibleCount] = useState(8); const [expandedIngredients, setExpandedIngredients] = useState>(new Set()); useEffect(() => { productService.getProducts({ limit: 999 }) .then(res => { if (res?.data && res.data.length > 0) { setProducts(res.data); } }) .catch(err => { console.warn('[IngredientWiki] Products fetch failed:', err); setProducts([]); }); }, []); useEffect(() => { api.get('/ingredients') .then(res => { const rawList = Array.isArray(res.data) ? res.data : (res.data?.data || []); if (rawList.length > 0) { const apiList: IngredientInfo[] = rawList.map((item: Ingredient) => ({ id: item.slug || item.id, name: formatIngredientDisplayName(item), description: item.description || '', benefits: Array.isArray(item.benefits) ? item.benefits : [] })); setIngredientsWiki(apiList); } }) .catch((err) => { console.warn('[IngredientWiki] Ingredients fetch failed:', err); setIngredientsWiki([]); }); }, []); useEffect(() => { if (termParam && ingredientsWiki.length > 0) { const el = document.getElementById(`wiki-${termParam}`); if (el) { setTimeout(() => { const yOffset = -120; const y = el.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({ top: y, behavior: 'smooth' }); }, 200); } } }, [termParam, ingredientsWiki, visibleCount]); useEffect(() => { if (!termParam || ingredientsWiki.length === 0) return; setExpandedIngredients(current => { if (current.has(termParam)) return current; const next = new Set(current); next.add(termParam); return next; }); const targetIndex = ingredientsWiki.findIndex(ing => ing.id === termParam); if (targetIndex >= visibleCount) { setVisibleCount(Math.ceil((targetIndex + 1) / 8) * 8); } }, [termParam, ingredientsWiki, visibleCount]); // Product matcher for each ingredient const getProductsForIngredient = useMemo(() => { return (ingId: string, ingName: string) => { const cleanSlug = (ingId || '').replace(/-/g, ' ').toLowerCase(); const cleanFa = (ingName || '').replace(/\s*\([^)]*\)\s*/g, ' ').trim().toLowerCase(); const keywords = INGREDIENT_MATCH_KEYWORDS[ingId] || []; return products.filter(p => { const pText = [ p.name || '', p.nameFa || '', p.nameEn || '', p.scientificTagline || '', p.slug || '', p.id || '', p.description || '', p.shortDescription || '', p.category || '', p.categorySlug || '', ...(p.main_ingredients || []), ...(p.benefitsList || []), ...(p.keyBenefits?.map(k => `${k.title} ${k.description}`) || []), (p as any).ingredients || '' ].join(' ').toLowerCase(); if (cleanFa && pText.includes(cleanFa)) return true; if (cleanSlug && pText.includes(cleanSlug)) return true; return keywords.some(kw => pText.includes(kw.toLowerCase())); }); }; }, [products]); return (
{/* Standard Breadcrumb Navigation & Integrated Back Button */}
router.push('/')}>خانه دانشنامه مواد نایاب و ارگانیک
علم در خدمت کیفیت

دانشنامه مواد نایاب و ارگانیک کنینا

تمامی ترکیبات فعال و مکمل‌های به کار رفته در محصولات دارویی و مراقبتی Canina Pharma آلمان، دارای بالاترین گرید بیولوژیک و فارماکوپه اروپا می‌باشند.

{ setSearchQuery(e.target.value); setVisibleCount(8); }} className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 sm:py-3 pr-10 pl-4 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-xs" />
{/* Sugar-Free & Gluten-Free Medical Standards Banner */}
۱۰۰٪ فاقد قند افزوده (Sugar-Free)
مطابق استانداردهای دارویی و بالینی آلمان
{(() => { const filtered = ingredientsWiki.filter(ing => { if (!searchQuery.trim()) return true; const q = searchQuery.trim().toLowerCase(); return ing.name.toLowerCase().includes(q) || ing.description.toLowerCase().includes(q); }); if (filtered.length === 0) { return (

ماده‌ای یافت نشد

با عبارت جستجو شده ماده مؤثره‌ای مطابقت ندارد.

); } const visibleIngredients = filtered.slice(0, visibleCount); const remainingCount = Math.max(filtered.length - visibleCount, 0); const nextCount = Math.min(8, remainingCount); return ( <>
{visibleIngredients.map((ing, idx) => { const hasIngredient = getProductsForIngredient(ing.id, ing.name); const isTargeted = termParam === ing.id; const isExpanded = expandedIngredients.has(ing.id); const safeId = ing.id.replace(/[^a-zA-Z0-9_-]/g, '-'); const triggerId = `wiki-trigger-${safeId}`; const panelId = `wiki-panel-${safeId}`; return (

); })}
{remainingCount > 0 && (
نمایش {Math.min(visibleCount, filtered.length).toLocaleString('fa-IR')} از {filtered.length.toLocaleString('fa-IR')} ماده
)} ); })()}
); }