Files
canina/frontend/application/components/ArchivePage.tsx
T
2026-10-18 13:54:31 +00:00

1315 lines
71 KiB
TypeScript

"use client";
import { useUserStore } from "../lib/store/userStore";
import React, { useState, useMemo, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { toPersian, isProductOutOfStock } 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<string, React.ReactNode> = {
joints: <HeartPulse className="w-4 h-4" />,
immune: <ShieldCheck className="w-4 h-4" />,
energy: <Activity className="w-4 h-4" />,
"special-care": <Stethoscope className="w-4 h-4" />,
general: <Heart className="w-4 h-4" />,
nutrition: <Sparkles className="w-4 h-4" />,
};
const CATEGORY_MAP: Record<string, { category?: string; query?: string; symptoms?: string[] }> = {
// 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: "چشم" },
};
export const orderProductsByAvailability = (products: Product[]): Product[] => {
const available = products.filter(product => !isProductOutOfStock(product));
const unavailable = products.filter(product => isProductOutOfStock(product));
return [...available, ...unavailable];
};
export 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 isLoggedIn = useUserStore(s => s.isLoggedIn);
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : 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 (
<motion.div
layout
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="h-full"
>
<Link
data-testid="archive-product-card"
href={productUrl}
className="group bg-white rounded-[2.5rem] border border-medical-gray-200 overflow-hidden hover:shadow-2xl transition-all flex flex-col h-full relative"
>
{/* SpecialBadge moved below image to avoid covering product photo */}
{compatibility && (
<div className={`absolute top-4 right-4 z-10 text-3xs font-black uppercase tracking-widest px-2.5 py-1 rounded-full shadow-md flex items-center gap-1 backdrop-blur-xs ${compatibility.type === 'alert' ? 'bg-amber-500/90 text-white' :
compatibility.type === 'success' ? 'bg-emerald-600/90 text-white' : 'bg-canina-blue/90 text-white'
}`}>
{compatibility.type === 'alert' ? (
forBoth ? (
<span className="flex items-center gap-0.5">
<Dog className="w-2.5 h-2.5" />
<Cat className="w-2.5 h-2.5" />
</span>
) : forCat ? (
<Cat className="w-2.5 h-2.5" />
) : forDog ? (
<Dog className="w-2.5 h-2.5" />
) : (
<AlertCircle className="w-2.5 h-2.5" />
)
) : compatibility.type === 'success' ? (
<Heart className="w-2.5 h-2.5" />
) : (
<Sparkles className="w-2.5 h-2.5" />
)}
{compatibility.text}
</div>
)}
<div className="aspect-square bg-medical-gray-50 flex items-center justify-center p-2 overflow-hidden relative">
<SafeImage
src={product.image}
alt={product.name}
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw)"
className="w-full h-full group-hover:scale-105 transition-transform duration-700"
imgClassName="w-full h-full object-contain"
/>
<div className="absolute bottom-4 left-4 flex gap-2">
{forDog && (
<div className="w-7 h-7 bg-white rounded-lg flex items-center justify-center text-medical-gray-400 border border-medical-gray-100 shadow-sm" title="مناسب برای سگ">
<Dog className="w-4 h-4" />
</div>
)}
{forCat && (
<div className="w-7 h-7 bg-white rounded-lg flex items-center justify-center text-medical-gray-400 border border-medical-gray-100 shadow-sm" title="مناسب برای گربه">
<Cat className="w-4 h-4" />
</div>
)}
</div>
</div>
<div className="p-6 flex flex-col flex-1">
{product.specialBadge && (
<div className="mb-2">
<span className="inline-block bg-canina-blue/10 text-canina-blue border border-canina-blue/20 text-[10px] font-black px-2.5 py-1 rounded-lg line-clamp-1 font-vazir" title={product.specialBadge}>
{product.specialBadge}
</span>
</div>
)}
<div className="text-2xs font-bold text-canina-blue uppercase tracking-widest mb-2">{product.category}</div>
<div className="flex flex-col gap-1 mb-3">
<h3 dir="rtl" className="text-base font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors leading-tight text-right font-vazir">
{product.nameFa || product.name}
</h3>
{product.nameEn && (
<span dir="ltr" className="text-xs-plus font-bold text-slate-400 font-sans text-left block">
{product.nameEn}
</span>
)}
</div>
<div className="flex flex-wrap gap-1">
{product.symptoms.slice(0, 2).map((s, i) => (
<span key={i} className="text-2xs font-bold bg-medical-gray-100 text-medical-gray-500 px-2 py-0.5 rounded-md">
{s}
</span>
))}
</div>
<div className="mt-auto flex items-center justify-between pt-4 border-t border-medical-gray-50 gap-2 flex-wrap sm:flex-nowrap">
<div className="shrink-0">
{showPrices && (
<span className="font-black text-medical-gray-900 font-vazir text-sm sm:text-base whitespace-nowrap">{product.price}</span>
)}
</div>
<div className="shrink-0 mr-auto">
{isProductOutOfStock(product) ? (
<span className="px-2.5 py-1.5 rounded-xl bg-rose-50 text-rose-600 border border-rose-100 text-xs font-bold font-vazir whitespace-nowrap inline-block">
ناموجود
</span>
) : allowCart ? (
cartItem && cartItem.quantity > 0 ? (
<div
onClick={(e) => { e.preventDefault(); e.stopPropagation(); }}
className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-xl p-1 shrink-0"
>
<button
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
useCartStore.getState().updateQuantity(product.id, cartItem.quantity + 1);
}}
className="w-7 h-7 rounded-lg bg-canina-blue text-white flex items-center justify-center font-bold text-xs"
>
+
</button>
<span className="w-5 text-center font-black text-canina-blue text-xs font-vazir">
{toPersian(cartItem.quantity)}
</span>
<button
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
useCartStore.getState().updateQuantity(product.id, cartItem.quantity - 1);
}}
className="w-7 h-7 rounded-lg bg-white text-medical-gray-700 flex items-center justify-center font-bold text-xs shadow-sm"
>
-
</button>
</div>
) : (
<button
onClick={handleAddToCart}
disabled={isAdding}
className="px-3 py-2 rounded-xl bg-canina-blue text-white text-xs font-black flex items-center gap-1.5 hover:bg-canina-dark transition-all disabled:opacity-50 shadow-md shadow-canina-blue/20 whitespace-nowrap shrink-0"
>
{isAdding ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Plus className="w-3.5 h-3.5" />}
<span>خرید</span>
</button>
)
) : (showPreorderBtn || (product as unknown as { isPreorder?: boolean }).isPreorder) ? (
<span className="px-2.5 py-1.5 rounded-xl bg-purple-50 text-purple-700 border border-purple-200 text-xs font-black font-vazir whitespace-nowrap inline-block">
ثبت پیش‌خرید
</span>
) : null}
</div>
</div>
</div>
</Link>
</motion.div>
);
};
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 isLoggedIn = useUserStore(s => s.isLoggedIn);
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : 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 = isProductOutOfStock(product);
const { showPrices, allowCart, showPreorderBtn } = useCatalogMode();
return (
<motion.div
layout
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="w-full"
>
<Link
data-testid="archive-product-list-item"
href={productUrl}
className="group bg-white rounded-2xl border border-medical-gray-200 overflow-hidden hover:border-canina-blue/30 transition-all flex items-center p-2.5 gap-3 relative shadow-xs"
>
{/* Product Thumbnail with species badge */}
<div className="w-24 h-24 sm:w-28 sm:h-28 bg-medical-gray-50 rounded-xl flex-shrink-0 flex items-center justify-center p-1 relative overflow-hidden border border-medical-gray-100">
<SafeImage
src={product.image}
alt={product.name}
sizes="120px"
className="w-full h-full group-hover:scale-105 transition-transform duration-500"
imgClassName="w-full h-full object-contain"
/>
{/* List specialBadge moved below */}
<div className="absolute bottom-1 left-1 flex gap-1">
{forDog && (
<div className="w-5 h-5 bg-white/90 backdrop-blur-xs rounded-md flex items-center justify-center text-medical-gray-500 border border-medical-gray-100 shadow-2xs" title="مناسب برای سگ">
<Dog className="w-3 h-3" />
</div>
)}
{forCat && (
<div className="w-5 h-5 bg-white/90 backdrop-blur-xs rounded-md flex items-center justify-center text-medical-gray-500 border border-medical-gray-100 shadow-2xs" title="مناسب برای گربه">
<Cat className="w-3 h-3" />
</div>
)}
</div>
</div>
{/* Product Info */}
<div className="flex-1 flex flex-col justify-between self-stretch min-w-0 py-0.5">
<div>
<div className="flex items-center gap-1.5 mb-1">
<span className="text-[10px] font-bold text-canina-blue truncate">{product.category}</span>
{compatibility && (
<span className={`text-[9px] font-black px-1.5 py-0.2 rounded-md ${compatibility.type === 'alert' ? 'bg-amber-100 text-amber-700' :
compatibility.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-medical-gray-100 text-medical-gray-600'
}`}>
{compatibility.text}
</span>
)}
</div>
<h3 dir="rtl" className="text-xs sm:text-sm font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors leading-snug text-right font-vazir line-clamp-2">
{product.nameFa || product.name}
</h3>
{product.nameEn && (
<span dir="ltr" className="text-[10px] font-semibold text-slate-400 font-sans text-left block truncate mt-0.5">
{product.nameEn}
</span>
)}
{product.symptoms && product.symptoms.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1.5">
{product.symptoms.slice(0, 2).map((s, i) => (
<span key={i} className="text-[9px] font-bold bg-medical-gray-100 text-medical-gray-500 px-1.5 py-0.5 rounded">
{s}
</span>
))}
</div>
)}
</div>
{/* Price & Add to Cart */}
<div className="mt-2 flex items-center justify-between pt-2 border-t border-medical-gray-100/70 gap-2 flex-wrap sm:flex-nowrap">
<div className="shrink-0">
{showPrices && (
<span className="font-black text-medical-gray-900 font-vazir text-xs sm:text-sm whitespace-nowrap">{product.price}</span>
)}
</div>
<div className="shrink-0 mr-auto">
{isOutOfStock ? (
<span className="px-2 py-1 rounded-lg bg-rose-50 text-rose-600 border border-rose-100 text-[10px] font-bold font-vazir whitespace-nowrap inline-block">
ناموجود
</span>
) : allowCart ? (
cartItem && cartItem.quantity > 0 ? (
<div
onClick={(e) => { e.preventDefault(); e.stopPropagation(); }}
className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-lg p-0.5 shrink-0"
>
<button
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
useCartStore.getState().updateQuantity(product.id, cartItem.quantity + 1);
}}
className="w-6 h-6 rounded-md bg-canina-blue text-white flex items-center justify-center font-bold text-xs"
>
+
</button>
<span className="w-4 text-center font-black text-canina-blue text-xs font-vazir">
{toPersian(cartItem.quantity)}
</span>
<button
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
useCartStore.getState().updateQuantity(product.id, cartItem.quantity - 1);
}}
className="w-6 h-6 rounded-md bg-white text-medical-gray-700 flex items-center justify-center font-bold text-xs shadow-sm"
>
-
</button>
</div>
) : (
<button
onClick={handleAddToCart}
disabled={isAdding}
className="px-2.5 py-1.5 rounded-lg bg-canina-blue text-white text-[10px] font-black flex items-center gap-1 hover:bg-canina-dark transition-all disabled:opacity-50 shadow-sm whitespace-nowrap shrink-0"
>
{isAdding ? <Loader2 className="w-3 h-3 animate-spin" /> : <Plus className="w-3 h-3" />}
<span>خرید</span>
</button>
)
) : (showPreorderBtn || (product as unknown as { isPreorder?: boolean }).isPreorder) ? (
<span className="px-2 py-1 rounded-lg bg-purple-50 text-purple-700 border border-purple-200 text-[10px] font-black font-vazir whitespace-nowrap inline-block">
ثبت پیش‌خرید
</span>
) : null}
</div>
</div>
</div>
</Link>
</motion.div>
);
};
import { useRouter } from 'next/navigation';
export default function ArchivePage({
initialCategory = "all",
initialSearch = "",
initialPetType = "all",
initialSymptoms = "",
initialProducts = [],
initialPage = 1,
initialLimit = 12
}: {
initialCategory?: string,
initialSearch?: string,
initialPetType?: string,
initialSymptoms?: string,
initialProducts?: Product[],
initialPage?: number,
initialLimit?: number
}) {
const router = useRouter();
const getText = useSettingsStore(state => state.getText);
const [selectedCategory, setSelectedCategory] = useState(initialCategory);
const [selectedPet, setSelectedPet] = useState<PetType | "all">((initialPetType as PetType) || "all");
const [activeSymptoms, setActiveSymptoms] = useState<string[]>(initialSymptoms ? initialSymptoms.split(',') : []);
const [searchQuery, setSearchQuery] = useState(initialSearch);
const [isUpdating, setIsUpdating] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [filteredProducts, setFilteredProducts] = useState<Product[]>(() => orderProductsByAvailability(initialProducts));
const [sortBy, setSortBy] = useState<string>("createdAt");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [viewMode, setViewMode] = useState<"list" | "grid">("list");
const [currentPage, setCurrentPage] = useState<number>(() => Math.max(1, initialPage));
const pageSize = Math.max(1, initialLimit);
const [isMounted, setIsMounted] = useState<boolean>(false);
useEffect(() => {
setIsMounted(true);
}, []);
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<string[]>([]);
const [banners, setBanners] = useState<Banner[]>([]);
useEffect(() => {
const loadFiltersAndBanners = async () => {
try {
const [filters, bannerData] = await Promise.all([
productService.getActiveFilters(),
productService.getBanners()
]);
const mapped = [
{ id: "all", label: "همه محصولات", icon: <Activity className="w-4 h-4" /> },
...filters.categories.map(c => ({
id: c.slug,
label: c.name,
icon: ICON_MAP[c.slug] || <Activity className="w-4 h-4" />
}))
];
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<string, string> = { 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 };
setCurrentPage(initialPage || 1);
// 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) : []);
}
setCurrentPage(1);
}, [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(','));
if (currentPage > 1) params.set('page', String(currentPage));
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, currentPage, router]);
const hasInitialProducts = Boolean(initialProducts && initialProducts.length > 0);
const didSkipInitialFetch = React.useRef(false);
const fetchProducts = useCallback(async () => {
setFetchError(null);
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(orderProductsByAvailability(result));
setCurrentPage(1);
} catch (error) {
console.error("Failed to fetch products:", error);
toast.error("خطا در دریافت لیست محصولات از سرور.");
setFetchError("خطا در برقراری ارتباط با سرور یا دریافت اطلاعات محصولات.");
} finally {
setIsUpdating(false);
}
}, [selectedCategory, selectedPet, searchQuery, sortBy, sortOrder, activeSymptoms]);
useEffect(() => {
if (hasInitialProducts && !didSkipInitialFetch.current) {
didSkipInitialFetch.current = true;
return;
}
Promise.resolve().then(() => fetchProducts());
}, [fetchProducts, hasInitialProducts]);
const toggleSymptom = (s: string) => {
setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]);
};
return (
<div className="min-h-screen bg-medical-gray-50 pb-20 px-4 pt-4 md:pt-10 font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto">
{/* Standard Breadcrumb Navigation, Mobile Filter & Integrated Back Button */}
<div className="flex items-center justify-between mb-4 md:mb-8 pb-4 border-b border-medical-gray-200/60 font-vazir gap-2" dir="rtl">
{/* Breadcrumb - right side in RTL */}
<div className="flex items-center gap-1.5 text-xs font-bold text-medical-gray-400 overflow-hidden min-w-0">
<span className="cursor-pointer hover:text-canina-blue transition-colors shrink-0" onClick={() => router.push('/')}>خانه</span>
<ChevronLeft className="w-3 h-3 text-medical-gray-300 shrink-0" />
<span className="cursor-pointer hover:text-canina-blue transition-colors shrink-0" onClick={() => { setSelectedCategory("all"); }}>فروشگاه محصولات</span>
{selectedCategory !== "all" && (
<>
<ChevronLeft className="w-3 h-3 text-medical-gray-300 shrink-0" />
<span className="text-canina-blue font-black truncate">{CATEGORY_LABELS[selectedCategory] || selectedCategory}</span>
</>
)}
</div>
<div className="flex items-center gap-2 shrink-0">
{/* Back Button - leftmost in RTL */}
<button
onClick={() => router.push('/')}
className="flex-shrink-0 px-3 py-1.5 bg-white border border-medical-gray-200 rounded-lg text-medical-gray-600 shadow-xs flex items-center gap-1.5 font-bold text-xs hover:border-canina-blue hover:text-canina-blue transition-all cursor-pointer"
>
<span>بازگشت</span>
<ChevronLeft className="w-3.5 h-3.5" />
</button>
</div>
</div>
{/* Shop Top Banner Placement */}
<BannerPlacement banners={banners} position="shop_top" className="!px-0 !py-2 mb-6" />
<div className="flex flex-col lg:flex-row gap-8">
{/* Sidebar Filters - Desktop only */}
<aside className="lg:w-72 flex-shrink-0 space-y-6 hidden lg:block">
<div className="bg-white rounded-[2rem] lg:p-6 border-0 lg:border lg:border-medical-gray-200 shadow-none lg:shadow-sm">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-2">
<Filter className="w-5 h-5 text-canina-blue" />
<h3 className="font-black text-medical-gray-900">{getText('shop_filter_title', 'فیلترهای تخصصی')}</h3>
</div>
</div>
<div className="space-y-6">
{/* Pet Type */}
<div>
<span className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block mb-3">{getText('shop_filter_pet_type', 'نوع پت')}</span>
<div className="grid grid-cols-3 gap-2">
{[
{ id: "all", label: "هر دو", icon: <Activity className="w-3 h-3" /> },
{ id: "سگ", label: "سگ", icon: <Dog className="w-3 h-3" /> },
{ id: "گربه", label: "گربه", icon: <Cat className="w-3 h-3" /> },
].map(pet => (
<button
key={pet.id}
onClick={() => setSelectedPet(pet.id as PetType | "all")}
className={`py-2 rounded-xl text-[10px] font-black border transition-all flex flex-col items-center gap-1 ${selectedPet === pet.id ? 'bg-canina-blue border-canina-blue text-white shadow-lg shadow-canina-blue/20' : 'bg-white border-medical-gray-200 text-medical-gray-400'}`}
>
{pet.icon}
{pet.label}
</button>
))}
</div>
</div>
{/* Solutions */}
<div>
<span className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest block mb-3">{getText('shop_filter_solutions', 'راهکار درمانی')}</span>
<div className="flex flex-col gap-2">
{categories.map(cat => (
<button
key={cat.id}
onClick={() => setSelectedCategory(cat.id)}
className={`flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold transition-all border ${selectedCategory === cat.id ? 'bg-canina-blue border-canina-blue text-white' : 'bg-white border-medical-gray-100 text-medical-gray-600 hover:border-canina-blue/30'}`}
>
{cat.icon}
{cat.label}
</button>
))}
</div>
</div>
{/* Symptoms Pill Tags with Search Field */}
<div>
<div className="flex items-center justify-between mb-3">
<span className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest">جستجو بر اساس علائم</span>
{activeSymptoms.length > 0 && (
<button
onClick={() => setActiveSymptoms([])}
className="text-[10px] font-bold text-canina-blue hover:underline"
>
پاک کردن
</button>
)}
</div>
<div className="relative mb-3">
<input
type="text"
aria-label="جستجوی علائم"
placeholder="جستجوی علائم..."
value={symptomSearch}
onChange={(e) => setSymptomSearch(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2 px-3 text-xs outline-none focus:border-canina-blue font-vazir"
/>
</div>
<div className="flex flex-wrap gap-1.5 max-h-48 overflow-y-auto scrollbar-thin scrollbar-thumb-medical-gray-200 scrollbar-track-transparent pr-0.5">
{symptoms.length === 0 ? (
<span className="text-[10px] text-medical-gray-400">در حال بارگذاری...</span>
) : symptoms
.filter(s => s.toLowerCase().includes(symptomSearch.toLowerCase()))
.map(s => (
<button
key={s}
onClick={() => toggleSymptom(s)}
className={`px-2.5 py-1 rounded-full text-[10px] font-bold transition-all border whitespace-nowrap ${activeSymptoms.includes(s)
? 'bg-canina-blue border-canina-blue text-white shadow-sm shadow-canina-blue/30'
: 'bg-medical-gray-50 border-medical-gray-200 text-medical-gray-500 hover:border-canina-blue/40 hover:text-canina-blue'
}`}
>
{s}
</button>
))}
</div>
</div>
</div>
</div>
{/* Promo Card */}
<div className="bg-medical-gray-900 rounded-[2rem] p-6 text-white relative overflow-hidden group">
<div className="absolute -top-10 -left-10 w-32 h-32 bg-canina-blue rounded-full blur-3xl opacity-20 group-hover:opacity-40 transition-opacity" />
<h4 className="text-lg font-black italic mb-4 relative z-10 underline decoration-canina-blue underline-offset-8">{getText('shop_promo_card_title', 'مشاوره رایگان')}</h4>
<p className="text-xs text-white/60 leading-relaxed mb-6 relative z-10">{getText('shop_promo_card_desc', 'اگر نمی‌دانید کدام ترکیب برای پت شما مناسب است، همین حالا با دامپزشکان ما تماس بگیرید.')}</p>
<a
href={getText('contact_phone_link', `tel:${getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)}
className="w-full bg-white text-medical-gray-900 py-3 rounded-xl text-xs font-black hover:scale-105 transition-transform relative z-10 flex items-center justify-center font-vazir"
>
شماره تماس: {getText('contact_phone', '')}
</a>
</div>
</aside>
{/* Main Content */}
<main className="flex-1 relative">
{/* Semantic Single H1 across breakpoints */}
<div className="flex flex-col lg:flex-row items-start lg:items-center justify-between mb-2 lg:mb-6 gap-2 lg:gap-4">
<h1
className="text-2xl lg:text-3xl font-black text-medical-gray-900"
dangerouslySetInnerHTML={{
__html: getText('shop_catalog_title', 'کاتالوگ و فروشگاه مکمل‌های دارویی <span class="text-canina-blue">کنینا</span>')
.replace(/^\s*<h1[^>]*>/i, '')
.replace(/<\/h1>\s*$/i, '')
}}
/>
<div className="hidden lg:flex items-center gap-3 w-auto">
{/* Sort Dropdown */}
<div className="flex items-center gap-2 bg-white border border-medical-gray-200 rounded-2xl px-3 py-2 text-xs font-bold shadow-xs">
<span className="text-medical-gray-400 whitespace-nowrap">مرتب‌سازی:</span>
<select
aria-label="مرتب‌سازی محصولات"
value={`${sortBy}:${sortOrder}`}
onChange={(e) => {
const [b, o] = e.target.value.split(':');
setSortBy(b);
setSortOrder(o as 'asc' | 'desc');
}}
className="bg-transparent font-black text-medical-gray-800 outline-none cursor-pointer"
>
<option value="createdAt:desc">جدیدترین</option>
<option value="createdAt:asc">قدیمی‌ترین</option>
<option value="priceValue:asc">ارزان‌ترین</option>
<option value="priceValue:desc">گران‌ترین</option>
<option value="nameFa:asc">نام (الف - ی)</option>
</select>
</div>
<div className="relative w-64">
<Search className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<input
data-testid="shop-search-input"
type="text"
aria-label="جستجوی محصول"
placeholder="جستجوی محصول..."
value={searchQuery}
onChange={(e) => 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"
/>
</div>
</div>
</div>
{/* Mobile Controls: Horizontal Sliding Filters & View Toggle Row */}
<div className="lg:hidden flex flex-col gap-2 mb-2">
{/* Search Bar on Mobile */}
<div className="relative w-full">
<Search className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<input
data-testid="shop-search-input-mobile"
type="text"
aria-label="جستجوی محصول"
placeholder="جستجوی محصول..."
value={searchQuery}
onChange={(e) => 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"
/>
</div>
{/* Horizontal Scrollable Row for Sort, Pet Type, Solutions & Symptoms Filter */}
<div className="relative -mx-4 mt-2 mb-4" data-testid="mobile-catalog-filters-edge">
<div data-testid="mobile-catalog-filters" aria-label="فیلترهای محصولات" className="flex items-center gap-2 overflow-x-auto pb-2.5 pt-0.5 micro-hscroll px-4 select-none touch-pan-x mobile-filter-mask">
{/* 1. View Mode Switch: 2 Buttons (List / Card) */}
<div className="flex-shrink-0 inline-flex items-center bg-white border border-medical-gray-200 rounded-xl p-0.5 shadow-2xs mr-auto">
<button
type="button"
onClick={() => setViewMode("list")}
className={`p-1.5 rounded-lg transition-all ${viewMode === "list" ? "bg-canina-blue text-white shadow-xs" : "text-medical-gray-400 hover:text-medical-gray-700"}`}
title="نمایش لیستی"
>
<List className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => setViewMode("grid")}
className={`p-1.5 rounded-lg transition-all ${viewMode === "grid" ? "bg-canina-blue text-white shadow-xs" : "text-medical-gray-400 hover:text-medical-gray-700"}`}
title="نمایش کارتی"
>
<LayoutGrid className="w-3.5 h-3.5" />
</button>
</div>
{/* 2. Compact Sort Button */}
<div className="relative flex-shrink-0">
<div className="flex items-center bg-white border border-medical-gray-200 rounded-xl px-2.5 py-1.5 shadow-2xs text-xs font-bold text-medical-gray-700">
<SlidersHorizontal className="w-3.5 h-3.5 text-canina-blue ml-1.5 shrink-0" />
<select
value={`${sortBy}:${sortOrder}`}
onChange={(e) => {
const [b, o] = e.target.value.split(':');
setSortBy(b);
setSortOrder(o as 'asc' | 'desc');
}}
className="bg-transparent text-[11px] font-black text-medical-gray-800 outline-none cursor-pointer pr-1"
>
<option value="createdAt:desc">جدیدترین</option>
<option value="createdAt:asc">قدیمی‌ترین</option>
<option value="priceValue:asc">ارزان‌ترین</option>
<option value="priceValue:desc">گران‌ترین</option>
<option value="nameFa:asc">الف - ی</option>
</select>
</div>
</div>
{/* 3. Three Segmented Pet Type Buttons (Dog right, Both middle, Cat left) */}
<div className="flex-shrink-0 inline-flex items-center bg-white border border-medical-gray-200 rounded-xl px-1.5 py-0.5 shadow-2xs">
{/* Right: Dog */}
<button
type="button"
onClick={() => setSelectedPet("سگ")}
className={`flex items-center gap-1 px-1 py-1 rounded-lg text-[11px] font-black transition-all ${selectedPet === "سگ" ? "bg-canina-blue text-white shadow-xs" : "text-medical-gray-500 hover:text-medical-gray-800"}`}
>
<Dog className="w-3.5 h-3.5" />
<span>سگ</span>
</button>
{/* Middle: Both */}
<button
type="button"
onClick={() => setSelectedPet("all")}
className={`flex items-center gap-1 px-1 py-1 rounded-lg text-[11px] font-black transition-all ${selectedPet === "all" ? "bg-canina-blue text-white shadow-xs" : "text-medical-gray-500 hover:text-medical-gray-800"}`}
>
<Activity className="w-3.5 h-3.5" />
<span>هردو</span>
</button>
{/* Left: Cat */}
<button
type="button"
onClick={() => setSelectedPet("گربه")}
className={`flex items-center gap-1 px-1 py-1 rounded-lg text-[11px] font-black transition-all ${selectedPet === "گربه" ? "bg-canina-blue text-white shadow-xs" : "text-medical-gray-500 hover:text-medical-gray-800"}`}
>
<Cat className="w-3.5 h-3.5" />
<span>گربه</span>
</button>
</div>
{/* 4. Solutions Dropdown / Action Sheet Button */}
<div className="flex-shrink-0">
<button
type="button"
onClick={() => {
setIsMobileSolutionsOpen(!isMobileSolutionsOpen);
setIsMobileSymptomsOpen(false);
}}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-[11px] font-black shadow-2xs transition-all whitespace-nowrap ${selectedCategory !== "all" ? "bg-canina-blue text-white border-canina-blue" : "bg-white border-medical-gray-200 text-medical-gray-700"}`}
>
<span>{selectedCategory !== "all" ? (CATEGORY_LABELS[selectedCategory] || "دسته‌بندی") : "دسته‌بندی و راهکار"}</span>
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSolutionsOpen ? "rotate-180" : ""}`} />
</button>
{isMobileSolutionsOpen && isMounted && createPortal(
<div className="fixed inset-0 z-[9999] flex items-end justify-center bg-black/50 backdrop-blur-xs font-vazir" dir="rtl" onClick={() => setIsMobileSolutionsOpen(false)}>
<div
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[75vh] flex flex-col animate-in slide-in-from-bottom duration-200"
onClick={(e) => e.stopPropagation()}
>
<div className="w-10 h-1 bg-medical-gray-200 rounded-full mx-auto mb-3 shrink-0" />
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-100 mb-3 shrink-0">
<h4 className="font-black text-sm text-medical-gray-900">فیلتر دسته‌بندی و راهکار درمانی</h4>
<button
type="button"
onClick={() => setIsMobileSolutionsOpen(false)}
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1 cursor-pointer"
>
بستن ✕
</button>
</div>
<div className="overflow-y-auto space-y-1.5 py-1">
{categories.map(cat => (
<button
key={cat.id}
type="button"
onClick={() => {
setSelectedCategory(cat.id);
setIsMobileSolutionsOpen(false);
}}
className={`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold text-right transition-colors border cursor-pointer ${selectedCategory === cat.id ? "bg-canina-blue border-canina-blue text-white" : "bg-white border-medical-gray-100 hover:bg-medical-gray-50 text-medical-gray-700"}`}
>
<span className="shrink-0">{cat.icon}</span>
<span className="truncate">{cat.label}</span>
</button>
))}
</div>
</div>
</div>,
document.body
)}
</div>
{/* 5. Symptoms Dropdown / Action Sheet Button with search inside */}
<div className="flex-shrink-0">
<button
type="button"
onClick={() => {
setIsMobileSymptomsOpen(!isMobileSymptomsOpen);
setIsMobileSolutionsOpen(false);
}}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-[11px] font-black shadow-2xs transition-all whitespace-nowrap ${activeSymptoms.length > 0 ? "bg-canina-blue text-white border-canina-blue" : "bg-white border-medical-gray-200 text-medical-gray-700"}`}
>
<span>علائم پت {activeSymptoms.length > 0 ? `(${toPersian(activeSymptoms.length)})` : ""}</span>
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSymptomsOpen ? "rotate-180" : ""}`} />
</button>
{isMobileSymptomsOpen && isMounted && createPortal(
<div className="fixed inset-0 z-[9999] flex items-end justify-center bg-black/50 backdrop-blur-xs font-vazir" dir="rtl" onClick={() => setIsMobileSymptomsOpen(false)}>
<div
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[80vh] flex flex-col animate-in slide-in-from-bottom duration-200"
onClick={(e) => e.stopPropagation()}
>
<div className="w-10 h-1 bg-medical-gray-200 rounded-full mx-auto mb-3 shrink-0" />
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-100 mb-3 shrink-0">
<div>
<h4 className="font-black text-sm text-medical-gray-900">فیلتر بر اساس علائم پت</h4>
<span className="text-[11px] text-medical-gray-400">یک یا چند مورد از علائم را انتخاب کنید</span>
</div>
<div className="flex items-center gap-2">
{activeSymptoms.length > 0 && (
<button
type="button"
onClick={() => setActiveSymptoms([])}
className="text-xs font-bold text-red-500 hover:underline px-1 cursor-pointer"
>
پاک کردن همه
</button>
)}
<button
type="button"
onClick={() => setIsMobileSymptomsOpen(false)}
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1 cursor-pointer"
>
بستن ✕
</button>
</div>
</div>
<div className="relative mb-3 shrink-0">
<Search className="absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<input
type="text"
aria-label="جستجوی علائم"
placeholder="جستجوی علائم بیماری یا نیاز دارویی..."
value={symptomSearch}
onChange={(e) => 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"
/>
</div>
<div className="overflow-y-auto flex-1 min-h-0 py-1">
<div className="flex flex-wrap gap-2">
{symptoms.length === 0 ? (
<span className="text-xs text-medical-gray-400 py-4 text-center w-full">در حال بارگذاری علائم...</span>
) : symptoms
.filter(s => s.toLowerCase().includes(symptomSearch.toLowerCase()))
.map(s => (
<button
key={s}
type="button"
onClick={() => toggleSymptom(s)}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border whitespace-nowrap cursor-pointer ${activeSymptoms.includes(s)
? "bg-canina-blue border-canina-blue text-white shadow-2xs"
: "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40 hover:text-canina-blue"
}`}
>
{s}
</button>
))}
</div>
</div>
<div className="pt-3 border-t border-medical-gray-100 mt-2 shrink-0">
<button
type="button"
onClick={() => setIsMobileSymptomsOpen(false)}
className="w-full bg-canina-blue text-white py-2.5 rounded-xl font-bold text-xs shadow-lg shadow-canina-blue/20 cursor-pointer"
>
مشاهده نتایج {activeSymptoms.length > 0 ? `(${toPersian(activeSymptoms.length)} علامت)` : ""}
</button>
</div>
</div>
</div>,
document.body
)}
</div>
</div>
</div>
</div>
{/* Active Filters Bar with X Dismiss Cross Buttons */}
{(selectedCategory !== "all" || selectedPet !== "all" || activeSymptoms.length > 0 || searchQuery) && (
<div className="flex flex-wrap items-center gap-2 mb-6 bg-white p-3 sm:p-4 rounded-2xl border border-medical-gray-200 shadow-sm font-vazir" dir="rtl">
<span className="text-xs font-black text-medical-gray-400 ml-2">فیلترهای فعال:</span>
{selectedCategory !== "all" && (
<span className="inline-flex items-center gap-1.5 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-xl text-xs font-black border border-canina-blue/20">
{CATEGORY_LABELS[selectedCategory] || selectedCategory}
<button onClick={() => setSelectedCategory("all")} className="hover:text-red-500 text-sm leading-none">✕</button>
</span>
)}
{selectedPet !== "all" && (
<span className="inline-flex items-center gap-1.5 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-xl text-xs font-black border border-canina-blue/20">
پت: {selectedPet}
<button onClick={() => setSelectedPet("all")} className="hover:text-red-500 text-sm leading-none">✕</button>
</span>
)}
{activeSymptoms.map(sym => (
<span key={sym} className="inline-flex items-center gap-1.5 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-xl text-xs font-black border border-canina-blue/20">
علائم: {sym}
<button onClick={() => toggleSymptom(sym)} className="hover:text-red-500 text-sm leading-none">✕</button>
</span>
))}
{searchQuery && (
<span className="inline-flex items-center gap-1.5 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-xl text-xs font-black border border-canina-blue/20">
جستجو: {searchQuery}
<button onClick={() => setSearchQuery("")} className="hover:text-red-500 text-sm leading-none">✕</button>
</span>
)}
<button
onClick={() => { setSelectedCategory("all"); setSelectedPet("all"); setActiveSymptoms([]); setSearchQuery(""); }}
className="text-xs font-bold text-red-500 hover:underline mr-auto"
>
حذف همه فیلترها
</button>
</div>
)}
<AnimatePresence mode="wait">
{fetchError ? (
<div key="fetch-error" data-testid="shop-fetch-error" className="bg-white rounded-[2.5rem] p-10 sm:p-14 text-center border border-rose-200/80 shadow-sm flex flex-col items-center">
<div className="w-16 h-16 bg-rose-50 rounded-2xl flex items-center justify-center text-rose-500 mb-4 border border-rose-100">
<AlertCircle className="w-8 h-8" />
</div>
<h3 className="text-xl font-black text-medical-gray-900 mb-2">خطا در دریافت اطلاعات محصولات</h3>
<p className="text-medical-gray-500 max-w-md mb-6 font-medium text-xs sm:text-sm leading-relaxed">{fetchError}</p>
<button
type="button"
onClick={() => fetchProducts()}
className="inline-flex items-center gap-2 bg-canina-blue text-white px-6 py-2.5 rounded-xl font-black text-xs sm:text-sm hover:bg-canina-dark transition-all shadow-md shadow-canina-blue/20 cursor-pointer active:scale-95"
>
<Activity className="w-4 h-4" />
<span>تلاش مجدد</span>
</button>
</div>
) : isUpdating ? (
viewMode === "list" ? (
<div key="skeleton-list" className="flex flex-col gap-3 lg:hidden">
{Array.from({ length: 8 }).map((_, i) => (
<ProductListSkeleton key={i} />
))}
</div>
) : (
<div key="skeleton-grid" className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6">
{Array.from({ length: 8 }).map((_, i) => (
<ProductCardSkeleton key={i} />
))}
</div>
)
) : filteredProducts.length > 0 ? (
<>
{/* Progressive slice of products for optimal DOM density and mobile UX */}
{(() => {
const totalPages = Math.max(1, Math.ceil(filteredProducts.length / pageSize));
const safeCurrentPage = Math.min(currentPage, totalPages);
const startIndex = (safeCurrentPage - 1) * pageSize;
const slicedProducts = filteredProducts.slice(startIndex, startIndex + pageSize);
const totalInStock = filteredProducts.filter(product => !isProductOutOfStock(product)).length;
const totalOutOfStock = filteredProducts.filter(product => isProductOutOfStock(product)).length;
const sections = [
{
key: "available",
title: "محصولات موجود",
totalCount: totalInStock,
products: slicedProducts.filter(product => !isProductOutOfStock(product)),
},
{
key: "unavailable",
title: "محصولات ناموجود",
totalCount: totalOutOfStock,
products: slicedProducts.filter(product => isProductOutOfStock(product)),
}
] as const;
return (
<>
{sections.map(section => section.products.length > 0 && (
<section key={section.key} data-testid={`products-${section.key}`} className="mb-8 last:mb-0">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-black text-medical-gray-900">{section.title}</h2>
<span className="text-xs font-bold text-medical-gray-400">
{toPersian(section.totalCount)} محصول
</span>
</div>
<div
key={viewMode}
className={
viewMode === "list"
? "flex flex-col gap-3 lg:grid lg:grid-cols-2 xl:grid-cols-4 lg:gap-6"
: "grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6"
}
>
<AnimatePresence mode="popLayout">
{section.products.map((p: Product) => (
<React.Fragment key={p.id}>
{viewMode === "list" ? (
<ArchiveProductListItem product={p} />
) : (
<ArchiveProductCard product={p} />
)}
</React.Fragment>
))}
</AnimatePresence>
</div>
</section>
))}
{/* Pagination Controls */}
{totalPages > 1 && (
<nav aria-label="صفحه‌بندی محصولات" data-testid="shop-pagination" className="mt-10 mb-4 flex flex-col sm:flex-row items-center justify-between gap-4 bg-white border border-medical-gray-200/80 rounded-2xl p-4 shadow-xs font-vazir">
<div className="text-xs text-medical-gray-500 font-bold order-2 sm:order-1">
صفحه {toPersian(safeCurrentPage)} از {toPersian(totalPages)} (کل محصولات: {toPersian(filteredProducts.length)})
</div>
<div className="flex items-center gap-2 order-1 sm:order-2">
<button
type="button"
disabled={safeCurrentPage <= 1}
onClick={() => {
setCurrentPage(prev => Math.max(1, prev - 1));
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-label="صفحه قبل"
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
>
قبلی
</button>
<div className="flex items-center gap-1.5">
{Array.from({ length: totalPages }).map((_, i) => {
const pageNum = i + 1;
const isActive = pageNum === safeCurrentPage;
return (
<button
key={pageNum}
type="button"
onClick={() => {
setCurrentPage(pageNum);
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-current={isActive ? "page" : undefined}
className={isActive ? "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer bg-canina-blue text-white shadow-sm" : "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer text-medical-gray-700 hover:bg-medical-gray-100 border border-medical-gray-200/60"}
>
{toPersian(pageNum)}
</button>
);
})}
</div>
<button
type="button"
disabled={safeCurrentPage >= totalPages}
onClick={() => {
setCurrentPage(prev => Math.min(totalPages, prev + 1));
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-label="صفحه بعد"
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
>
بعدی
</button>
</div>
</nav>
)}
</>
);
})()}
{/* SEO Category Rich Description Section (Rendered below products to maintain primary UX while boosting category SEO) */}
{selectedCategory !== "all" && (
<div className="mt-12 bg-white border border-medical-gray-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm space-y-4 font-vazir">
<div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-canina-blue" />
<h3 className="text-lg md:text-xl font-black text-medical-gray-900">
راهنمای تخصصی و درمانی {CATEGORY_LABELS[selectedCategory] || selectedCategory}
</h3>
</div>
<p className="text-xs md:text-sm text-medical-gray-600 leading-relaxed">
{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) تولید و به صورت رسمی در ایران توزیع می‌گردند.'}
</p>
<div className="pt-2 flex flex-wrap gap-2 text-[11px] font-bold text-canina-blue">
<span className="bg-canina-blue/5 px-3 py-1 rounded-lg border border-canina-blue/10">فرمولاسیون اختصاصی Canina Pharma آلمان</span>
<span className="bg-canina-blue/5 px-3 py-1 rounded-lg border border-canina-blue/10">مورد تایید کلینیک‌های تخصصی دامپزشکی</span>
<span className="bg-canina-blue/5 px-3 py-1 rounded-lg border border-canina-blue/10">پروانه بهداشتی واردات رسمی</span>
</div>
</div>
)}
</>
) : (
<div key="empty" className="bg-white rounded-[3rem] p-20 text-center border-2 border-dashed border-medical-gray-200 flex flex-col items-center">
<div className="w-20 h-20 bg-medical-gray-50 rounded-full flex items-center justify-center text-medical-gray-300 mb-6">
<Search className="w-10 h-10" />
</div>
<h3 className="text-2xl font-black text-medical-gray-900 mb-2">محصولی یافت نشد!</h3>
<p className="text-medical-gray-400 max-w-sm mb-8 font-bold">با فیلترهای فعلی محصولی مطابق با نیاز شما پیدا نکردیم. لطفاً فیلترها را گسترده‌تر کنید یا دکمه ریست را بزنید.</p>
<button
onClick={() => {
router.push('/shop');
setSelectedCategory("all");
setSelectedPet("all");
setActiveSymptoms([]);
setSearchQuery("");
}}
className="bg-canina-blue text-white px-8 py-3 rounded-xl font-black text-sm hover:scale-105 transition-transform shadow-lg shadow-canina-blue/20"
>
پاک کردن همه فیلترها و نمایش همه
</button>
</div>
)}
</AnimatePresence>
</main>
</div>
</div>
</div>
);
}