ifixkart-storefront/sections/CategoriesSection.tsx

414 lines
16 KiB
TypeScript

'use client';
import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { ArrowRight, Layers, ChevronLeft, ChevronRight } from 'lucide-react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, A11y } from 'swiper/modules';
import type { Swiper as SwiperType } from 'swiper';
import { catalogService, CategoryResponse } from '../services/api/catalogService';
import { getImageUrl } from '../lib/utils';
import { getSectionTitle } from '../lib/homepageDefaults';
import { Skeleton } from '../components/ui/Skeleton';
import 'swiper/css';
import 'swiper/css/navigation';
interface CategoriesSectionProps {
config?: any;
initialCategories?: CategoryResponse[];
}
/** Category tile image with official URL → product thumb → icon fallback */
function CategoryThumb({
name,
primarySrc,
fallbackSrc,
}: {
name: string;
primarySrc: string;
fallbackSrc?: string;
}) {
const [src, setSrc] = useState(primarySrc || fallbackSrc || '');
const [stage, setStage] = useState<'primary' | 'fallback' | 'empty'>(() =>
primarySrc ? 'primary' : fallbackSrc ? 'fallback' : 'empty'
);
useEffect(() => {
if (primarySrc) {
setSrc(primarySrc);
setStage('primary');
} else if (fallbackSrc) {
setSrc(fallbackSrc);
setStage('fallback');
} else {
setSrc('');
setStage('empty');
}
}, [primarySrc, fallbackSrc]);
const handleError = () => {
if (stage === 'primary' && fallbackSrc) {
setSrc(fallbackSrc);
setStage('fallback');
return;
}
setSrc('');
setStage('empty');
};
if (!src || stage === 'empty') {
return <Layers className="w-10 h-10 text-gray-300 stroke-[1.5]" />;
}
return (
<img
src={src}
alt={name}
loading="lazy"
onError={handleError}
className="max-h-full max-w-full object-contain transition-transform duration-300 group-hover:scale-[1.04]"
/>
);
}
export const CategoriesSection: React.FC<CategoriesSectionProps> = ({
config,
initialCategories,
}) => {
const [categories, setCategories] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [canSlide, setCanSlide] = useState(false);
const [productThumbs, setProductThumbs] = useState<Record<string, string>>({});
const [activeParentCat, setActiveParentCat] = useState<any | null>(null);
const swiperRef = useRef<SwiperType | null>(null);
const rootCategories = React.useMemo(() => {
const roots = categories.filter((c) => !c.parent_category_id);
return roots.length > 0 ? roots : categories;
}, [categories]);
useEffect(() => {
const sortCats = (cats: any[]) =>
[...cats].sort((a, b) => {
const orderA = parseInt(a.sort_order || '0', 10);
const orderB = parseInt(b.sort_order || '0', 10);
return orderA - orderB;
});
if (initialCategories && initialCategories.length > 0) {
setCategories(sortCats(initialCategories));
setLoading(false);
return;
}
setLoading(true);
catalogService
.getCategories()
.then((res) => {
setLoading(false);
const rawCats =
config?.metadata_json?.categories || config?.metadata?.categories;
if (res && res.length > 0) {
setCategories(sortCats(res));
} else if (rawCats && rawCats.length > 0) {
setCategories(sortCats(rawCats));
} else {
setCategories([]);
}
})
.catch((err) => {
console.error('Failed to load categories:', err);
setLoading(false);
const rawCats =
config?.metadata_json?.categories || config?.metadata?.categories;
if (rawCats) {
setCategories(sortCats(rawCats));
} else {
setError(true);
}
});
}, [config, initialCategories]);
// Build category_id → first product thumbnail map (used when category image is missing/broken)
useEffect(() => {
if (categories.length === 0) return;
let cancelled = false;
catalogService
.getProductsPaginated({ limit: 48 })
.then((res) => {
if (cancelled) return;
const map: Record<string, string> = {};
for (const p of res.products || []) {
const cid = p.category_id;
const thumb = getImageUrl(p.thumbnail_url);
if (cid && thumb && !map[cid]) {
map[cid] = thumb;
}
}
setProductThumbs(map);
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [categories]);
const title = getSectionTitle(config, 'featured_categories');
const syncOverflow = (swiper: SwiperType) => {
if (!swiper) return;
setCanSlide(!swiper.isLocked && categories.length > 0);
};
useEffect(() => {
const swiper = swiperRef.current;
if (!swiper) return;
setTimeout(() => {
if (
swiper.params &&
swiper.params.navigation &&
typeof swiper.params.navigation !== 'boolean'
) {
swiper.params.navigation.prevEl = '.cat-swiper-prev';
swiper.params.navigation.nextEl = '.cat-swiper-next';
}
if (swiper.navigation) {
try {
swiper.navigation.destroy();
swiper.navigation.init();
swiper.navigation.update();
} catch (e) {}
}
syncOverflow(swiper);
}, 0);
}, [categories.length]);
return (
<section className="py-8 bg-white font-sans">
<div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-[1400px]">
<div className="flex items-center justify-between gap-4 pb-3.5 mb-6 border-b border-[#e5e5e5]">
<h2 className="text-[20px] md:text-[22px] font-bold text-[#222] tracking-tight">
{title}
</h2>
<Link
href="/shop"
className="text-[13px] text-[#333] hover:text-primary transition-colors flex items-center gap-1.5 shrink-0"
>
View All
<ArrowRight size={14} strokeWidth={2} />
</Link>
</div>
{loading ? (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4 md:gap-5">
{[1, 2, 3, 4, 5, 6].map((i) => (
<div key={i} className="flex flex-col items-center gap-2">
<Skeleton className="w-full aspect-square rounded-xl" />
<Skeleton className="h-4 w-2/3" />
<Skeleton className="h-3 w-1/3" />
</div>
))}
</div>
) : error || categories.length === 0 ? (
<div className="bg-[#F8F9FB] rounded-xl p-8 text-center flex flex-col items-center justify-center">
<Layers className="w-8 h-8 text-gray-400 mb-2 stroke-[1.5]" />
<h3 className="text-sm font-bold text-gray-800">No Categories Found</h3>
<p className="text-xs text-gray-500 mt-1">
Categories added in the catalog will appear here.
</p>
</div>
) : (
<div className="relative group/cats px-1">
<button
type="button"
aria-label="Previous categories"
className={`cat-swiper-prev absolute left-0 top-[22%] z-20 -translate-x-1/2 w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center shadow-md transition-opacity duration-200 hover:brightness-95 ${
canSlide
? 'opacity-0 pointer-events-none group-hover/cats:opacity-100 group-hover/cats:pointer-events-auto'
: 'opacity-0 pointer-events-none invisible'
}`}
>
<ChevronLeft size={20} strokeWidth={2.5} />
</button>
<button
type="button"
aria-label="Next categories"
className={`cat-swiper-next absolute right-0 top-[22%] z-20 translate-x-1/2 w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center shadow-md transition-opacity duration-200 hover:brightness-95 ${
canSlide
? 'opacity-0 pointer-events-none group-hover/cats:opacity-100 group-hover/cats:pointer-events-auto'
: 'opacity-0 pointer-events-none invisible'
}`}
>
<ChevronRight size={20} strokeWidth={2.5} />
</button>
<Swiper
modules={[Navigation, A11y]}
onSwiper={(swiper) => {
swiperRef.current = swiper;
setTimeout(() => {
if (
swiper &&
swiper.params &&
swiper.params.navigation &&
typeof swiper.params.navigation !== 'boolean'
) {
swiper.params.navigation.prevEl = '.cat-swiper-prev';
swiper.params.navigation.nextEl = '.cat-swiper-next';
}
if (swiper?.navigation) {
try {
swiper.navigation.destroy();
swiper.navigation.init();
swiper.navigation.update();
} catch (e) {}
}
syncOverflow(swiper);
}, 0);
}}
onResize={syncOverflow}
onBreakpoint={syncOverflow}
onLock={() => setCanSlide(false)}
onUnlock={() => setCanSlide(true)}
navigation={{
prevEl: '.cat-swiper-prev',
nextEl: '.cat-swiper-next',
}}
watchOverflow
spaceBetween={18}
slidesPerView={2}
breakpoints={{
480: { slidesPerView: 3, spaceBetween: 18 },
768: { slidesPerView: 4, spaceBetween: 20 },
1024: { slidesPerView: 5, spaceBetween: 22 },
1280: { slidesPerView: 6, spaceBetween: 24 },
}}
>
{rootCategories.map((cat) => {
const rawCatImg = cat.image_url || cat.image || cat.icon_url;
const primarySrc = rawCatImg ? getImageUrl(rawCatImg) : '';
const fallbackSrc =
productThumbs[cat.category_id] ||
productThumbs[cat.id] ||
'';
const count =
cat.product_count !== undefined && cat.product_count !== null
? Number(cat.product_count)
: null;
const hasSubs = cat.sub_categories && cat.sub_categories.length > 0;
return (
<SwiperSlide key={cat.category_id || cat.id || cat.slug}>
<div
onClick={(e) => {
if (hasSubs) {
e.preventDefault();
setActiveParentCat(cat);
}
}}
className="cursor-pointer"
>
<Link
href={hasSubs ? '#' : (cat.link || `/shop?category=${cat.slug}`)}
onClick={(e) => {
if (hasSubs) {
e.preventDefault();
setActiveParentCat(cat);
}
}}
className="flex flex-col items-center text-center group"
>
<div className="w-full aspect-square bg-[#F5F5F5] rounded-xl flex items-center justify-center p-5 md:p-6 overflow-hidden transition-colors duration-200 group-hover:bg-[#ececec] relative">
<CategoryThumb
name={cat.name}
primarySrc={primarySrc}
fallbackSrc={fallbackSrc}
/>
{hasSubs && (
<span className="absolute bottom-2 right-2 bg-white/90 text-primary text-[10px] font-bold px-1.5 py-0.5 rounded shadow-xs">
{cat.sub_categories.length} sub
</span>
)}
</div>
<h3 className="text-[14px] font-bold text-[#333] mt-3 leading-snug group-hover:text-primary transition-colors">
{cat.name}
</h3>
<span className="text-[12px] text-[#888] mt-0.5">
{count !== null ? `${count} Products` : 'Shop now'}
</span>
</Link>
</div>
</SwiperSlide>
);
})}
</Swiper>
</div>
)}
{/* Sub-Category Drilldown Modal */}
{activeParentCat && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs animate-in fade-in duration-200">
<div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl relative border border-gray-100 max-h-[85vh] flex flex-col">
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
<div>
<h3 className="text-base font-bold text-gray-900">{activeParentCat.name}</h3>
<p className="text-xs text-gray-500 mt-0.5">
Select a sub-category to view products ({activeParentCat.product_count || 0} total items)
</p>
</div>
<button
type="button"
onClick={() => setActiveParentCat(null)}
className="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-500 hover:text-gray-800 transition-colors cursor-pointer text-sm font-bold"
>
✕
</button>
</div>
<div className="py-4 space-y-2 overflow-y-auto flex-1">
{(activeParentCat.sub_categories || []).map((sub: any) => (
<Link
key={sub.category_id || sub.slug}
href={`/products?category=${sub.slug}`}
onClick={() => setActiveParentCat(null)}
className="flex items-center justify-between p-3 rounded-xl border border-gray-100 hover:border-primary/40 hover:bg-primary/5 transition-all group"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-white transition-colors">
<Layers className="w-4 h-4" />
</div>
<div>
<p className="text-[13px] font-semibold text-gray-800 group-hover:text-primary transition-colors">
{sub.name}
</p>
<p className="text-[11px] text-gray-400">
{sub.product_count !== undefined ? `${sub.product_count} Products` : 'Browse'}
</p>
</div>
</div>
<ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-primary group-hover:translate-x-0.5 transition-all" />
</Link>
))}
</div>
<div className="pt-3 border-t border-gray-100 flex items-center justify-between gap-3">
<Link
href={`/shop?category=${activeParentCat.slug}`}
onClick={() => setActiveParentCat(null)}
className="w-full text-center py-2.5 px-4 bg-primary text-white text-xs font-bold rounded-xl hover:brightness-95 transition-all shadow-sm"
>
View All {activeParentCat.name} ({activeParentCat.product_count || 0})
</Link>
</div>
</div>
</div>
)}
</div>
</section>
);
};