"use client"; import React, { useState, useMemo, useEffect } 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 Link from "next/link"; import { motion, AnimatePresence } from "motion/react"; import { ProductCardSkeleton } from "./Skeleton"; import { toast } from "sonner"; import { Search, Filter, Dog, Cat, ShieldCheck, ChevronLeft, ChevronRight, Activity, Sparkles, Stethoscope, HeartPulse, Heart, AlertCircle, Plus, Loader2 } from "lucide-react"; import { useCartStore } from "../lib/store/cartStore"; import SafeImage from "./SafeImage"; 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 [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), 800); }; const compatibility = useMemo(() => { if (!activePet) return null; const sameSpecies = product.suitableFor === activePet.type || product.suitableFor === "هر دو"; const matchedSymptom = (activePet.medicalConditions || []).find(mc => (product.symptoms || []).some(s => mc.includes(s) || s.includes(mc)) ); 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' ? : compatibility.type === 'success' ? : } {compatibility.text}
)}
{(product.suitableFor === "سگ" || product.suitableFor === "هر دو") && (
)} {(product.suitableFor === "گربه" || product.suitableFor === "هر دو") && (
)}
{product.category}

{product.nameFa || product.name}

{product.nameEn && ( {product.nameEn} )}
{product.symptoms.slice(0, 2).map((s, i) => ( {s} ))}
{product.price} {(() => { const cartItem = useCartStore.getState().items.find(i => i.product.id === product.id); if (cartItem && cartItem.quantity > 0) { return (
{ 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)}
); } return ( ); })()}
); }; 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 [selectedCategory, setSelectedCategory] = useState(initialCategory); const [selectedPet, setSelectedPet] = useState(initialPetType as any); const [activeSymptoms, setActiveSymptoms] = useState(initialSymptoms ? initialSymptoms.split(',') : []); const [searchQuery, setSearchQuery] = useState(initialSearch); const [isUpdating, setIsUpdating] = useState(false); const [isMobileFilterOpen, setIsMobileFilterOpen] = useState(false); const [filteredProducts, setFilteredProducts] = useState([]); const [page, setPage] = useState(1); const [meta, setMeta] = useState({ total: 0, lastPage: 1 }); const [symptomSearch, setSymptomSearch] = useState(""); const [categories, setCategories] = useState<{ id: string; label: string; icon: React.ReactNode }[]>([]); const [symptoms, setSymptoms] = useState([]); useEffect(() => { const loadFilters = async () => { try { const filters = await productService.getActiveFilters(); 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); } catch (e) { console.error("Failed to load active filters:", e); } }; loadFilters(); }, []); const CATEGORY_LABELS = useMemo(() => { const labels: Record = { all: "همه محصولات" }; categories.forEach(c => { labels[c.id] = c.label; }); return labels; }, [categories]); // Sync state with prop change (e.g. from Header menu) useEffect(() => { // Normalize Input (Trim and lowercase) const normSearch = (initialSearch || "").trim().toLowerCase(); const normCat = initialCategory.trim().toLowerCase(); const mapKey = normSearch || normCat; const mapping = CATEGORY_MAP[mapKey]; if (selectedCategory === initialCategory && searchQuery === initialSearch) { return; } setIsUpdating(true); // Reset ALL other filters when a new category/solution is selected from menu setSelectedPet("all"); setActiveSymptoms([]); setSearchQuery(""); if (mapping) { if (mapping.category) setSelectedCategory(mapping.category); if (mapping.query) setSearchQuery(mapping.query); if (mapping.symptoms) { setActiveSymptoms(mapping.symptoms); } } else { setSelectedCategory(initialCategory); setSearchQuery(initialSearch); if (initialSearch && symptoms.includes(initialSearch)) { setActiveSymptoms([initialSearch]); } } const timer = setTimeout(() => { window.scrollTo({ top: 0, behavior: "smooth" }); }, 400); return () => clearTimeout(timer); }, [initialCategory, initialSearch, symptoms]); // 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}` : ''}`; router.push(newUrl, { scroll: false }); }, [selectedCategory, selectedPet, searchQuery, activeSymptoms]); const fetchProducts = async () => { setIsUpdating(true); try { const res = await productService.getProducts({ category: selectedCategory, petType: selectedPet, query: searchQuery, 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); setMeta(res.meta); } catch (error) { console.error("Failed to fetch products:", error); toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید."); } finally { setIsUpdating(false); } }; useEffect(() => { fetchProducts(); }, [selectedCategory, selectedPet, searchQuery, activeSymptoms]); const toggleSymptom = (s: string) => { setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]); }; return (
{/* Mobile Header & Filter Trigger */}
router.push('/')}>کانینا فروشگاه تخصصی ({meta.total || filteredProducts.length} محصول)
{/* Desktop Breadcrumbs */}
router.push('/')}>خانه { setSelectedCategory("all"); }}>کاتالوگ {selectedCategory !== "all" && ( <> {CATEGORY_LABELS[selectedCategory] || selectedCategory} )}
{/* Sidebar Filters - Collapsible on Mobile */} {/* Main Content */}

کاتولوگ دارویی Canina

setSearchQuery(e.target.value)} className="w-full bg-white border border-medical-gray-200 rounded-full py-3 pr-11 pl-4 text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20" />
{/* 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 ? (
{Array.from({ length: 8 }).map((_, i) => ( ))}
) : filteredProducts.length > 0 ? ( <>
{filteredProducts.map((p: Product) => ( ))}
) : (

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

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

)}
); }