"use client"; import React, { useState, useMemo, useEffect, useCallback } from "react"; import { toPersian } from "../lib/utils"; import { Product, PetType } from "../lib/data/products"; import { usePetStore } from "../lib/store/usePetStore"; import { productService } from "../lib/services/productService"; import { isSuitableForDog, isSuitableForCat, isSuitableForBoth, isSpeciesCompatible, matchesMedicalSymptom } from "../lib/petCompatibility"; import Link from "next/link"; import { motion, AnimatePresence } from "motion/react"; import { ProductCardSkeleton, ProductListSkeleton } from "./Skeleton"; import { toast } from "sonner"; import { Search, Filter, Dog, Cat, ShieldCheck, ChevronLeft, Activity, Sparkles, Stethoscope, HeartPulse, Heart, AlertCircle, Plus, Loader2, LayoutGrid, List, SlidersHorizontal, ChevronDown } from "lucide-react"; import { useCartStore } from "../lib/store/cartStore"; import { useSettingsStore } from "../lib/store/settingsStore"; import { useCatalogMode } from "../lib/useCatalogMode"; import SafeImage from "./SafeImage"; import BannerPlacement from "./BannerPlacement"; import { Banner } from "../lib/types"; const ICON_MAP: Record = { joints: , immune: , energy: , "special-care": , general: , nutrition: , }; const CATEGORY_MAP: Record = { // Main Categories "joints": { category: "joints" }, "immune": { category: "immune" }, "energy": { category: "energy" }, "special-care": { category: "special-care" }, // Persian Fallbacks (for robust matching) "مفاصل و استخوان": { category: "joints" }, "تقویت سیستم ایمنی و گوارش": { category: "immune" }, "ویتامین‌ها و انرژی‌بخش‌ها": { category: "energy" }, "مراقبت‌های ویژه (پوست، دندان و چشم)": { category: "special-care" }, // Solutions "آرتروز سگ‌های پیر": { category: "joints", symptoms: ["درد مفاصل", "سختی در بلند شدن", "لنگیدن"] }, "رشد استخوانی توله‌سگ": { category: "joints", symptoms: ["رشد سریع توله‌سگ"] }, "تقویت رباط و تاندون": { category: "joints", query: "تاندون" }, "پیشگیری از بیماری": { category: "immune", symptoms: ["ضعف بعد از بیماری"] }, "رفع اسهال و یبوست": { category: "immune", symptoms: ["اسهال", "یبوست", "اسهال مزمن"] }, "پروبیوتیک‌ها": { category: "immune", query: "فیبر" }, "مکمل‌های مولتی‌ویتامین": { category: "energy", query: "ویتامین" }, "افزایش اشتها": { category: "energy", symptoms: ["بی‌اشتهایی"] }, "رشد و بلوغ": { category: "energy", query: "انرژی" }, "سلامت پوست و مفاصل": { category: "special-care", symptoms: ["خشکی پوست", "ریزش مو", "خارش"] }, "رفع جرم دندان": { category: "special-care", symptoms: ["جرم دندان", "بوی بد دهان", "التهاب لثه"] }, "شستشوی چشم": { category: "special-care", query: "چشم" }, }; const ArchiveProductCard: React.FC<{ product: Product }> = ({ product }) => { const { addItem } = useCartStore(); const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id)); const [isAdding, setIsAdding] = useState(false); const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null); const { showPrices, allowCart, showPreorderBtn } = useCatalogMode(); const productUrl = `/shop/${product.slug || product.id}`; const handleAddToCart = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); setIsAdding(true); addItem(product, 1); toast.success(`${product.name} به سبد خرید اضافه شد`); setTimeout(() => setIsAdding(false), 400); }; const forDog = isSuitableForDog(product.suitableFor); const forCat = isSuitableForCat(product.suitableFor); const forBoth = isSuitableForBoth(product.suitableFor) || (forDog && forCat); const compatibility = useMemo(() => { if (!activePet) return null; const sameSpecies = isSpeciesCompatible(product.suitableFor, activePet.type); const matchedSymptom = matchesMedicalSymptom(activePet.medicalConditions, product.symptoms, product.benefits); if (!sameSpecies) return { type: 'alert', text: `مخصوص ${product.suitableFor}` }; if (matchedSymptom) return { type: 'success', text: `توصیه شده برای ${matchedSymptom} ${activePet.name}` }; if (sameSpecies) return { type: 'neutral', text: `مناسب برای ${activePet.name}` }; return null; }, [product, activePet]); return ( {product.specialBadge && (
{product.specialBadge}
)} {compatibility && (
{compatibility.type === 'alert' ? ( forBoth ? ( ) : forCat ? ( ) : forDog ? ( ) : ( ) ) : compatibility.type === 'success' ? ( ) : ( )} {compatibility.text}
)}
{forDog && (
)} {forCat && (
)}
{product.category}

