From 59453e809af12bd21d157c68cb1ae3186668e2cb Mon Sep 17 00:00:00 2001 From: iFixKart Dev Date: Tue, 17 Nov 2026 11:53:25 +0530 Subject: [PATCH] feat(catalog): remove rating filter, add mobile filter drawer, category hierarchy accordion, and complete customer review system --- app/products/[slug]/page.tsx | 3 + components/catalog/StandardCatalog.tsx | 645 +++++++++++++++------- components/pdp/ProductReviewsSection.tsx | 190 +++++++ components/pdp/ProductTabsWrapper.tsx | 26 +- components/pdp/ReviewCard.tsx | 123 +++++ components/pdp/ReviewSubmissionModal.tsx | 325 +++++++++++ components/pdp/ReviewSummaryBreakdown.tsx | 104 ++++ services/api/reviewService.ts | 102 ++++ 8 files changed, 1322 insertions(+), 196 deletions(-) create mode 100644 components/pdp/ProductReviewsSection.tsx create mode 100644 components/pdp/ReviewCard.tsx create mode 100644 components/pdp/ReviewSubmissionModal.tsx create mode 100644 components/pdp/ReviewSummaryBreakdown.tsx create mode 100644 services/api/reviewService.ts diff --git a/app/products/[slug]/page.tsx b/app/products/[slug]/page.tsx index 85cd7b2..28ac6f9 100644 --- a/app/products/[slug]/page.tsx +++ b/app/products/[slug]/page.tsx @@ -542,6 +542,9 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
([]); const [categories, setCategories] = useState([]); const [brands, setBrands] = useState([]); - const [selectedCategory, setSelectedCategory] = useState('all'); - const [selectedBrand, setSelectedBrand] = useState('all'); + const [selectedCategory, setSelectedCategory] = useState( + categoryParam || initialCategory?.category_id || 'all' + ); + const [selectedBrand, setSelectedBrand] = useState(brandParam || 'all'); const [highlight, setHighlight] = useState('All Products'); const [priceRangeId, setPriceRangeId] = useState('all'); - const [selectedRating, setSelectedRating] = useState(null); const [sortBy, setSortBy] = useState('default'); const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid'); const [page, setPage] = useState(1); const [isLoading, setIsLoading] = useState(true); const [loadingMore, setLoadingMore] = useState(false); + const [isMobileFilterOpen, setIsMobileFilterOpen] = useState(false); + const [expandedCategoryIds, setExpandedCategoryIds] = useState>({}); const fetchIdRef = useRef(0); const [collapsed, setCollapsed] = useState>({ categories: false, brands: false, highlight: false, price: false, - rating: false, }); const [allProductsTotal, setAllProductsTotal] = useState(0); const [categoryCounts, setCategoryCounts] = useState>({}); @@ -330,10 +336,45 @@ export function StandardCatalog({ }).catch(() => {}); }, []); - const toggleCollapse = (key: CollapseKey) => setCollapsed((prev) => ({ ...prev, [key]: !prev[key] })); + // Synchronize URL search params seamlessly + const syncUrlParams = (catId: string, brandId: string) => { + if (typeof window === 'undefined') return; + const currentParams = new URLSearchParams(window.location.search); + if (catId && catId !== 'all') { + const cat = categories.find( + (c) => c.category_id === catId || c.slug.toLowerCase() === catId.toLowerCase() + ); + currentParams.set('category', cat?.slug || catId); + } else { + currentParams.delete('category'); + } + if (brandId && brandId !== 'all') { + const b = brands.find( + (br) => br.brand_id === brandId || br.slug.toLowerCase() === brandId.toLowerCase() + ); + currentParams.set('brand', b?.slug || brandId); + } else { + currentParams.delete('brand'); + } + const qs = currentParams.toString(); + router.replace(`/shop${qs ? `?${qs}` : ''}`, { scroll: false }); + }; + + const handleCategorySelect = (catId: string) => { + const nextCat = selectedCategory === catId ? 'all' : catId; + setSelectedCategory(nextCat); + syncUrlParams(nextCat, selectedBrand); + }; + + const handleBrandSelect = (brandId: string) => { + const nextBrand = selectedBrand === brandId ? 'all' : brandId; + setSelectedBrand(nextBrand); + syncUrlParams(selectedCategory, nextBrand); + }; + useEffect(() => { catalogService.getCategories().then((catData) => { setCategories(catData); @@ -355,12 +396,42 @@ export function StandardCatalog({ setSelectedCategory(found?.category_id || categoryParam); } else if (initialCategory) { setSelectedCategory(initialCategory.category_id); - } else { - setSelectedCategory('all'); } }); }, [categoryParam, initialCategory]); + // Group root categories and their child subcategories + const rootCategories = useMemo(() => { + return categories.filter((c) => !c.parent_category_id); + }, [categories]); + + const subCategoriesMap = useMemo(() => { + const map: Record = {}; + for (const cat of categories) { + if (cat.parent_category_id) { + if (!map[cat.parent_category_id]) map[cat.parent_category_id] = []; + map[cat.parent_category_id].push(cat); + } + } + return map; + }, [categories]); + + // Auto-expand active category parent in accordion + useEffect(() => { + if (selectedCategory && selectedCategory !== 'all') { + const found = categories.find( + (c) => + c.category_id === selectedCategory || + c.slug.toLowerCase() === selectedCategory.toLowerCase() + ); + if (found?.parent_category_id) { + setExpandedCategoryIds((prev) => ({ ...prev, [found.parent_category_id!]: true })); + } else if (found?.category_id) { + setExpandedCategoryIds((prev) => ({ ...prev, [found.category_id]: true })); + } + } + }, [selectedCategory, categories]); + useEffect(() => { const activeCatId = selectedCategory === 'all' ? undefined : selectedCategory; catalogService.getBrands(activeCatId).then((brandData) => { @@ -386,7 +457,6 @@ export function StandardCatalog({ searchQuery, highlight, priceRangeId, - selectedRating, sortBy, ]); @@ -457,22 +527,11 @@ export function StandardCatalog({ const filteredProducts = useMemo(() => { return applyCatalogFilters(productPool, { priceRangeId, - selectedRating, + selectedRating: null, highlight, sortBy, }); - }, [productPool, priceRangeId, selectedRating, highlight, sortBy]); - - const ratingFilterPool = useMemo( - () => - applyCatalogFilters(productPool, { - priceRangeId, - selectedRating: null, - highlight, - sortBy: 'default', - }), - [productPool, priceRangeId, highlight] - ); + }, [productPool, priceRangeId, highlight, sortBy]); const displayed = useMemo( () => filteredProducts.slice(0, page * CATALOG_PAGE_SIZE), @@ -489,18 +548,225 @@ export function StandardCatalog({ setSelectedBrand('all'); setHighlight('All Products'); setPriceRangeId('all'); - setSelectedRating(null); setSortBy('default'); setPage(1); + if (typeof window !== 'undefined') { + const currentParams = new URLSearchParams(window.location.search); + currentParams.delete('category'); + currentParams.delete('brand'); + currentParams.delete('search'); + const qs = currentParams.toString(); + router.replace(`/shop${qs ? `?${qs}` : ''}`, { scroll: false }); + } }; const handleLoadMore = () => { setLoadingMore(true); setPage((p) => p + 1); - // next paint after slice grows requestAnimationFrame(() => setLoadingMore(false)); }; + const activeFiltersCount = useMemo(() => { + let count = 0; + if (selectedCategory !== 'all') count++; + if (selectedBrand !== 'all') count++; + if (highlight !== 'All Products') count++; + if (priceRangeId !== 'all') count++; + return count; + }, [selectedCategory, selectedBrand, highlight, priceRangeId]); + + // Reusable Filter Cards Component (used in both desktop sidebar & mobile drawer) + const renderFiltersContent = () => ( +
+ {/* 1. Categories Accordion */} + toggleCollapse('categories')} + > +
+ + + {rootCategories.map((parent) => { + const isParentActive = + selectedCategory === parent.category_id || + selectedCategory.toLowerCase() === parent.slug.toLowerCase(); + const parentCount = + categoryCounts[parent.category_id] ?? + categoryCounts[parent.slug] ?? + parent.product_count ?? + 0; + const subs = subCategoriesMap[parent.category_id] || parent.sub_categories || []; + const hasSubs = subs.length > 0; + const isExpanded = !!expandedCategoryIds[parent.category_id]; + + return ( +
+
+ +
+ ({parentCount}) + {hasSubs && ( + + )} +
+
+ + {hasSubs && isExpanded && ( +
+ {subs.map((sub) => { + const isSubActive = + selectedCategory === sub.category_id || + selectedCategory.toLowerCase() === sub.slug.toLowerCase(); + const subCount = + categoryCounts[sub.category_id] ?? + categoryCounts[sub.slug] ?? + sub.product_count ?? + 0; + return ( + + ); + })} +
+ )} +
+ ); + })} +
+
+ + {/* 2. Brands */} + toggleCollapse('brands')}> +
+ + {brands.map((brand) => { + const checked = selectedBrand === brand.brand_id; + return ( + + ); + })} +
+
+ + {/* 3. Highlight */} + toggleCollapse('highlight')} + > +
+ {HIGHLIGHTS.map((item) => ( + + ))} +
+
+ + {/* 4. Price Filter */} + toggleCollapse('price')}> +
+ {CATALOG_PRICE_RANGES.map((range) => ( + + ))} +
+
+
+ ); + return (
@@ -510,177 +776,110 @@ export function StandardCatalog({
+ {/* Mobile Filter & Sort Bar (Visible on mobile/tablet < lg) */} +
+ + +
+ Sort: +
+ + +
+
+
+ + {/* Active Filter Chips */} + {activeFiltersCount > 0 && ( +
+ Active: + {selectedCategory !== 'all' && ( + + )} + {selectedBrand !== 'all' && ( + + )} + {priceRangeId !== 'all' && ( + + )} + {highlight !== 'All Products' && ( + + )} + +
+ )} +
-
+ {/* Slide-over Mobile Filter Drawer */} + {isMobileFilterOpen && ( +
+ {/* Backdrop */} +
setIsMobileFilterOpen(false)} + /> + + {/* Drawer Sheet */} +
+ {/* Header */} +
+
+ +

Filters

+ {activeFiltersCount > 0 && ( + + {activeFiltersCount} + + )} +
+ +
+ + {/* Scrollable Body */} +
+ {renderFiltersContent()} +
+ + {/* Sticky Footer */} +
+ + +
+
+
+ )} +
diff --git a/components/pdp/ProductReviewsSection.tsx b/components/pdp/ProductReviewsSection.tsx new file mode 100644 index 0000000..62dd5f1 --- /dev/null +++ b/components/pdp/ProductReviewsSection.tsx @@ -0,0 +1,190 @@ +'use client'; + +import React, { useState, useEffect } from 'react'; +import { ChevronDown, MessageSquare, Loader2 } from 'lucide-react'; +import { reviewService, ProductReviewItem, ProductReviewSummaryResponse } from '@/services/api/reviewService'; +import { ReviewSummaryBreakdown } from './ReviewSummaryBreakdown'; +import { ReviewCard } from './ReviewCard'; +import { ReviewSubmissionModal } from './ReviewSubmissionModal'; + +interface ProductReviewsSectionProps { + productId: string; + productName: string; + onReviewsCountChange?: (count: number) => void; +} + +export function ProductReviewsSection({ + productId, + productName, + onReviewsCountChange, +}: ProductReviewsSectionProps) { + const [data, setData] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [sort, setSort] = useState('newest'); + const [page, setPage] = useState(1); + const [isModalOpen, setIsModalOpen] = useState(false); + const [isLoadingMore, setIsLoadingMore] = useState(false); + + useEffect(() => { + setIsLoading(true); + reviewService + .getProductReviews(productId, 1, 10, sort) + .then((res) => { + setData(res); + if (onReviewsCountChange) onReviewsCountChange(res.total_reviews); + }) + .finally(() => { + setIsLoading(false); + }); + }, [productId, sort]); + + const handleLoadMore = () => { + if (!data) return; + setIsLoadingMore(true); + const nextPage = page + 1; + reviewService + .getProductReviews(productId, nextPage, 10, sort) + .then((res) => { + setData((prev) => { + if (!prev) return res; + return { + ...res, + reviews: [...prev.reviews, ...res.reviews], + }; + }); + setPage(nextPage); + }) + .finally(() => { + setIsLoadingMore(false); + }); + }; + + const handleReviewSubmitted = (newReview: ProductReviewItem) => { + setData((prev) => { + const existingReviews = prev ? prev.reviews : []; + const updatedReviews = [newReview, ...existingReviews]; + const newTotal = (prev?.total_reviews || 0) + 1; + const starKey = String(newReview.rating); + const newDist = { ...(prev?.star_distribution || {}) }; + newDist[starKey] = (newDist[starKey] || 0) + 1; + + if (onReviewsCountChange) onReviewsCountChange(newTotal); + + return { + average_rating: prev ? ((prev.average_rating * prev.total_reviews) + newReview.rating) / newTotal : newReview.rating, + total_reviews: newTotal, + star_distribution: newDist, + verified_count: (prev?.verified_count || 0) + (newReview.verified_buyer ? 1 : 0), + page: 1, + limit: 10, + reviews: updatedReviews, + }; + }); + }; + + if (isLoading) { + return ( +
+ +

Loading customer reviews...

+
+ ); + } + + const reviews = data?.reviews || []; + const totalReviews = data?.total_reviews || 0; + const averageRating = data?.average_rating || 0; + const verifiedCount = data?.verified_count || 0; + const starDistribution = data?.star_distribution || { '5': 0, '4': 0, '3': 0, '2': 0, '1': 0 }; + const hasMore = reviews.length < totalReviews; + + return ( +
+ {/* 1. Summary Breakdown */} + setIsModalOpen(true)} + /> + + {/* 2. Reviews Header with Sorting */} +
+

+ Customer Feedback ({totalReviews}) +

+ + {reviews.length > 0 && ( +
+ Sort by: +
+ + +
+
+ )} +
+ + {/* 3. Review Cards List */} + {reviews.length === 0 ? ( +
+ +

No reviews yet

+

+ Have you purchased this product? Be the first to share your thoughts with other customers. +

+ +
+ ) : ( +
+ {reviews.map((r) => ( + + ))} +
+ )} + + {/* 4. Load More Button */} + {hasMore && ( +
+ +
+ )} + + {/* 5. Submission Modal */} + setIsModalOpen(false)} + onReviewSubmitted={handleReviewSubmitted} + /> +
+ ); +} diff --git a/components/pdp/ProductTabsWrapper.tsx b/components/pdp/ProductTabsWrapper.tsx index 21cd6e0..9a04ab8 100644 --- a/components/pdp/ProductTabsWrapper.tsx +++ b/components/pdp/ProductTabsWrapper.tsx @@ -1,28 +1,37 @@ "use client"; import React, { useState } from 'react'; +import { ProductReviewsSection } from './ProductReviewsSection'; interface ProductTabsWrapperProps { + productId?: string; + productName?: string; + initialReviewsCount?: number; descriptionHtml: React.ReactNode; specsHtml: React.ReactNode; showSpecifications?: boolean; } -type TabId = 'description' | 'specs'; +type TabId = 'description' | 'specs' | 'reviews'; const TAB_LINE = 'border-[#e0e0e0]'; const BOX = 'border border-[#e0e0e0]'; export const ProductTabsWrapper: React.FC = ({ + productId, + productName, + initialReviewsCount = 0, descriptionHtml, specsHtml, showSpecifications = true, }) => { const [activeTab, setActiveTab] = useState('description'); + const [reviewsCount, setReviewsCount] = useState(initialReviewsCount); const tabs: { id: TabId; label: string }[] = [ { id: 'description', label: 'Description' }, ...(showSpecifications ? [{ id: 'specs' as TabId, label: 'Specifications' }] : []), + { id: 'reviews' as TabId, label: `Reviews (${reviewsCount})` }, ]; return ( @@ -38,7 +47,7 @@ export const ProductTabsWrapper: React.FC = ({ onClick={() => setActiveTab(tab.id)} className={`-mb-px pb-[13px] text-[14px] leading-none whitespace-nowrap cursor-pointer border-b-2 transition-colors ${ isActive - ? 'border-primary text-[#222]' + ? 'border-primary text-[#222] font-bold' : 'border-transparent text-[#9a9a9a] hover:text-[#555]' }`} > @@ -67,6 +76,19 @@ export const ProductTabsWrapper: React.FC = ({ {specsHtml}
+ {/* ── Reviews ── */} +
+ {productId ? ( + + ) : ( +

Reviews unavailable

+ )} +
+
); diff --git a/components/pdp/ReviewCard.tsx b/components/pdp/ReviewCard.tsx new file mode 100644 index 0000000..ccf0da5 --- /dev/null +++ b/components/pdp/ReviewCard.tsx @@ -0,0 +1,123 @@ +'use client'; + +import React, { useState } from 'react'; +import Image from 'next/image'; +import { Star, CheckCircle, MessageSquareQuote, X } from 'lucide-react'; +import { ProductReviewItem } from '@/services/api/reviewService'; +import { getImageUrl } from '@/lib/utils'; + +export function ReviewCard({ review }: { review: ProductReviewItem }) { + const [selectedImage, setSelectedImage] = useState(null); + + return ( +
+ {/* Header: Author & Verified Badge & Date */} +
+
+
+ {review.author_name ? review.author_name.charAt(0).toUpperCase() : 'U'} +
+
+
+ + {review.author_name} + + {review.verified_buyer && ( + + + Verified Purchase + + )} +
+ {review.review_date && ( + + Reviewed on {review.review_date} + + )} +
+
+ + {/* Stars */} +
+ {Array.from({ length: 5 }).map((_, i) => ( + + ))} +
+
+ + {/* Review Title */} + {review.title && ( +

+ {review.title} +

+ )} + + {/* Review Body */} +

+ {review.comment} +

+ + {/* Uploaded Customer Photos */} + {review.images && review.images.length > 0 && ( +
+ {review.images.map((imgUrl, idx) => { + const fullUrl = getImageUrl(imgUrl); + return ( + + ); + })} +
+ )} + + {/* Admin Reply */} + {review.admin_reply && ( +
+
+ + iFixKart Response +
+

{review.admin_reply}

+
+ )} + + {/* Lightbox Modal */} + {selectedImage && ( +
setSelectedImage(null)} + > +
+ + Customer photo enlarged +
+
+ )} +
+ ); +} diff --git a/components/pdp/ReviewSubmissionModal.tsx b/components/pdp/ReviewSubmissionModal.tsx new file mode 100644 index 0000000..e0241aa --- /dev/null +++ b/components/pdp/ReviewSubmissionModal.tsx @@ -0,0 +1,325 @@ +'use client'; + +import React, { useState, useEffect } from 'react'; +import { Star, X, Upload, CheckCircle2, AlertCircle, Loader2 } from 'lucide-react'; +import { useAuthStore } from '@/store/authStore'; +import { reviewService, ProductReviewItem } from '@/services/api/reviewService'; + +interface ReviewSubmissionModalProps { + productId: string; + productName: string; + isOpen: boolean; + onClose: () => void; + onReviewSubmitted: (newReview: ProductReviewItem) => void; +} + +const RATING_DESCRIPTIONS: Record = { + 1: 'Terrible - Very disappointed', + 2: 'Poor - Not as expected', + 3: 'Average - It was okay', + 4: 'Good - Satisfied with quality', + 5: 'Excellent - Highly recommended!', +}; + +export function ReviewSubmissionModal({ + productId, + productName, + isOpen, + onClose, + onReviewSubmitted, +}: ReviewSubmissionModalProps) { + const customer = useAuthStore((s) => s.customer); + + const [rating, setRating] = useState(5); + const [hoverRating, setHoverRating] = useState(null); + const [title, setTitle] = useState(''); + const [comment, setComment] = useState(''); + const [authorName, setAuthorName] = useState(''); + const [authorEmail, setAuthorEmail] = useState(''); + const [selectedFiles, setSelectedFiles] = useState([]); + const [filePreviews, setFilePreviews] = useState([]); + const [isSubmitting, setIsSubmitting] = useState(false); + const [errorMsg, setErrorMsg] = useState(null); + const [isSuccess, setIsSuccess] = useState(false); + + useEffect(() => { + if (customer) { + const fullName = [customer.first_name, customer.last_name].filter(Boolean).join(' '); + if (fullName) setAuthorName(fullName); + if (customer.email) setAuthorEmail(customer.email); + } + }, [customer]); + + if (!isOpen) return null; + + const handleFileChange = (e: React.ChangeEvent) => { + const files = Array.from(e.target.files || []); + if (!files.length) return; + + const remainingSlots = 3 - selectedFiles.length; + const toAdd = files.slice(0, remainingSlots); + + setSelectedFiles((prev) => [...prev, ...toAdd]); + const newPreviews = toAdd.map((f) => URL.createObjectURL(f)); + setFilePreviews((prev) => [...prev, ...newPreviews]); + }; + + const removeFile = (index: number) => { + setSelectedFiles((prev) => prev.filter((_, i) => i !== index)); + setFilePreviews((prev) => { + URL.revokeObjectURL(prev[index]); + return prev.filter((_, i) => i !== index); + }); + }; + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setErrorMsg(null); + + if (!title.trim()) { + setErrorMsg('Please enter a headline for your review.'); + return; + } + if (!comment.trim() || comment.trim().length < 5) { + setErrorMsg('Please enter a detailed review comment (at least 5 characters).'); + return; + } + if (!authorName.trim()) { + setErrorMsg('Please enter your name.'); + return; + } + + setIsSubmitting(true); + + try { + // 1. Upload images if any + const imageUrls: string[] = []; + for (const file of selectedFiles) { + try { + const url = await reviewService.uploadReviewImage(file, productId); + if (url) imageUrls.push(url); + } catch (uploadErr) { + console.warn('Image upload error, continuing without this photo:', uploadErr); + } + } + + // 2. Submit the review + const newReview = await reviewService.submitReview(productId, { + rating, + title: title.trim(), + comment: comment.trim(), + author_name: authorName.trim(), + author_email: authorEmail.trim() || undefined, + image_urls: imageUrls, + }); + + setIsSuccess(true); + setTimeout(() => { + onReviewSubmitted(newReview); + onClose(); + setIsSuccess(false); + }, 1500); + } catch (err: any) { + setErrorMsg(err.message || 'Failed to submit review. Please try again.'); + } finally { + setIsSubmitting(false); + } + }; + + const activeRating = hoverRating ?? rating; + + return ( +
+
+ {/* Header */} +
+
+

Write a Review

+

{productName}

+
+ +
+ + {/* Success Banner */} + {isSuccess ? ( +
+ +

Thank You!

+

+ Your review has been successfully submitted and verified. +

+
+ ) : ( + /* Form */ +
+ {errorMsg && ( +
+ + {errorMsg} +
+ )} + + {/* Overall Rating */} +
+ +
+ {[1, 2, 3, 4, 5].map((star) => ( + + ))} + + {RATING_DESCRIPTIONS[activeRating] || ''} + +
+
+ + {/* Review Title */} +
+ + setTitle(e.target.value)} + placeholder="e.g. Excellent display, perfectly fits my Samsung A80" + className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:border-primary" + required + /> +
+ + {/* Review Comment */} +
+ +