208 lines
7.4 KiB
TypeScript
208 lines
7.4 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useRef, useState } from 'react';
|
|
import { Loader2, Plus, Search } from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
import { storefrontService } from '@/services/api/storefrontService';
|
|
import { ProductResponse } from '@/services/api/catalogService';
|
|
import { mapProductCardToProductResponse } from '@/utils/productMapper';
|
|
import { getCatalogPriceInfo, getImageUrl } from '@/lib/utils';
|
|
import { isSameCompareProduct, notifyCompareResult } from '@/lib/compare';
|
|
import {
|
|
compareKindLabel,
|
|
detectProductKind,
|
|
formatComparePrice,
|
|
lockedCompareKind,
|
|
} from '@/lib/compareSpecs';
|
|
import { useCartStore } from '@/store/cartStore';
|
|
|
|
interface CompareProductPickerProps {
|
|
variant?: 'hero' | 'icon' | 'button';
|
|
replaceProductId?: string;
|
|
defaultOpen?: boolean;
|
|
onAdded?: () => void;
|
|
}
|
|
|
|
export function CompareProductPicker({
|
|
variant = 'icon',
|
|
replaceProductId,
|
|
defaultOpen = false,
|
|
onAdded,
|
|
}: CompareProductPickerProps) {
|
|
const compareList = useCartStore((s) => s.compareList);
|
|
const addToCompare = useCartStore((s) => s.addToCompare);
|
|
const replaceCompareProduct = useCartStore((s) => s.replaceCompareProduct);
|
|
const [query, setQuery] = useState('');
|
|
const [results, setResults] = useState<ProductResponse[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [open, setOpen] = useState(variant === 'hero' || defaultOpen);
|
|
|
|
useEffect(() => {
|
|
if (defaultOpen) setOpen(true);
|
|
}, [defaultOpen, replaceProductId]);
|
|
const rootRef = useRef<HTMLDivElement>(null);
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
const lockedKind = lockedCompareKind(compareList, replaceProductId);
|
|
const kindLabel = lockedKind ? compareKindLabel(lockedKind) : 'products';
|
|
|
|
useEffect(() => {
|
|
if (open) inputRef.current?.focus();
|
|
}, [open]);
|
|
|
|
useEffect(() => {
|
|
const q = query.trim();
|
|
if (q.length < 2) {
|
|
setResults([]);
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
|
|
setLoading(true);
|
|
const timer = window.setTimeout(async () => {
|
|
try {
|
|
const data = await storefrontService.getLiveSearch(q);
|
|
const products = (data.products || [])
|
|
.map((p) => mapProductCardToProductResponse(p as unknown as Record<string, unknown>))
|
|
.filter((p) => {
|
|
if (!p.product_id) return false;
|
|
const alreadyListed = compareList.some(
|
|
(c) =>
|
|
isSameCompareProduct(c, p) &&
|
|
(!replaceProductId || !isSameCompareProduct(c, replaceProductId))
|
|
);
|
|
if (alreadyListed) return false;
|
|
if (lockedKind && detectProductKind(p) !== lockedKind) return false;
|
|
return true;
|
|
})
|
|
.slice(0, 8);
|
|
setResults(products);
|
|
} catch {
|
|
setResults([]);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, 280);
|
|
|
|
return () => window.clearTimeout(timer);
|
|
}, [query, compareList, replaceProductId, lockedKind]);
|
|
|
|
useEffect(() => {
|
|
if (variant === 'hero') return;
|
|
const onPointer = (event: MouseEvent) => {
|
|
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointer);
|
|
return () => document.removeEventListener('mousedown', onPointer);
|
|
}, [variant]);
|
|
|
|
const handleSelect = (product: ProductResponse) => {
|
|
const result = replaceProductId
|
|
? replaceCompareProduct(replaceProductId, product)
|
|
: addToCompare(product);
|
|
if (!notifyCompareResult(result)) return;
|
|
if (result.ok && !result.already) {
|
|
toast.success(replaceProductId ? 'Product replaced' : 'Added to comparison');
|
|
}
|
|
setQuery('');
|
|
setResults([]);
|
|
if (variant === 'icon') setOpen(false);
|
|
onAdded?.();
|
|
};
|
|
|
|
const searchField = (
|
|
<div className="relative w-full">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
|
|
<input
|
|
ref={inputRef}
|
|
type="search"
|
|
value={query}
|
|
onChange={(e) => setQuery(e.target.value)}
|
|
placeholder={lockedKind ? `Search ${kindLabel}` : 'Search product name'}
|
|
className="w-full h-10 pl-9 pr-9 rounded-lg border border-gray-200 bg-white text-[13px] text-gray-800 placeholder:text-gray-400 focus:outline-none focus:border-primary"
|
|
/>
|
|
{loading ? (
|
|
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 animate-spin" />
|
|
) : null}
|
|
</div>
|
|
);
|
|
|
|
const resultList =
|
|
query.trim().length >= 2 ? (
|
|
<ul className="mt-2 max-h-72 overflow-y-auto">
|
|
{loading && results.length === 0 ? (
|
|
<li className="px-2 py-3 text-[13px] text-gray-400">Searching…</li>
|
|
) : results.length === 0 ? (
|
|
<li className="px-2 py-3 text-[13px] text-gray-400">
|
|
{lockedKind ? `No matching ${kindLabel}` : 'No matching products'}
|
|
</li>
|
|
) : (
|
|
results.map((product) => {
|
|
const img = getImageUrl(product.images?.[0]?.image_url);
|
|
const price = getCatalogPriceInfo(product).price;
|
|
return (
|
|
<li key={product.product_id}>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleSelect(product)}
|
|
className="w-full flex items-center gap-3 px-2 py-2 rounded-lg text-left hover:bg-[#f5f8fc] cursor-pointer"
|
|
>
|
|
<div className="w-11 h-11 shrink-0 rounded-md border border-gray-100 bg-white overflow-hidden">
|
|
{img ? (
|
|
// eslint-disable-next-line @next/next/no-img-element
|
|
<img src={img} alt="" className="w-full h-full object-contain p-1" />
|
|
) : (
|
|
<div className="w-full h-full bg-gray-50" />
|
|
)}
|
|
</div>
|
|
<div className="min-w-0">
|
|
<p className="text-[13px] font-medium text-[#212121] line-clamp-2">{product.name}</p>
|
|
{price ? (
|
|
<p className="text-[12px] font-bold text-[#212121] mt-0.5">
|
|
{formatComparePrice(price)}
|
|
</p>
|
|
) : null}
|
|
</div>
|
|
</button>
|
|
</li>
|
|
);
|
|
})
|
|
)}
|
|
</ul>
|
|
) : null;
|
|
|
|
if (variant === 'hero') {
|
|
return (
|
|
<div ref={rootRef} className="w-full max-w-lg mx-auto">
|
|
{searchField}
|
|
{resultList}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div ref={rootRef} className="relative">
|
|
<button
|
|
type="button"
|
|
onClick={() => setOpen((v) => !v)}
|
|
aria-label="Add product to compare"
|
|
className={
|
|
variant === 'button'
|
|
? 'h-9 px-4 rounded-lg bg-primary text-white text-[13px] font-semibold inline-flex items-center gap-1.5 hover:brightness-95 cursor-pointer'
|
|
: 'w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center shadow-sm hover:brightness-95 cursor-pointer'
|
|
}
|
|
>
|
|
<Plus className="w-4 h-4" />
|
|
{variant === 'button' ? 'Add Product' : null}
|
|
</button>
|
|
{open ? (
|
|
<div className="absolute right-0 top-full mt-2 w-[340px] bg-white border border-gray-200 rounded-xl shadow-[0_16px_40px_rgba(16,24,40,0.16)] p-3 z-[80]">
|
|
<p className="text-[13px] font-semibold text-[#212121] mb-2">
|
|
{replaceProductId ? 'Replace product' : 'Add a product'}
|
|
</p>
|
|
{searchField}
|
|
{resultList}
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|