{product.nameFa || product.name}

{product.nameEn && ( {product.nameEn} )}
{product.symptoms.slice(0, 2).map((s, i) => ( {s} ))}
{showPrices ? ( {product.price} ) : ( تماس جهت استعلام قیمت )} {(product.packageSize !== undefined && product.packageSize !== null ? Number(product.packageSize) : 100) <= 0 ? ( ناموجود ) : showPreorderBtn ? ( ثبت پیش‌خرید ) : allowCart && ( cartItem && cartItem.quantity > 0 ? (
{ e.preventDefault(); e.stopPropagation(); }} className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-xl p-1" > {toPersian(cartItem.quantity)}
) : ( ) )}
); }; const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) => { const { addItem } = useCartStore(); const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id)); const [isAdding, setIsAdding] = useState(false); const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null); const productUrl = `/shop/${product.slug || product.id}`; const handleAddToCart = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); setIsAdding(true); addItem(product, 1); toast.success(`${product.name} به سبد خرید اضافه شد`); setTimeout(() => setIsAdding(false), 400); }; const forDog = isSuitableForDog(product.suitableFor); const forCat = isSuitableForCat(product.suitableFor); const compatibility = useMemo(() => { if (!activePet) return null; const sameSpecies = isSpeciesCompatible(product.suitableFor, activePet.type); const matchedSymptom = matchesMedicalSymptom(activePet.medicalConditions, product.symptoms, product.benefits); if (!sameSpecies) return { type: 'alert', text: `مخصوص ${product.suitableFor}` }; if (matchedSymptom) return { type: 'success', text: `توصیه شده برای ${matchedSymptom} ${activePet.name}` }; if (sameSpecies) return { type: 'neutral', text: `مناسب برای ${activePet.name}` }; return null; }, [product, activePet]); const isOutOfStock = (product.packageSize !== undefined && product.packageSize !== null ? Number(product.packageSize) : 100) <= 0; const { showPrices, allowCart, showPreorderBtn } = useCatalogMode(); return ( {/* Product Thumbnail with species badge */}
{product.specialBadge && (
{product.specialBadge}
)}
{forDog && (
)} {forCat && (
)}
{/* Product Info */}
{product.category} {compatibility && ( {compatibility.text} )}

{product.nameFa || product.name}

{product.nameEn && ( {product.nameEn} )} {product.symptoms && product.symptoms.length > 0 && (
{product.symptoms.slice(0, 2).map((s, i) => ( {s} ))}
)}
{/* Price & Add to Cart */}
{showPrices ? ( {product.price} ) : ( استعلام قیمت )} {isOutOfStock ? ( ناموجود ) : showPreorderBtn ? ( ثبت پیش‌خرید ) : allowCart && ( cartItem && cartItem.quantity > 0 ? (
{ e.preventDefault(); e.stopPropagation(); }} className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-lg p-0.5" > {toPersian(cartItem.quantity)}
) : ( ) )}
); }; import { useRouter } from 'next/navigation'; export default function ArchivePage({ initialCategory = "all", initialSearch = "", initialPetType = "all", initialSymptoms = "" }: { initialCategory?: string, initialSearch?: string, initialPetType?: string, initialSymptoms?: string }) { const router = useRouter(); const getText = useSettingsStore(state => state.getText); const [selectedCategory, setSelectedCategory] = useState(initialCategory); const [selectedPet, setSelectedPet] = useState((initialPetType as PetType) || "all"); const [activeSymptoms, setActiveSymptoms] = useState(initialSymptoms ? initialSymptoms.split(',') : []); const [searchQuery, setSearchQuery] = useState(initialSearch); const [isUpdating, setIsUpdating] = useState(false); const [filteredProducts, setFilteredProducts] = useState([]); const [sortBy, setSortBy] = useState("createdAt"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [viewMode, setViewMode] = useState<"list" | "grid">("list"); const [isMobileSolutionsOpen, setIsMobileSolutionsOpen] = useState(false); const [isMobileSymptomsOpen, setIsMobileSymptomsOpen] = useState(false); const [symptomSearch, setSymptomSearch] = useState(""); const [categories, setCategories] = useState<{ id: string; label: string; icon: React.ReactNode }[]>([]); const [symptoms, setSymptoms] = useState([]); const [banners, setBanners] = useState([]); useEffect(() => { const loadFiltersAndBanners = async () => { try { const [filters, bannerData] = await Promise.all([ productService.getActiveFilters(), productService.getBanners() ]); const mapped = [ { id: "all", label: "همه محصولات", icon: }, ...filters.categories.map(c => ({ id: c.slug, label: c.name, icon: ICON_MAP[c.slug] || })) ]; setCategories(mapped); setSymptoms(filters.symptoms); if (Array.isArray(bannerData)) { setBanners(bannerData); } } catch (e) { console.error("Failed to load active filters or banners:", e); } }; loadFiltersAndBanners(); }, []); const CATEGORY_LABELS = useMemo(() => { const labels: Record = { all: "همه محصولات" }; categories.forEach(c => { labels[c.id] = c.label; }); return labels; }, [categories]); const lastInitialPropsRef = React.useRef({ initialCategory, initialSearch, initialPetType, initialSymptoms }); // Sync state when incoming initial props change from navigation useEffect(() => { const isNewCategory = lastInitialPropsRef.current.initialCategory !== initialCategory; const isNewSearch = lastInitialPropsRef.current.initialSearch !== initialSearch; const isNewPet = lastInitialPropsRef.current.initialPetType !== initialPetType; const isNewSymptoms = lastInitialPropsRef.current.initialSymptoms !== initialSymptoms; if (!isNewCategory && !isNewSearch && !isNewPet && !isNewSymptoms) { return; } lastInitialPropsRef.current = { initialCategory, initialSearch, initialPetType, initialSymptoms }; // Normalize Input const normSearch = (initialSearch || "").trim().toLowerCase(); const normCat = (initialCategory || "").trim().toLowerCase(); const mapKey = normSearch || normCat; const mapping = CATEGORY_MAP[mapKey]; setIsUpdating(true); if (mapping) { setSelectedCategory(mapping.category || "all"); setSearchQuery(mapping.query || ""); setSelectedPet("all"); setActiveSymptoms(mapping.symptoms || []); } else { setSelectedCategory(initialCategory || "all"); setSearchQuery(initialSearch || ""); setSelectedPet((initialPetType as PetType) || "all"); setActiveSymptoms(initialSymptoms ? initialSymptoms.split(',').filter(Boolean) : []); } }, [initialCategory, initialSearch, initialPetType, initialSymptoms]); // Update URL Query Parameters useEffect(() => { const params = new URLSearchParams(); if (selectedCategory && selectedCategory !== "all") params.set('category', selectedCategory); if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet); if (searchQuery) params.set('search', searchQuery); if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(',')); const queryString = params.toString(); const newUrl = `/shop${queryString ? `?${queryString}` : ''}`; if (typeof window !== 'undefined' && window.location.pathname + window.location.search !== newUrl) { router.replace(newUrl, { scroll: false }); } }, [selectedCategory, selectedPet, searchQuery, activeSymptoms, router]); const fetchProducts = useCallback(async () => { setIsUpdating(true); try { const res = await productService.getProducts({ category: selectedCategory, petType: selectedPet, query: searchQuery, sortBy, sortOrder, limit: 999, }); let result = res.data; // Filter with OR logic (union of symptoms) if symptoms are active if (activeSymptoms.length > 0) { result = result.filter(p => p.symptoms && p.symptoms.some(s => activeSymptoms.includes(s))); } setFilteredProducts(result); } catch (error) { console.error("Failed to fetch products:", error); toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید."); } finally { setIsUpdating(false); } }, [selectedCategory, selectedPet, searchQuery, sortBy, sortOrder, activeSymptoms]); useEffect(() => { Promise.resolve().then(() => fetchProducts()); }, [fetchProducts]); const toggleSymptom = (s: string) => { setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]); }; return (
{/* Standard Breadcrumb Navigation, Mobile Filter & Integrated Back Button */}
{/* Breadcrumb - right side in RTL */}
router.push('/')}>خانه { setSelectedCategory("all"); }}>فروشگاه محصولات {selectedCategory !== "all" && ( <> {CATEGORY_LABELS[selectedCategory] || selectedCategory} )}
{/* Back Button - leftmost in RTL */}
{/* Shop Top Banner Placement */}
{/* Sidebar Filters - Desktop only */} {/* Main Content */}
{/* Desktop Top Title & Search / Sort Row */}
{getText('shop_catalog_title', '').trim() ? (

Canina') }} /> ) : null}
{/* Sort Dropdown */}
مرتب‌سازی:
setSearchQuery(e.target.value)} className="w-full bg-white border border-medical-gray-200 rounded-full py-2.5 pr-11 pl-4 text-xs font-bold focus:outline-none focus:ring-2 focus:ring-canina-blue/20" />

{/* Mobile Title (Only if set in admin) */} {getText('shop_catalog_title', '').trim() ? (

Canina') }} />

) : null} {/* Mobile Controls: Horizontal Sliding Filters & View Toggle Row */}
{/* Search Bar on Mobile */}
setSearchQuery(e.target.value)} className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 pr-11 pl-4 text-xs font-bold focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-2xs" />
{/* Horizontal Scrollable Row for Sort, Pet Type, Solutions & Symptoms Filter */}
{/* 1. View Mode Switch: 2 Buttons (List / Card) */}
{/* 2. Compact Sort Button */}
{/* 3. Three Segmented Pet Type Buttons (Dog right, Both middle, Cat left) */}
{/* Right: Dog */} {/* Middle: Both */} {/* Left: Cat */}
{/* 4. Solutions Dropdown / Action Sheet Button */}
{isMobileSolutionsOpen && (
setIsMobileSolutionsOpen(false)}>
e.stopPropagation()} >

