From 3d45b618ab3d5584fdbcab02b60c5f9458556107 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 10:42:55 +0000 Subject: [PATCH] feat(search): redesign search page for mobile-first layout with multi-content tabs (products, blogs, wiki, videos) --- .../components/SearchResultsPage.tsx | 690 ++++++++++++++---- 1 file changed, 548 insertions(+), 142 deletions(-) diff --git a/frontend/application/components/SearchResultsPage.tsx b/frontend/application/components/SearchResultsPage.tsx index 1bf69ef8..6d56a762 100644 --- a/frontend/application/components/SearchResultsPage.tsx +++ b/frontend/application/components/SearchResultsPage.tsx @@ -1,182 +1,588 @@ "use client"; -import React, { useState, useEffect } from "react"; -import { Search, ChevronLeft, ArrowRight, Sparkles, Heart, AlertCircle } from "lucide-react"; + +import React, { useState, useEffect, useMemo } from "react"; +import { + Search, + ChevronLeft, + ArrowRight, + Sparkles, + Heart, + AlertCircle, + ShoppingBag, + FileText, + BookOpen, + Video, + Check, + ExternalLink, + Pill, + Clock, + PlayCircle +} from "lucide-react"; import { usePetStore } from "../lib/store/usePetStore"; -import { motion } from "motion/react"; +import { motion, AnimatePresence } from "motion/react"; import { Product } from "../lib/data/products"; import { productService } from "../lib/services/productService"; - import Link from "next/link"; import Image from "next/image"; import { useRouter } from 'next/navigation'; +import api from "../lib/services/api"; +import { toPersian } from "../lib/utils"; + +type SearchTab = "all" | "products" | "blogs" | "wiki" | "videos"; + +interface BlogItem { + id: string; + title: string; + slug: string; + excerpt?: string; + category?: string | { name?: string }; + imageUrl?: string; + readingTime?: number; +} + +interface WikiItem { + id: string; + name?: string; + nameFa?: string; + scientificName?: string; + slug?: string; + description?: string; + category?: string; +} + +interface VideoItem { + id: string; + title: string; + doctor?: string; + duration?: string; + thumbnail?: string; + description?: string; +} export default function SearchResultsPage({ query }: { query: string }) { const router = useRouter(); const { getActivePet } = usePetStore(); const activePet = getActivePet(); - const [products, setProducts] = useState([]); + const [activeTab, setActiveTab] = useState("all"); + const [searchInput, setSearchInput] = useState(query); + + const [products, setProducts] = useState([]); + const [blogs, setBlogs] = useState([]); + const [wikiItems, setWikiItems] = useState([]); + const [videos, setVideos] = useState([]); + const [isLoading, setIsLoading] = useState(true); + + // Sync input when prop changes useEffect(() => { - productService.getProducts({ limit: 999 }) - .then(res => setProducts(res.data)) - .catch(err => console.error("Error fetching products in SearchResultsPage:", err)); + setSearchInput(query); + }, [query]); + + // Fetch all searchable datasets in parallel + useEffect(() => { + let isMounted = true; + setIsLoading(true); + + const loadAll = async () => { + try { + const [prodRes, blogRes, wikiRes, videoRes] = await Promise.allSettled([ + productService.getProducts({ limit: 999 }), + api.get("/blogs?limit=50"), + api.get("/ingredients?limit=100"), + api.get("/videos?limit=50") + ]); + + if (!isMounted) return; + + if (prodRes.status === "fulfilled" && prodRes.value?.data) { + setProducts(prodRes.value.data); + } else if (prodRes.status === "rejected") { + console.error("Error fetching products in SearchResultsPage:", prodRes.reason); + } + + if (blogRes.status === "fulfilled" && blogRes.value?.data) { + const list = Array.isArray(blogRes.value.data.data) + ? blogRes.value.data.data + : Array.isArray(blogRes.value.data) + ? blogRes.value.data + : []; + setBlogs(list); + } + + if (wikiRes.status === "fulfilled" && wikiRes.value?.data) { + const list = Array.isArray(wikiRes.value.data.data) + ? wikiRes.value.data.data + : Array.isArray(wikiRes.value.data) + ? wikiRes.value.data + : []; + setWikiItems(list); + } + + if (videoRes.status === "fulfilled" && videoRes.value?.data) { + const vList = videoRes.value.data.videos || videoRes.value.data.data || videoRes.value.data; + setVideos(Array.isArray(vList) ? vList : []); + } + } catch (err) { + console.error("Error loading search datasets:", err); + } finally { + if (isMounted) setIsLoading(false); + } + }; + + loadAll(); + return () => { isMounted = false; }; }, []); - const results = products.filter(p => - p.name.toLowerCase().includes(query.toLowerCase()) || - p.description.toLowerCase().includes(query.toLowerCase()) || - p.main_ingredients.some(ing => ing.toLowerCase().includes(query.toLowerCase())) || - p.symptoms.some(sym => sym.toLowerCase().includes(query.toLowerCase())) - ); + const cleanQuery = (query || "").trim().toLowerCase(); + // 1. Filtered Products + const filteredProducts = useMemo(() => { + if (!cleanQuery) return products; + return products.filter(p => + (p.name || '').toLowerCase().includes(cleanQuery) || + (p.description || '').toLowerCase().includes(cleanQuery) || + (Array.isArray(p.main_ingredients) && p.main_ingredients.some(ing => ing.toLowerCase().includes(cleanQuery))) || + (Array.isArray(p.symptoms) && p.symptoms.some(sym => sym.toLowerCase().includes(cleanQuery))) || + (p.nameFa || '').toLowerCase().includes(cleanQuery) || + (p.nameEn || '').toLowerCase().includes(cleanQuery) + ); + }, [products, cleanQuery]); + + // 2. Filtered Blogs + const filteredBlogs = useMemo(() => { + if (!cleanQuery) return blogs; + return blogs.filter(b => + (b.title || '').toLowerCase().includes(cleanQuery) || + (b.excerpt || '').toLowerCase().includes(cleanQuery) + ); + }, [blogs, cleanQuery]); + + // 3. Filtered Wiki Items + const filteredWiki = useMemo(() => { + if (!cleanQuery) return wikiItems; + return wikiItems.filter(w => + (w.name || '').toLowerCase().includes(cleanQuery) || + (w.nameFa || '').toLowerCase().includes(cleanQuery) || + (w.scientificName || '').toLowerCase().includes(cleanQuery) || + (w.description || '').toLowerCase().includes(cleanQuery) + ); + }, [wikiItems, cleanQuery]); + + // 4. Filtered Videos + const filteredVideos = useMemo(() => { + if (!cleanQuery) return videos; + return videos.filter(v => + (v.title || '').toLowerCase().includes(cleanQuery) || + (v.doctor || '').toLowerCase().includes(cleanQuery) || + (v.description || '').toLowerCase().includes(cleanQuery) + ); + }, [videos, cleanQuery]); + + const totalResults = filteredProducts.length + filteredBlogs.length + filteredWiki.length + filteredVideos.length; const bestSellers = products.slice(0, 3); + const handleSearchSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (searchInput.trim()) { + router.push(`/search?q=${encodeURIComponent(searchInput.trim())}`); + } else { + router.push('/search'); + } + }; + return ( -
+
- -
-
-

- {query ? ( - <>نتایج جستجو برای: "{query}" - ) : ( - "جستجوی هوشمند در محصولات و مکمل‌های کنینا" - )} -

-

- {query - ? `${results.length} محصول با معیارهای شما مطابقت دارد.` - : "نام دارو، ترکیب مؤثره، علامت بیماری یا مشکل پت خود را جستجو کنید."} -

- - {/* Direct Interactive Search Box */} -
{ - e.preventDefault(); - const form = e.currentTarget; - const input = form.elements.namedItem("q") as HTMLInputElement; - if (input && input.value.trim()) { - router.push(`/search?q=${encodeURIComponent(input.value.trim())}`); - } - }} - className="relative max-w-xl" + {/* Mobile-First Header Bar: Back Button & Compact Title */} +
+
+ - + + بازگشت + + جستجوی جامع کنینا
+ + {cleanQuery && ( + + {toPersian(totalResults)} نتیجه + + )}
- {results.length > 0 ? ( -
- {results.map((product) => { - const compatibility = (() => { - if (!activePet) return null; - const sameSpecies = product.suitableFor === activePet.type || product.suitableFor === "هر دو"; - const helpsSymptom = activePet.medicalConditions.some(c => product.symptoms.includes(c)); - if (!sameSpecies) return { type: 'alert', text: `مخصوص ${product.suitableFor}` }; - if (helpsSymptom) return { type: 'success', text: `توصیه شده برای ${activePet.name}` }; - return { type: 'neutral', text: `مناسب برای ${activePet.name}` }; - })(); + {/* Compact Search Header & Input */} +
+

+ {cleanQuery ? ( + <>نتایج جستجو برای: "{query}" + ) : ( + "جستجوی هوشمند در تمامی بخش‌های کنینا" + )} +

+

+ جستجوی هم‌زمان در داروها، مکمل‌ها، مقالات وبلاگ، دانشنامه ترکیبات و ویدیوهای بالینی +

- return ( - - -
- {product.nameFa - {product.specialBadge && ( -
- {product.specialBadge} -
- )} - {compatibility && ( -
- {compatibility.type === 'alert' ? : compatibility.type === 'success' ? : } - {compatibility.text} -
- )} -
+ {/* Search Box Input */} +
+ setSearchInput(e.target.value)} + placeholder="جستجوی دارو، مقاله، ترکیب علمی، ویدیو..." + className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 sm:py-3 pr-10 pl-20 text-xs sm:text-sm font-bold focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-xs text-medical-gray-900" + /> + + + +
-
- {product.category} -

{product.nameFa || product.name}

-

{product.benefits}

-
+ {/* Multi-Content Filter Tabs */} +
+ {[ + { id: "all", label: "همه نتایج", count: totalResults, icon: }, + { id: "products", label: "محصولات و داروها", count: filteredProducts.length, icon: }, + { id: "blogs", label: "مقالات وبلاگ", count: filteredBlogs.length, icon: }, + { id: "wiki", label: "دانشنامه ترکیبات", count: filteredWiki.length, icon: }, + { id: "videos", label: "ویدیوهای بالینی", count: filteredVideos.length, icon:
-
-
- {product.price} + {/* RESULTS AREA */} + {cleanQuery && totalResults === 0 && !isLoading ? ( + /* Empty State - Mobile-Optimized with direct suggestion cards */ +
+
+
+ +
+

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

+

+ متأسفیم، هیچ موردی با عبارت جستجو شده تطبیق نداشت. محصولات پرطرفدار زیر را بررسی کنید: +

+ +
+ + {bestSellers.length > 0 && ( +
+

محصولات پیشنهادی (پرفروش)

+
+ {bestSellers.map(p => ( + +
+ {p.name}
-
- +
+

{p.nameFa || p.name}

+
{p.price}
-
- - - ) - })} + + ))} +
+
+ )}
) : ( -
-
-
- -
-

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

-

- متاسفیم، هیچ محصولی با عبارت مورد نظر شما مطابقت نداشت. شاید محصولات پرفروش ما برای شما مفید باشند؟ -

-
+
-
-

محصولات پیشنهادی (پرفروش)

-
- {bestSellers.map(p => ( - -
- {p.name} -
-

{p.name}

- - ))} + {/* 1. PRODUCTS SECTION */} + {(activeTab === "all" || activeTab === "products") && filteredProducts.length > 0 && ( +
+
+
+ +

محصولات و مکمل‌ها ({toPersian(filteredProducts.length)})

+
+ {activeTab === "all" && filteredProducts.length > 6 && ( + + )}
-
+ +
+ {(activeTab === "all" ? filteredProducts.slice(0, 6) : filteredProducts).map((product) => { + const compatibility = (() => { + if (!activePet) return null; + const sameSpecies = product.suitableFor === activePet.type || product.suitableFor === "هر دو"; + const helpsSymptom = Array.isArray(activePet.medicalConditions) && Array.isArray(product.symptoms) && activePet.medicalConditions.some(c => product.symptoms.includes(c)); + if (!sameSpecies) return { type: 'alert', text: `مخصوص ${product.suitableFor}` }; + if (helpsSymptom) return { type: 'success', text: `توصیه شده برای ${activePet.name}` }; + return { type: 'neutral', text: `مناسب برای ${activePet.name}` }; + })(); + + return ( + +
+
+ {product.nameFa +
+ +
+
+ + {product.category} + + {compatibility && ( + + {compatibility.text} + + )} +
+

+ {product.nameFa || product.name} +

+

+ {product.benefits || product.description} +

+
+
+ +
+ {product.price} + + مشاهده و خرید + + +
+ + ); + })} +
+ + )} + + {/* 2. BLOGS SECTION */} + {(activeTab === "all" || activeTab === "blogs") && filteredBlogs.length > 0 && ( +
+
+
+ +

مقالات مجله سلامت ({toPersian(filteredBlogs.length)})

+
+ {activeTab === "all" && filteredBlogs.length > 4 && ( + + )} +
+ +
+ {(activeTab === "all" ? filteredBlogs.slice(0, 4) : filteredBlogs).map((blog) => ( + + {blog.imageUrl ? ( +
+ {blog.title} +
+ ) : ( +
+ +
+ )} + +
+ + {typeof blog.category === 'object' ? blog.category?.name : blog.category || 'مقاله علمی'} + +

+ {blog.title} +

+

+ {blog.excerpt} +

+
+ + ))} +
+
+ )} + + {/* 3. WIKI SECTION */} + {(activeTab === "all" || activeTab === "wiki") && filteredWiki.length > 0 && ( +
+
+
+ +

دانشنامه ترکیبات علمی ({toPersian(filteredWiki.length)})

+
+ {activeTab === "all" && filteredWiki.length > 4 && ( + + )} +
+ +
+ {(activeTab === "all" ? filteredWiki.slice(0, 4) : filteredWiki).map((wiki) => ( + +
+ +
+
+

+ {wiki.nameFa || wiki.name} +

+ {wiki.scientificName && ( +
+ {wiki.scientificName} +
+ )} +

+ {wiki.description} +

+
+ + + ))} +
+
+ )} + + {/* 4. VIDEOS SECTION */} + {(activeTab === "all" || activeTab === "videos") && filteredVideos.length > 0 && ( +
+
+
+
+ {activeTab === "all" && filteredVideos.length > 3 && ( + + )} +
+ +
+ {(activeTab === "all" ? filteredVideos.slice(0, 3) : filteredVideos).map((vid) => ( + +
+ {vid.thumbnail ? ( + {vid.title} + ) : null} +
+ +
+ {vid.duration && ( + + {vid.duration} + + )} +
+
+
+

+ {vid.title} +

+ {vid.doctor && ( + + {vid.doctor} + + )} +
+
+ + ))} +
+
+ )} +
)} +
);