feat(catalog): remove rating filter, add mobile filter drawer, category hierarchy accordion, and complete customer review system
This commit is contained in:
parent
fd93e7023a
commit
59453e809a
8 changed files with 1322 additions and 196 deletions
|
|
@ -542,6 +542,9 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
|
|||
|
||||
<div className="mt-10">
|
||||
<ProductTabsWrapper
|
||||
productId={product.product_id}
|
||||
productName={product.name}
|
||||
initialReviewsCount={reviews.length}
|
||||
descriptionHtml={descriptionHtml}
|
||||
specsHtml={specsHtml}
|
||||
showSpecifications={product.show_specifications ?? true}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,9 @@ import {
|
|||
ShoppingCart,
|
||||
Star,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
SlidersHorizontal,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useCartStore } from '@/store/cartStore';
|
||||
import { AnnouncementBar } from '@/layout/AnnouncementBar';
|
||||
|
|
@ -60,7 +63,7 @@ const HIGHLIGHTS: CatalogHighlight[] = [
|
|||
'Hot Items',
|
||||
];
|
||||
|
||||
type CollapseKey = 'categories' | 'brands' | 'highlight' | 'price' | 'rating';
|
||||
type CollapseKey = 'categories' | 'brands' | 'highlight' | 'price';
|
||||
|
||||
function mapApiProduct(p: any): ProductResponse {
|
||||
return mapProductCardToProductResponse(p);
|
||||
|
|
@ -298,26 +301,29 @@ export function StandardCatalog({
|
|||
brandParam,
|
||||
searchQuery,
|
||||
}: StandardCatalogProps) {
|
||||
const router = useRouter();
|
||||
const [productPool, setProductPool] = useState<ProductResponse[]>([]);
|
||||
const [categories, setCategories] = useState<CategoryResponse[]>([]);
|
||||
const [brands, setBrands] = useState<BrandResponse[]>([]);
|
||||
const [selectedCategory, setSelectedCategory] = useState('all');
|
||||
const [selectedBrand, setSelectedBrand] = useState('all');
|
||||
const [selectedCategory, setSelectedCategory] = useState<string>(
|
||||
categoryParam || initialCategory?.category_id || 'all'
|
||||
);
|
||||
const [selectedBrand, setSelectedBrand] = useState<string>(brandParam || 'all');
|
||||
const [highlight, setHighlight] = useState<CatalogHighlight>('All Products');
|
||||
const [priceRangeId, setPriceRangeId] = useState('all');
|
||||
const [selectedRating, setSelectedRating] = useState<number | null>(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<Record<string, boolean>>({});
|
||||
const fetchIdRef = useRef(0);
|
||||
const [collapsed, setCollapsed] = useState<Record<CollapseKey, boolean>>({
|
||||
categories: false,
|
||||
brands: false,
|
||||
highlight: false,
|
||||
price: false,
|
||||
rating: false,
|
||||
});
|
||||
const [allProductsTotal, setAllProductsTotal] = useState<number>(0);
|
||||
const [categoryCounts, setCategoryCounts] = useState<Record<string, number>>({});
|
||||
|
|
@ -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<string, CategoryResponse[]> = {};
|
||||
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,91 +548,156 @@ 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));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white text-[#1E293B] flex flex-col font-sans">
|
||||
<AnnouncementBar />
|
||||
<Header />
|
||||
<StickyHeaderSpacer />
|
||||
<Navbar />
|
||||
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]);
|
||||
|
||||
<main className="flex-grow pb-16">
|
||||
<div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6 max-w-[1400px]">
|
||||
<div className="flex flex-col lg:flex-row gap-7 items-start">
|
||||
<aside className="w-full lg:w-[260px] shrink-0 space-y-4">
|
||||
// Reusable Filter Cards Component (used in both desktop sidebar & mobile drawer)
|
||||
const renderFiltersContent = () => (
|
||||
<div className="space-y-4">
|
||||
{/* 1. Categories Accordion */}
|
||||
<FilterCard
|
||||
title="Shop By Categories"
|
||||
open={!collapsed.categories}
|
||||
onToggle={() => toggleCollapse('categories')}
|
||||
>
|
||||
<div className="pt-3 space-y-2.5">
|
||||
<label className="flex items-center justify-between text-[13px] cursor-pointer group">
|
||||
<div className="pt-3 space-y-2 max-h-80 overflow-y-auto pr-1">
|
||||
<label className="flex items-center justify-between text-[13px] cursor-pointer group py-1">
|
||||
<span className="flex items-center gap-2.5">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedCategory === 'all'}
|
||||
onChange={() => setSelectedCategory('all')}
|
||||
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer"
|
||||
onChange={() => handleCategorySelect('all')}
|
||||
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer shrink-0"
|
||||
/>
|
||||
<span className={selectedCategory === 'all' ? 'text-primary font-semibold' : 'text-gray-600'}>
|
||||
Our Store
|
||||
<span className={selectedCategory === 'all' ? 'text-primary font-semibold' : 'text-gray-700'}>
|
||||
All Categories
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-gray-400">({allProductsTotal})</span>
|
||||
<span className="text-gray-400 text-xs shrink-0">({allProductsTotal || 0})</span>
|
||||
</label>
|
||||
{categories.map((cat) => {
|
||||
const checked =
|
||||
selectedCategory === cat.category_id ||
|
||||
selectedCategory.toLowerCase() === cat.slug.toLowerCase();
|
||||
const catCount =
|
||||
categoryCounts[cat.category_id] ??
|
||||
categoryCounts[cat.slug] ??
|
||||
(cat as any).product_count;
|
||||
|
||||
{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 (
|
||||
<label
|
||||
key={cat.category_id}
|
||||
className="flex items-center justify-between text-[13px] cursor-pointer"
|
||||
>
|
||||
<span className="flex items-center gap-2.5 min-w-0">
|
||||
<div key={parent.category_id} className="space-y-1">
|
||||
<div className="flex items-center justify-between text-[13px] group">
|
||||
<label className="flex items-center gap-2.5 min-w-0 cursor-pointer flex-1 py-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => setSelectedCategory(checked ? 'all' : cat.category_id)}
|
||||
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer"
|
||||
checked={isParentActive}
|
||||
onChange={() => handleCategorySelect(parent.category_id)}
|
||||
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer shrink-0"
|
||||
/>
|
||||
<span className={`truncate ${checked ? 'text-primary font-semibold' : 'text-gray-600'}`}>
|
||||
{cat.name}
|
||||
<span className={`truncate ${isParentActive ? 'text-primary font-semibold' : 'text-gray-700 group-hover:text-primary'}`}>
|
||||
{parent.name}
|
||||
</span>
|
||||
</span>
|
||||
{catCount != null && (
|
||||
<span className="text-gray-400 shrink-0">
|
||||
({catCount})
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<div className="flex items-center gap-1.5 shrink-0 ml-1">
|
||||
<span className="text-gray-400 text-xs">({parentCount})</span>
|
||||
{hasSubs && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setExpandedCategoryIds((prev) => ({
|
||||
...prev,
|
||||
[parent.category_id]: !prev[parent.category_id],
|
||||
}));
|
||||
}}
|
||||
className="p-1 text-gray-400 hover:text-gray-700 rounded hover:bg-gray-100 transition-colors"
|
||||
aria-label={`Toggle ${parent.name} subcategories`}
|
||||
>
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className={`transition-transform duration-200 ${isExpanded ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasSubs && isExpanded && (
|
||||
<div className="pl-6 pr-1 py-1 space-y-1.5 border-l-2 border-gray-100 ml-1.5">
|
||||
{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 (
|
||||
<label
|
||||
key={sub.category_id}
|
||||
className="flex items-center justify-between text-[12.5px] cursor-pointer group py-0.5"
|
||||
>
|
||||
<span className="flex items-center gap-2 min-w-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSubActive}
|
||||
onChange={() => handleCategorySelect(sub.category_id)}
|
||||
className="w-3 h-3 rounded border-gray-300 text-primary accent-primary cursor-pointer shrink-0"
|
||||
/>
|
||||
<span className={`truncate ${isSubActive ? 'text-primary font-semibold' : 'text-gray-600 group-hover:text-primary'}`}>
|
||||
{sub.name}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-gray-400 text-[11px] shrink-0">({subCount})</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</FilterCard>
|
||||
|
||||
{/* 2. Brands */}
|
||||
<FilterCard title="Brands" open={!collapsed.brands} onToggle={() => toggleCollapse('brands')}>
|
||||
<div className="pt-3 space-y-2.5 max-h-56 overflow-y-auto">
|
||||
<div className="pt-3 space-y-2.5 max-h-56 overflow-y-auto pr-1">
|
||||
<label className="flex items-center gap-2.5 text-[13px] cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedBrand === 'all'}
|
||||
onChange={() => setSelectedBrand('all')}
|
||||
onChange={() => handleBrandSelect('all')}
|
||||
className="w-3.5 h-3.5 rounded border-gray-300 accent-primary cursor-pointer"
|
||||
/>
|
||||
<span className={selectedBrand === 'all' ? 'text-primary font-semibold' : 'text-gray-600'}>
|
||||
|
|
@ -587,7 +711,7 @@ export function StandardCatalog({
|
|||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => setSelectedBrand(checked ? 'all' : brand.brand_id)}
|
||||
onChange={() => handleBrandSelect(brand.brand_id)}
|
||||
className="w-3.5 h-3.5 rounded border-gray-300 accent-primary cursor-pointer"
|
||||
/>
|
||||
<span className={checked ? 'text-primary font-semibold' : 'text-gray-600'}>
|
||||
|
|
@ -599,6 +723,7 @@ export function StandardCatalog({
|
|||
</div>
|
||||
</FilterCard>
|
||||
|
||||
{/* 3. Highlight */}
|
||||
<FilterCard
|
||||
title="Highlight"
|
||||
open={!collapsed.highlight}
|
||||
|
|
@ -620,6 +745,7 @@ export function StandardCatalog({
|
|||
</div>
|
||||
</FilterCard>
|
||||
|
||||
{/* 4. Price Filter */}
|
||||
<FilterCard title="Price Filter" open={!collapsed.price} onToggle={() => toggleCollapse('price')}>
|
||||
<div className="pt-3 space-y-2">
|
||||
{CATALOG_PRICE_RANGES.map((range) => (
|
||||
|
|
@ -638,49 +764,122 @@ export function StandardCatalog({
|
|||
))}
|
||||
</div>
|
||||
</FilterCard>
|
||||
|
||||
<FilterCard
|
||||
title="Average rating"
|
||||
open={!collapsed.rating}
|
||||
onToggle={() => toggleCollapse('rating')}
|
||||
>
|
||||
<div className="pt-3 space-y-1">
|
||||
{[5, 4, 3, 2, 1].map((stars) => {
|
||||
const active = selectedRating === stars;
|
||||
const matchCount = ratingFilterPool.filter((p) =>
|
||||
productMatchesRating(p, stars)
|
||||
).length;
|
||||
return (
|
||||
<button
|
||||
key={stars}
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
onClick={() =>
|
||||
setSelectedRating(selectedRating === stars ? null : stars)
|
||||
}
|
||||
className={`flex items-center justify-between w-full rounded-md px-2 py-1.5 -mx-2 text-[13px] cursor-pointer ${
|
||||
active
|
||||
? 'bg-[#f3f6fb] text-primary ring-1 ring-[#d7e3f4]'
|
||||
: 'text-gray-600 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-0.5 text-amber-400">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Star
|
||||
key={i}
|
||||
size={12}
|
||||
className={i < stars ? 'fill-amber-400' : 'text-gray-200'}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
<span className={active ? 'text-primary' : 'text-gray-400'}>
|
||||
({stars}+) {isLoading ? '' : matchCount}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</FilterCard>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white text-[#1E293B] flex flex-col font-sans">
|
||||
<AnnouncementBar />
|
||||
<Header />
|
||||
<StickyHeaderSpacer />
|
||||
<Navbar />
|
||||
|
||||
<main className="flex-grow pb-16">
|
||||
<div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6 max-w-[1400px]">
|
||||
{/* Mobile Filter & Sort Bar (Visible on mobile/tablet < lg) */}
|
||||
<div className="lg:hidden mb-4 flex items-center justify-between gap-3 bg-gray-50 p-3 rounded-lg border border-gray-200">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsMobileFilterOpen(true)}
|
||||
className="flex items-center gap-2 px-3.5 py-2 bg-white border border-gray-300 rounded-md shadow-xs text-[13px] font-semibold text-gray-800 hover:border-primary active:bg-gray-50 transition-colors cursor-pointer"
|
||||
>
|
||||
<SlidersHorizontal size={14} className="text-primary" />
|
||||
<span>Filters</span>
|
||||
{activeFiltersCount > 0 && (
|
||||
<span className="w-5 h-5 rounded-full bg-primary text-white text-[11px] font-bold flex items-center justify-center">
|
||||
{activeFiltersCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-gray-500 font-medium hidden sm:inline">Sort:</span>
|
||||
<div className="relative">
|
||||
<select
|
||||
value={sortBy}
|
||||
onChange={(e) => setSortBy(e.target.value)}
|
||||
className="appearance-none bg-white border border-gray-300 rounded-md pl-2.5 pr-7 py-2 text-[12px] font-medium text-gray-700 cursor-pointer focus:outline-none focus:border-primary"
|
||||
>
|
||||
<option value="default">Default</option>
|
||||
<option value="newest">Newest</option>
|
||||
<option value="price-low">Price: Low to High</option>
|
||||
<option value="price-high">Price: High to Low</option>
|
||||
<option value="a-z">A–Z</option>
|
||||
</select>
|
||||
<ChevronDown
|
||||
size={12}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Active Filter Chips */}
|
||||
{activeFiltersCount > 0 && (
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2 text-xs">
|
||||
<span className="text-gray-500 font-medium">Active:</span>
|
||||
{selectedCategory !== 'all' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCategorySelect('all')}
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
|
||||
>
|
||||
<span>
|
||||
{categories.find(
|
||||
(c) => c.category_id === selectedCategory || c.slug.toLowerCase() === selectedCategory.toLowerCase()
|
||||
)?.name || 'Category'}
|
||||
</span>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
{selectedBrand !== 'all' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleBrandSelect('all')}
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
|
||||
>
|
||||
<span>
|
||||
{brands.find(
|
||||
(b) => b.brand_id === selectedBrand || b.slug.toLowerCase() === selectedBrand.toLowerCase()
|
||||
)?.name || 'Brand'}
|
||||
</span>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
{priceRangeId !== 'all' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPriceRangeId('all')}
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
|
||||
>
|
||||
<span>{CATALOG_PRICE_RANGES.find((r) => r.id === priceRangeId)?.label}</span>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
{highlight !== 'All Products' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setHighlight('All Products')}
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
|
||||
>
|
||||
<span>{highlight}</span>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetFilters}
|
||||
className="text-xs text-gray-500 hover:text-red-600 underline ml-1 cursor-pointer"
|
||||
>
|
||||
Reset All
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col lg:flex-row gap-7 items-start">
|
||||
{/* Desktop Sidebar: hidden on mobile (< lg), shown on lg+ */}
|
||||
<aside className="hidden lg:block w-[260px] shrink-0 space-y-4">
|
||||
{renderFiltersContent()}
|
||||
</aside>
|
||||
|
||||
<div className="flex-1 min-w-0 w-full">
|
||||
|
|
@ -788,6 +987,64 @@ export function StandardCatalog({
|
|||
</div>
|
||||
</main>
|
||||
|
||||
{/* Slide-over Mobile Filter Drawer */}
|
||||
{isMobileFilterOpen && (
|
||||
<div className="fixed inset-0 z-[100] lg:hidden flex justify-end">
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 backdrop-blur-xs transition-opacity"
|
||||
onClick={() => setIsMobileFilterOpen(false)}
|
||||
/>
|
||||
|
||||
{/* Drawer Sheet */}
|
||||
<div className="relative z-10 w-full max-w-[320px] bg-white h-full flex flex-col shadow-2xl animate-in slide-in-from-right duration-300">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
|
||||
<div className="flex items-center gap-2">
|
||||
<SlidersHorizontal size={16} className="text-primary" />
|
||||
<h3 className="text-base font-bold text-gray-900">Filters</h3>
|
||||
{activeFiltersCount > 0 && (
|
||||
<span className="w-5 h-5 rounded-full bg-primary text-white text-[11px] font-bold flex items-center justify-center">
|
||||
{activeFiltersCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsMobileFilterOpen(false)}
|
||||
className="p-1.5 text-gray-400 hover:text-gray-700 rounded-full hover:bg-gray-100 cursor-pointer"
|
||||
aria-label="Close filters"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Scrollable Body */}
|
||||
<div className="flex-1 overflow-y-auto p-4 space-y-4">
|
||||
{renderFiltersContent()}
|
||||
</div>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<div className="p-4 border-t border-gray-100 bg-white flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetFilters}
|
||||
className="flex-1 py-2.5 px-3 border border-gray-300 text-gray-700 text-xs font-semibold rounded-lg hover:bg-gray-50 cursor-pointer"
|
||||
>
|
||||
Reset All
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsMobileFilterOpen(false)}
|
||||
className="flex-1 py-2.5 px-3 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 shadow-sm cursor-pointer"
|
||||
>
|
||||
Apply ({totalProducts})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Footer />
|
||||
<FloatingButtons />
|
||||
</div>
|
||||
|
|
|
|||
190
components/pdp/ProductReviewsSection.tsx
Normal file
190
components/pdp/ProductReviewsSection.tsx
Normal file
|
|
@ -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<ProductReviewSummaryResponse | null>(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 (
|
||||
<div className="py-12 flex flex-col items-center justify-center gap-3">
|
||||
<Loader2 size={24} className="text-primary animate-spin" />
|
||||
<p className="text-xs font-semibold text-gray-500">Loading customer reviews...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="py-4">
|
||||
{/* 1. Summary Breakdown */}
|
||||
<ReviewSummaryBreakdown
|
||||
averageRating={averageRating}
|
||||
totalReviews={totalReviews}
|
||||
verifiedCount={verifiedCount}
|
||||
starDistribution={starDistribution}
|
||||
onWriteReviewClick={() => setIsModalOpen(true)}
|
||||
/>
|
||||
|
||||
{/* 2. Reviews Header with Sorting */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-gray-200 mb-2">
|
||||
<h3 className="text-sm font-bold text-gray-900">
|
||||
Customer Feedback ({totalReviews})
|
||||
</h3>
|
||||
|
||||
{reviews.length > 0 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-gray-500 font-medium">Sort by:</span>
|
||||
<div className="relative">
|
||||
<select
|
||||
value={sort}
|
||||
onChange={(e) => setSort(e.target.value)}
|
||||
className="appearance-none bg-white border border-gray-300 rounded-md pl-3 pr-7 py-1.5 text-xs font-medium text-gray-700 cursor-pointer focus:outline-none focus:border-primary"
|
||||
>
|
||||
<option value="newest">Most Recent</option>
|
||||
<option value="highest">Highest Rating</option>
|
||||
<option value="lowest">Lowest Rating</option>
|
||||
<option value="helpful">Most Helpful</option>
|
||||
</select>
|
||||
<ChevronDown
|
||||
size={12}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 3. Review Cards List */}
|
||||
{reviews.length === 0 ? (
|
||||
<div className="py-12 text-center space-y-3">
|
||||
<MessageSquare size={36} className="mx-auto text-gray-300" />
|
||||
<h4 className="text-sm font-bold text-gray-800">No reviews yet</h4>
|
||||
<p className="text-xs text-gray-500 max-w-sm mx-auto">
|
||||
Have you purchased this product? Be the first to share your thoughts with other customers.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsModalOpen(true)}
|
||||
className="px-5 py-2.5 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 shadow-sm inline-flex items-center gap-2 cursor-pointer mt-2"
|
||||
>
|
||||
Write the First Review
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{reviews.map((r) => (
|
||||
<ReviewCard key={r.review_id} review={r} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 4. Load More Button */}
|
||||
{hasMore && (
|
||||
<div className="pt-6 flex justify-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLoadMore}
|
||||
disabled={isLoadingMore}
|
||||
className="px-6 py-2.5 border border-gray-300 text-gray-700 text-xs font-semibold rounded-lg hover:bg-gray-50 transition-colors cursor-pointer disabled:opacity-60 inline-flex items-center gap-2"
|
||||
>
|
||||
{isLoadingMore && <Loader2 size={13} className="animate-spin" />}
|
||||
<span>{isLoadingMore ? 'Loading...' : 'Load More Reviews'}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 5. Submission Modal */}
|
||||
<ReviewSubmissionModal
|
||||
productId={productId}
|
||||
productName={productName}
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => setIsModalOpen(false)}
|
||||
onReviewSubmitted={handleReviewSubmitted}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<ProductTabsWrapperProps> = ({
|
||||
productId,
|
||||
productName,
|
||||
initialReviewsCount = 0,
|
||||
descriptionHtml,
|
||||
specsHtml,
|
||||
showSpecifications = true,
|
||||
}) => {
|
||||
const [activeTab, setActiveTab] = useState<TabId>('description');
|
||||
const [reviewsCount, setReviewsCount] = useState<number>(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<ProductTabsWrapperProps> = ({
|
|||
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<ProductTabsWrapperProps> = ({
|
|||
{specsHtml}
|
||||
</div>
|
||||
|
||||
{/* ── Reviews ── */}
|
||||
<div className={activeTab === 'reviews' ? 'block p-4 sm:p-6 md:p-8' : 'hidden'}>
|
||||
{productId ? (
|
||||
<ProductReviewsSection
|
||||
productId={productId}
|
||||
productName={productName || 'Product'}
|
||||
onReviewsCountChange={setReviewsCount}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-xs text-gray-400 py-6 text-center">Reviews unavailable</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
123
components/pdp/ReviewCard.tsx
Normal file
123
components/pdp/ReviewCard.tsx
Normal file
|
|
@ -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<string | null>(null);
|
||||
|
||||
return (
|
||||
<div className="py-6 border-b border-gray-100 last:border-b-0 space-y-3">
|
||||
{/* Header: Author & Verified Badge & Date */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-full bg-primary/10 text-primary font-bold text-sm flex items-center justify-center">
|
||||
{review.author_name ? review.author_name.charAt(0).toUpperCase() : 'U'}
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[14px] font-semibold text-gray-900">
|
||||
{review.author_name}
|
||||
</span>
|
||||
{review.verified_buyer && (
|
||||
<span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
|
||||
<CheckCircle size={11} className="text-emerald-600 fill-emerald-100" />
|
||||
Verified Purchase
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{review.review_date && (
|
||||
<span className="text-[12px] text-gray-400">
|
||||
Reviewed on {review.review_date}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stars */}
|
||||
<div className="flex items-center gap-0.5 text-amber-400">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Star
|
||||
key={i}
|
||||
size={14}
|
||||
className={i < review.rating ? 'fill-amber-400 text-amber-400' : 'text-gray-200'}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Review Title */}
|
||||
{review.title && (
|
||||
<h4 className="text-[14px] font-bold text-gray-900 leading-snug">
|
||||
{review.title}
|
||||
</h4>
|
||||
)}
|
||||
|
||||
{/* Review Body */}
|
||||
<p className="text-[13px] text-gray-700 leading-relaxed whitespace-pre-line">
|
||||
{review.comment}
|
||||
</p>
|
||||
|
||||
{/* Uploaded Customer Photos */}
|
||||
{review.images && review.images.length > 0 && (
|
||||
<div className="flex items-center gap-2.5 pt-1">
|
||||
{review.images.map((imgUrl, idx) => {
|
||||
const fullUrl = getImageUrl(imgUrl);
|
||||
return (
|
||||
<button
|
||||
key={idx}
|
||||
type="button"
|
||||
onClick={() => setSelectedImage(fullUrl)}
|
||||
className="relative w-16 h-16 rounded-md overflow-hidden border border-gray-200 hover:border-primary transition-all hover:scale-105 cursor-pointer"
|
||||
>
|
||||
<Image
|
||||
src={fullUrl}
|
||||
alt={`Customer photo ${idx + 1}`}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Admin Reply */}
|
||||
{review.admin_reply && (
|
||||
<div className="mt-3 p-3.5 bg-gray-50 border-l-3 border-primary rounded-r-md text-xs space-y-1">
|
||||
<div className="flex items-center gap-1.5 font-bold text-gray-900">
|
||||
<MessageSquareQuote size={14} className="text-primary" />
|
||||
<span>iFixKart Response</span>
|
||||
</div>
|
||||
<p className="text-gray-600 leading-relaxed">{review.admin_reply}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lightbox Modal */}
|
||||
{selectedImage && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"
|
||||
onClick={() => setSelectedImage(null)}
|
||||
>
|
||||
<div className="relative max-w-2xl max-h-[85vh] w-full bg-black rounded-lg overflow-hidden flex items-center justify-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedImage(null)}
|
||||
className="absolute top-3 right-3 z-10 p-2 text-white/80 hover:text-white bg-black/50 rounded-full"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
<img
|
||||
src={selectedImage}
|
||||
alt="Customer photo enlarged"
|
||||
className="max-h-[80vh] w-auto object-contain rounded-md"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
325
components/pdp/ReviewSubmissionModal.tsx
Normal file
325
components/pdp/ReviewSubmissionModal.tsx
Normal file
|
|
@ -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<number, string> = {
|
||||
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<number>(5);
|
||||
const [hoverRating, setHoverRating] = useState<number | null>(null);
|
||||
const [title, setTitle] = useState('');
|
||||
const [comment, setComment] = useState('');
|
||||
const [authorName, setAuthorName] = useState('');
|
||||
const [authorEmail, setAuthorEmail] = useState('');
|
||||
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
|
||||
const [filePreviews, setFilePreviews] = useState<string[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(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<HTMLInputElement>) => {
|
||||
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 (
|
||||
<div className="fixed inset-0 z-[120] flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs">
|
||||
<div className="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl overflow-hidden border border-gray-100 animate-in fade-in zoom-in-95 duration-200">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 bg-[#fafbfc]">
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-gray-900">Write a Review</h3>
|
||||
<p className="text-xs text-gray-500 truncate max-w-xs">{productName}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="p-1.5 text-gray-400 hover:text-gray-700 rounded-full hover:bg-gray-100 cursor-pointer"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Success Banner */}
|
||||
{isSuccess ? (
|
||||
<div className="p-8 text-center space-y-3">
|
||||
<CheckCircle2 size={48} className="mx-auto text-emerald-500 animate-bounce" />
|
||||
<h4 className="text-lg font-bold text-gray-900">Thank You!</h4>
|
||||
<p className="text-sm text-gray-600">
|
||||
Your review has been successfully submitted and verified.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
/* Form */
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
|
||||
{errorMsg && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-xs text-red-700 flex items-center gap-2">
|
||||
<AlertCircle size={15} className="shrink-0 text-red-500" />
|
||||
<span>{errorMsg}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Overall Rating */}
|
||||
<div className="space-y-1.5 text-center sm:text-left">
|
||||
<label className="block text-xs font-bold text-gray-700 uppercase tracking-wider">
|
||||
Overall Rating *
|
||||
</label>
|
||||
<div className="flex items-center gap-1.5 justify-center sm:justify-start">
|
||||
{[1, 2, 3, 4, 5].map((star) => (
|
||||
<button
|
||||
key={star}
|
||||
type="button"
|
||||
onClick={() => setRating(star)}
|
||||
onMouseEnter={() => setHoverRating(star)}
|
||||
onMouseLeave={() => setHoverRating(null)}
|
||||
className="p-1 text-gray-300 hover:scale-110 transition-transform cursor-pointer"
|
||||
>
|
||||
<Star
|
||||
size={24}
|
||||
className={
|
||||
star <= activeRating
|
||||
? 'fill-amber-400 text-amber-400'
|
||||
: 'text-gray-200'
|
||||
}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
<span className="text-xs font-semibold text-amber-700 ml-2">
|
||||
{RATING_DESCRIPTIONS[activeRating] || ''}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Review Title */}
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-gray-700 mb-1">
|
||||
Headline / Summary *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => 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
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Review Comment */}
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-gray-700 mb-1">
|
||||
Detailed Review *
|
||||
</label>
|
||||
<textarea
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
rows={4}
|
||||
placeholder="Share your experience: build quality, packaging, installation ease, and performance..."
|
||||
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
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Name and Email */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-gray-700 mb-1">
|
||||
Your Name *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={authorName}
|
||||
onChange={(e) => setAuthorName(e.target.value)}
|
||||
placeholder="e.g. Adithiyan"
|
||||
className="w-full px-3.5 py-2 border border-gray-300 rounded-lg text-sm text-gray-800 focus:outline-none focus:border-primary"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-gray-700 mb-1">
|
||||
Email (Used for Verified Buyer check)
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={authorEmail}
|
||||
onChange={(e) => setAuthorEmail(e.target.value)}
|
||||
placeholder="name@example.com"
|
||||
className="w-full px-3.5 py-2 border border-gray-300 rounded-lg text-sm text-gray-800 focus:outline-none focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Photos Upload */}
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-gray-700 mb-1">
|
||||
Attach Photos (Optional, up to 3)
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-2.5 pt-1">
|
||||
{filePreviews.map((previewUrl, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="relative w-16 h-16 rounded-lg overflow-hidden border border-gray-200 shadow-2xs"
|
||||
>
|
||||
<img src={previewUrl} alt="Preview" className="w-full h-full object-cover" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeFile(idx)}
|
||||
className="absolute top-1 right-1 p-0.5 bg-black/60 text-white rounded-full hover:bg-black"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{selectedFiles.length < 3 && (
|
||||
<label className="w-16 h-16 border-2 border-dashed border-gray-300 hover:border-primary rounded-lg flex flex-col items-center justify-center text-gray-400 hover:text-primary cursor-pointer transition-colors">
|
||||
<Upload size={16} />
|
||||
<span className="text-[10px] font-semibold mt-0.5">Upload</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer Buttons */}
|
||||
<div className="pt-3 border-t border-gray-100 flex items-center justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={isSubmitting}
|
||||
className="px-4 py-2 border border-gray-300 rounded-lg text-xs font-semibold text-gray-700 hover:bg-gray-50 cursor-pointer"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="px-6 py-2.5 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 shadow-sm inline-flex items-center gap-2 cursor-pointer disabled:opacity-60"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
<span>Submitting…</span>
|
||||
</>
|
||||
) : (
|
||||
<span>Submit Review</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
104
components/pdp/ReviewSummaryBreakdown.tsx
Normal file
104
components/pdp/ReviewSummaryBreakdown.tsx
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { Star, ShieldCheck, PenLine } from 'lucide-react';
|
||||
|
||||
interface ReviewSummaryBreakdownProps {
|
||||
averageRating: number;
|
||||
totalReviews: number;
|
||||
verifiedCount: number;
|
||||
starDistribution: Record<string, number>;
|
||||
onWriteReviewClick: () => void;
|
||||
}
|
||||
|
||||
export function ReviewSummaryBreakdown({
|
||||
averageRating,
|
||||
totalReviews,
|
||||
verifiedCount,
|
||||
starDistribution,
|
||||
onWriteReviewClick,
|
||||
}: ReviewSummaryBreakdownProps) {
|
||||
const starsList = [5, 4, 3, 2, 1];
|
||||
|
||||
return (
|
||||
<div className="bg-[#fafbfc] border border-gray-200/80 rounded-xl p-6 mb-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-12 gap-8 items-center">
|
||||
{/* Left: Big Score & Stars */}
|
||||
<div className="md:col-span-4 flex flex-col items-center md:items-start text-center md:text-left space-y-2 border-b md:border-b-0 md:border-r border-gray-200 pb-6 md:pb-0 md:pr-6">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-4xl font-extrabold text-gray-900">
|
||||
{averageRating > 0 ? averageRating.toFixed(1) : '0.0'}
|
||||
</span>
|
||||
<span className="text-gray-400 text-sm font-medium">/ 5.0</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 text-amber-400">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Star
|
||||
key={i}
|
||||
size={18}
|
||||
className={
|
||||
i < Math.round(averageRating)
|
||||
? 'fill-amber-400 text-amber-400'
|
||||
: 'text-gray-200'
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-500 font-medium">
|
||||
Based on {totalReviews} {totalReviews === 1 ? 'review' : 'customer reviews'}
|
||||
</p>
|
||||
|
||||
{verifiedCount > 0 && (
|
||||
<div className="inline-flex items-center gap-1.5 text-xs text-emerald-700 font-semibold bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200/60 mt-1">
|
||||
<ShieldCheck size={13} className="text-emerald-600" />
|
||||
<span>{verifiedCount} Verified Purchases</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="pt-2 w-full">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onWriteReviewClick}
|
||||
className="w-full py-2.5 px-4 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 transition-all shadow-xs inline-flex items-center justify-center gap-2 cursor-pointer"
|
||||
>
|
||||
<PenLine size={14} />
|
||||
Write a Review
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Star Distribution Progress Bars */}
|
||||
<div className="md:col-span-8 space-y-2.5">
|
||||
{starsList.map((stars) => {
|
||||
const count = starDistribution[String(stars)] || 0;
|
||||
const percent =
|
||||
totalReviews > 0 ? Math.round((count / totalReviews) * 100) : 0;
|
||||
|
||||
return (
|
||||
<div key={stars} className="flex items-center gap-3 text-xs">
|
||||
<span className="w-12 font-semibold text-gray-700 flex items-center gap-1 shrink-0">
|
||||
<span>{stars}</span>
|
||||
<Star size={11} className="fill-amber-400 text-amber-400" />
|
||||
</span>
|
||||
|
||||
<div className="flex-1 h-2.5 bg-gray-200 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-amber-400 rounded-full transition-all duration-500"
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-20 text-right text-gray-500 shrink-0 font-medium">
|
||||
<span>{percent}%</span>
|
||||
<span className="text-gray-400 text-[11px] ml-1.5">({count})</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
102
services/api/reviewService.ts
Normal file
102
services/api/reviewService.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { apiFetch, getBaseUrl } from './client';
|
||||
|
||||
export interface ProductReviewItem {
|
||||
review_id: string;
|
||||
product_id: string;
|
||||
author_name: string;
|
||||
rating: number;
|
||||
title: string;
|
||||
comment: string;
|
||||
verified_buyer: boolean;
|
||||
helpful_count: number;
|
||||
admin_reply?: string | null;
|
||||
review_date?: string | null;
|
||||
images: string[];
|
||||
}
|
||||
|
||||
export interface ProductReviewSummaryResponse {
|
||||
average_rating: number;
|
||||
total_reviews: number;
|
||||
star_distribution: Record<string, number>;
|
||||
verified_count: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
reviews: ProductReviewItem[];
|
||||
}
|
||||
|
||||
export interface ReviewCreatePayload {
|
||||
rating: number;
|
||||
title: string;
|
||||
comment: string;
|
||||
author_name: string;
|
||||
author_email?: string;
|
||||
image_urls?: string[];
|
||||
}
|
||||
|
||||
export const reviewService = {
|
||||
async getProductReviews(
|
||||
productId: string,
|
||||
page: number = 1,
|
||||
limit: number = 10,
|
||||
sort: string = 'newest'
|
||||
): Promise<ProductReviewSummaryResponse> {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
limit: String(limit),
|
||||
sort,
|
||||
});
|
||||
try {
|
||||
return await apiFetch<ProductReviewSummaryResponse>(
|
||||
`/api/v1/storefront/reviews/${productId}?${params.toString()}`
|
||||
);
|
||||
} catch {
|
||||
// Graceful fallback if no reviews yet
|
||||
return {
|
||||
average_rating: 0,
|
||||
total_reviews: 0,
|
||||
star_distribution: { '5': 0, '4': 0, '3': 0, '2': 0, '1': 0 },
|
||||
verified_count: 0,
|
||||
page: 1,
|
||||
limit,
|
||||
reviews: [],
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
async submitReview(
|
||||
productId: string,
|
||||
payload: ReviewCreatePayload
|
||||
): Promise<ProductReviewItem> {
|
||||
return await apiFetch<ProductReviewItem>(
|
||||
`/api/v1/storefront/reviews/${productId}`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
async uploadReviewImage(file: File, productId: string): Promise<string> {
|
||||
const baseUrl = getBaseUrl();
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('entity_type', 'review');
|
||||
formData.append('entity_id', productId);
|
||||
|
||||
const res = await fetch(
|
||||
`${baseUrl}/api/v1/files/upload?entity_type=review&entity_id=${encodeURIComponent(productId)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ detail: 'Upload failed' }));
|
||||
throw new Error(err.detail || 'Failed to upload review image');
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
return data.file_url || data.url || '';
|
||||
},
|
||||
};
|
||||
Loading…
Reference in a new issue