انتخاب راهکار درمانی

{categories.map(cat => ( ))}
)}
{/* 5. Symptoms Dropdown / Action Sheet Button with search inside */}
{isMobileSymptomsOpen && (
setIsMobileSymptomsOpen(false)}>
e.stopPropagation()} >

فیلتر بر اساس علائم پت

یک یا چند مورد از علائم را انتخاب کنید
{activeSymptoms.length > 0 && ( )}
setSymptomSearch(e.target.value)} className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2 pr-10 pl-3 text-xs outline-none focus:border-canina-blue font-vazir" />
{symptoms.length === 0 ? ( در حال بارگذاری علائم... ) : symptoms .filter(s => s.toLowerCase().includes(symptomSearch.toLowerCase())) .map(s => ( ))}
)}
{/* Active Filters Bar with X Dismiss Cross Buttons */} {(selectedCategory !== "all" || selectedPet !== "all" || activeSymptoms.length > 0 || searchQuery) && (
فیلترهای فعال: {selectedCategory !== "all" && ( {CATEGORY_LABELS[selectedCategory] || selectedCategory} )} {selectedPet !== "all" && ( پت: {selectedPet} )} {activeSymptoms.map(sym => ( علائم: {sym} ))} {searchQuery && ( جستجو: {searchQuery} )}
)} {isUpdating ? ( viewMode === "list" ? (
{Array.from({ length: 8 }).map((_, i) => ( ))}
) : (
{Array.from({ length: 8 }).map((_, i) => ( ))}
) ) : filteredProducts.length > 0 ? ( <> {/* Mobile List View vs Card View (Desktop is always responsive multi-column grid) */}
{filteredProducts.map((p: Product) => ( {/* In list mode on mobile, render ArchiveProductListItem; on desktop (lg+), render standard card */} {viewMode === "list" ? ( <>
) : ( )}
))}
{/* SEO Category Rich Description Section (Rendered below products to maintain primary UX while boosting category SEO) */} {selectedCategory !== "all" && (

راهنمای تخصصی و درمانی {CATEGORY_LABELS[selectedCategory] || selectedCategory}

{selectedCategory === 'joints' && 'مکمل‌های تخصصی مفاصل و استخوان کنینا آلمان (Canina Pharma) فرموله شده با عصاره خالص صدف سبز نیوزیلند (GAG)، گلوکوزامین، کندرویتین سولفات و مواد معدنی فعال جهت درمان و پیشگیری از آرتروز، دیسپلازی مفصل ران، ضعف لیگامنت‌ها و تسریع روند بهبود شکستگی‌های استخوانی در سگ‌ها و گربه‌ها.'} {selectedCategory === 'immune' && 'مکمل‌های تقویت سیستم ایمنی و سلامت دستگاه گوارش کنینا شامل پروبیوتیک‌های زیست‌سازگار، اینولین، ال‌گلوتامین و مخمر آبجو ارگانیک با هدف تنظیم فلور روده، جلوگیری از عفونت‌های مزمن، رفع اسهال و یبوست و افزایش مقاومت طبیعی بدن پت در برابر پاتوژن‌ها.'} {selectedCategory === 'energy' && 'مولتی‌ویتامین‌ها و انرژی‌بخش‌های بالینی کنینا با نسبت بالانس‌شده ویتامین‌های A، D3، E و گروه B، به همراه اسیدهای چرب امگا ۳ و ۶ برای ارتقای شادابی، بهبود اشتهای از دست رفته، پشتیبانی از توله‌های در حال رشد و حیوانات در دوران نقاهت و سالمندی.'} {selectedCategory === 'special-care' && 'محصولات درمانی و مراقبت ویژه پوست، مو، چشم و دهان و دندان کنینا بدون مواد شیمیایی آسیب‌رسان و با استاندارد دارویی اروپا برای پیشگیری از ایجاد پلاک دندان، درمان ریزش موی ناشی از کمبودهای تغذیه‌ای و التهابات آلرژیک.'} {!['joints', 'immune', 'energy', 'special-care'].includes(selectedCategory) && 'تمامی مکمل‌های درمانی و تقویتی کنینا آلمان با ۱۰۰٪ ترکیبات ارگانیک و مطابق با بالاترین استانداردهای داروسازی اروپا (IFS & HACCP) تولید و به صورت رسمی در ایران توزیع می‌گردند.'}

فرمولاسیون اختصاصی Canina Pharma آلمان مورد تایید کلینیک‌های تخصصی دامپزشکی پروانه بهداشتی واردات رسمی
)} ) : (

محصولی یافت نشد!

با فیلترهای فعلی محصولی مطابق با نیاز شما پیدا نکردیم. لطفاً فیلترها را گسترده‌تر کنید یا دکمه ریست را بزنید.

)}
); }