ifixkart-storefront/app/compare/page.tsx

244 lines
9.9 KiB
TypeScript

/**
* @page Compare Page (`app/compare/page.tsx`)
* @purpose Product specification comparison matrix comparing up to 4 selected products.
*/
'use client';
import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useCartStore } from '@/store/cartStore';
import { catalogService, ProductResponse } from '@/services/api/catalogService';
import { mapProductCardToProductResponse } from '@/utils/productMapper';
import { formatCatalogPriceLabel, getImageUrl } from '@/lib/utils';
import { ArrowLeftRight, Trash2 } from 'lucide-react';
import { AnnouncementBar } from '@/layout/AnnouncementBar';
import { Header } from '@/layout/Header';
import { Navbar } from '@/layout/Navbar';
import { Footer } from '@/layout/Footer';
import { StickyHeaderSpacer } from '@/components/StickyHeaderSpacer';
import { FloatingButtons } from '@/components/FloatingButtons';
import { CompareProductPicker } from '@/components/compare/CompareProductPicker';
import { COMPARE_LIMIT } from '@/lib/compare';
import {
buildTypeCompareRows,
sameTypeCompareList,
type ProductSpecItem,
} from '@/lib/compareSpecs';
export default function ComparePage() {
const compareList = useCartStore((state) => state.compareList) || [];
const toggleCompare = useCartStore((state) => state.toggleCompare);
const addToCart = useCartStore((state) => state.addToCart);
const hasHydrated = useCartStore((state) => state._hasHydrated);
const [ready, setReady] = useState(false);
const [enriched, setEnriched] = useState<Record<string, ProductResponse>>({});
const [specMap, setSpecMap] = useState<Record<string, ProductSpecItem[]>>({});
useEffect(() => {
if (hasHydrated) {
const list = useCartStore.getState().compareList;
const pruned = sameTypeCompareList(list);
if (pruned.length !== list.length) {
useCartStore.setState({ compareList: pruned });
}
setReady(true);
return;
}
const t = window.setTimeout(() => setReady(true), 250);
return () => window.clearTimeout(t);
}, [hasHydrated]);
const productKey = compareList.map((p) => p.product_id).join('|');
useEffect(() => {
let cancelled = false;
if (compareList.length === 0) {
setEnriched({});
setSpecMap({});
return;
}
Promise.all(
compareList.map(async (product) => {
if (!product.slug) return null;
try {
const data = await catalogService.getProductDetail(product.slug);
const raw = data?.product || data;
const full = mapProductCardToProductResponse(raw);
const specs = Array.isArray(data?.specifications)
? data.specifications
.map((item: { label?: string; value?: string }) => ({
label: String(item?.label || '').trim(),
value: String(item?.value || '').trim(),
}))
.filter((item: ProductSpecItem) => item.label && item.value)
: [];
return {
id: product.product_id,
product: {
...product,
...full,
product_id: product.product_id,
slug: product.slug || full.slug,
brand_name: full.brand_name || product.brand_name,
images: full.images?.length ? full.images : product.images,
variants: full.variants?.length ? full.variants : product.variants,
} as ProductResponse,
specs,
};
} catch {
return null;
}
})
).then((rows) => {
if (cancelled) return;
const nextProducts: Record<string, ProductResponse> = {};
const nextSpecs: Record<string, ProductSpecItem[]> = {};
rows.forEach((row) => {
if (!row) return;
nextProducts[row.id] = row.product;
nextSpecs[row.id] = row.specs;
});
setEnriched(nextProducts);
setSpecMap(nextSpecs);
});
return () => {
cancelled = true;
};
}, [productKey]);
const products = useMemo(
() => compareList.map((p) => enriched[p.product_id] || p),
[compareList, enriched]
);
const specRows = useMemo(
() => buildTypeCompareRows(products, specMap),
[products, specMap]
);
return (
<div className="min-h-screen bg-white text-[#1E293B] flex flex-col font-sans">
<AnnouncementBar />
<Header />
<StickyHeaderSpacer />
<Navbar />
<main className="flex-grow w-full bg-[#f8f9fb] py-8">
<div className="max-w-7xl mx-auto px-4">
{ready && compareList.length < COMPARE_LIMIT ? (
<div className="flex justify-end mb-4">
<CompareProductPicker variant="button" />
</div>
) : null}
{!ready ? (
<div className="bg-white border border-gray-200 rounded-xl p-8 animate-pulse h-48" />
) : compareList.length === 0 ? (
<div className="bg-white border border-gray-200 rounded-xl p-12 text-center max-w-lg mx-auto">
<ArrowLeftRight className="w-16 h-16 text-gray-300 mx-auto mb-4 stroke-1" />
<h2 className="text-lg font-bold text-gray-900">No Products Selected for Comparison</h2>
<p className="text-xs text-gray-400 mt-1 mb-6">
Click the compare icon on product cards to compare specifications side-by-side.
</p>
<Link
href="/shop"
className="bg-primary text-white text-xs font-bold px-6 py-3 rounded-lg hover:brightness-95 transition-colors inline-block"
>
Browse Catalog
</Link>
</div>
) : (
<div className="bg-white border border-gray-200 rounded-xl overflow-x-auto">
<table className="w-full text-left text-xs">
<thead>
<tr className="bg-gray-50 border-b border-gray-200 text-gray-900">
<th className="p-4 w-44 font-extrabold">Feature</th>
{products.map((product) => {
const img = getImageUrl(product.images?.[0]?.image_url);
return (
<th key={product.product_id} className="p-4 min-w-[200px]">
<div className="flex flex-col items-center text-center">
<div className="relative w-20 h-20 rounded-lg border border-gray-200 overflow-hidden bg-gray-50 mb-2">
{img ? (
<Image src={img} alt={product.name} fill className="object-contain p-1" unoptimized />
) : null}
</div>
<Link
href={`/products/${product.slug}`}
className="font-extrabold text-gray-900 line-clamp-2 hover:text-primary"
>
{product.name}
</Link>
<span className="text-xs font-bold text-gray-900 mt-1">
{formatCatalogPriceLabel(product)}
</span>
<button
type="button"
onClick={() => toggleCompare(product)}
className="text-[10px] text-red-500 font-bold hover:underline mt-2 flex items-center gap-1 cursor-pointer"
>
<Trash2 className="w-3 h-3" /> Remove
</button>
</div>
</th>
);
})}
</tr>
</thead>
<tbody className="divide-y divide-gray-100 text-gray-800">
<tr>
<td className="p-4 font-bold bg-gray-50">Price</td>
{products.map((p) => (
<td key={p.product_id} className="p-4 text-center font-extrabold">
{formatCatalogPriceLabel(p)}
</td>
))}
</tr>
{specRows.map((row) => (
<tr key={row.label}>
<td className="p-4 font-bold bg-gray-50">{row.label}</td>
{row.values.map((value, index) => (
<td key={`${products[index]?.product_id}-${row.label}`} className="p-4 text-center text-gray-700">
{value.text}
</td>
))}
</tr>
))}
<tr>
<td className="p-4 font-bold bg-gray-50">Rating</td>
{products.map((p) => (
<td key={p.product_id} className="p-4 text-center font-bold text-amber-500">
{p.rating || 4.9} / 5.0
</td>
))}
</tr>
<tr>
<td className="p-4 font-bold bg-gray-50">Action</td>
{products.map((p) => (
<td key={p.product_id} className="p-4 text-center">
<button
type="button"
onClick={() => {
const variant = p.variants?.[0];
if (variant) void addToCart(p, variant, 1);
}}
className="bg-primary hover:brightness-95 text-white text-[11px] font-bold px-3 py-1.5 rounded-md transition-colors cursor-pointer"
>
Add to Cart
</button>
</td>
))}
</tr>
</tbody>
</table>
</div>
)}
</div>
</main>
<Footer />
<FloatingButtons />
</div>
);
}