From 5424420accae4f2147fd583f1573aefa47678bba Mon Sep 17 00:00:00 2001 From: iFixKart Dev Date: Mon, 16 Nov 2026 14:59:16 +0530 Subject: [PATCH] feat(storefront): update PDP interactive grid, dynamic sitemap, catalog filters, and navigation links --- app/account/page.tsx | 2 +- app/layout.tsx | 16 ++- app/products/[slug]/page.tsx | 113 ++++++++++++++++++-- app/sitemap.ts | 71 ++++++++++++ components/FloatingButtons.tsx | 59 ++++++++-- components/MobileDrawer.tsx | 26 +++-- components/QuickViewModal.tsx | 2 +- components/TopDealsMegaMenu.tsx | 31 ++++-- components/WishlistModal.tsx | 2 +- components/auth/GoogleAuthModal.tsx | 65 ++++++++--- components/catalog/ParentFeatureCatalog.tsx | 18 ++-- components/catalog/StandardCatalog.tsx | 29 +++-- components/compare/CompareBar.tsx | 5 +- components/pdp/ProductInteractiveGrid.tsx | 69 ++++++++++-- components/store/LiveSearch.tsx | 73 ++++++++----- components/store/ProductCard.tsx | 5 +- layout/Header.tsx | 6 +- layout/HeaderActions.tsx | 6 +- next.config.ts | 2 +- services/api/catalogService.ts | 10 ++ services/api/storefrontService.ts | 6 +- styles/mobile-overrides.css | 11 ++ utils/productMapper.ts | 8 +- 23 files changed, 516 insertions(+), 119 deletions(-) create mode 100644 app/sitemap.ts diff --git a/app/account/page.tsx b/app/account/page.tsx index e0570d6..cff403d 100644 --- a/app/account/page.tsx +++ b/app/account/page.tsx @@ -1106,7 +1106,7 @@ function AccountDashboardPage() { {addressModalOpen && (
; + searchParams: Promise<{ variant?: string }>; +} + +const SITE_URL = 'https://ifixkart.trionixsolution.com'; + +const NON_DISPLAY_ATTR_CODES = new Set([ + 'sku', + 'barcode', + 'media_key', + 'parent_media_key', + 'cost_price', + 'compare_price', + 'warranty_months', + 'country_of_origin', +]); + +function resolveVariantLabel(variant: any): string { + const vals: string[] = []; + (variant?.attributes || []).forEach((attr: any) => { + const code = String(attr.attribute_code || '').trim().toLowerCase(); + if (NON_DISPLAY_ATTR_CODES.has(code) || code.startsWith('parent_')) return; + const value = String(attr.attribute_value || '').trim(); + if (value && !vals.includes(value)) vals.push(value); + }); + return vals.join(' '); +} + +function pickVariant(product: any, variantKey?: string) { + const variants = product?.variants || []; + if (variantKey) { + const decoded = decodeURIComponent(variantKey); + const match = variants.find( + (v: any) => v.sku === decoded || String(v.variant_id) === decoded + ); + if (match) return match; + } + return variants[0] || null; +} + +function buildVariantCanonical(slug: string, matchedVariant: any, variantKey?: string) { + if (variantKey && matchedVariant?.sku) { + return `/products/${slug}?variant=${encodeURIComponent(matchedVariant.sku)}`; + } + return `/products/${slug}`; +} + +export async function generateMetadata({ params, searchParams }: ProductDetailPageProps): Promise { + const { slug } = await params; + const { variant: variantKey } = await searchParams; + if (!slug) return {}; + + let product: any = null; + try { + const data = await catalogServerService.getProductDetail(slug); + product = data?.product; + } catch (err) { + console.error('Failed to build product metadata on server:', err); + return {}; + } + if (!product) return {}; + + const matchedVariant = pickVariant(product, variantKey); + const variantSuffix = resolveVariantLabel(matchedVariant); + const displayTitle = variantSuffix ? `${product.name} (${variantSuffix})` : product.name; + const variantImage = matchedVariant?.images?.[0]?.image_url || product.images?.[0]?.image_url; + + return { + title: `${displayTitle} | iFixKart`, + description: + product.seo_description || + `Buy ${displayTitle} with fast shipping and certified warranty at iFixKart.`, + alternates: { + canonical: buildVariantCanonical(slug, matchedVariant, variantKey), + }, + openGraph: { + title: `${displayTitle} | iFixKart`, + description: + product.seo_description || `Buy ${displayTitle} with certified warranty at iFixKart.`, + type: 'website', + images: variantImage ? [{ url: getImageUrl(variantImage) }] : undefined, + }, + }; } const HIDDEN_SPEC_KEYS = [ @@ -227,8 +310,9 @@ function groupSpecs(specifications: any[], product: any) { return groups; } -export default async function ProductDetailPage({ params }: ProductDetailPageProps) { +export default async function ProductDetailPage({ params, searchParams }: ProductDetailPageProps) { const { slug } = await params; + const { variant: variantKey } = await searchParams; if (!slug) { return notFound(); @@ -390,30 +474,38 @@ export default async function ProductDetailPage({ params }: ProductDetailPagePro ); - const primaryVariant = product.variants?.[0]; - const primaryImage = product.images?.[0]?.image_url || '/images/placeholder-product.webp'; + const matchedVariant = pickVariant(product, variantKey); + const activeVariant = matchedVariant || product.variants?.[0] || null; + const variantSuffix = resolveVariantLabel(activeVariant); + const displayTitle = variantSuffix ? `${product.name} (${variantSuffix})` : product.name; + const primaryImage = activeVariant?.images?.[0]?.image_url || product.images?.[0]?.image_url || '/images/placeholder-product.webp'; const resolvedImageUrl = getImageUrl(primaryImage); + const variantOfferUrl = activeVariant?.sku + ? `${SITE_URL}/products/${product.slug}?variant=${encodeURIComponent(activeVariant.sku)}` + : `${SITE_URL}/products/${product.slug}`; const jsonLd = { '@context': 'https://schema.org/', '@type': 'Product', - name: product.name, + name: displayTitle, image: [resolvedImageUrl], - description: product.seo_description || product.description || `${product.name} with certified warranty at iFixKart.`, - sku: primaryVariant?.sku || String(product.product_id), - mpn: primaryVariant?.barcode || primaryVariant?.sku || String(product.product_id), + description: product.seo_description || product.description || `${displayTitle} with certified warranty at iFixKart.`, + sku: activeVariant?.sku || String(product.product_id), + mpn: activeVariant?.barcode || activeVariant?.sku || String(product.product_id), + // Google Merchant Center: groups all color/spec swatches under one parent family + itemGroupId: String(product.product_id), brand: { '@type': 'Brand', name: product.brand?.name || 'iFixKart', }, offers: { '@type': 'Offer', - url: `https://ifixkart.trionixsolution.com/products/${product.slug}`, + url: variantOfferUrl, priceCurrency: 'INR', - price: primaryVariant?.price || 0, + price: activeVariant?.price || 0, priceValidUntil: '2027-12-31', itemCondition: 'https://schema.org/NewCondition', - availability: (primaryVariant?.price && Number(primaryVariant?.price) > 0) + availability: (activeVariant?.price && Number(activeVariant?.price) > 0) ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock', seller: { @@ -445,6 +537,7 @@ export default async function ProductDetailPage({ params }: ProductDetailPagePro product={product} initialReviewsCount={reviews.length} relatedProducts={related} + initialVariantSku={activeVariant?.sku} />
diff --git a/app/sitemap.ts b/app/sitemap.ts new file mode 100644 index 0000000..0c5d1ee --- /dev/null +++ b/app/sitemap.ts @@ -0,0 +1,71 @@ +import type { MetadataRoute } from 'next'; + +const SITE_URL = 'https://ifixkart.trionixsolution.com'; + +const API_URL = + process.env.API_URL || + process.env.NEXT_PUBLIC_API_URL || + 'https://ifixkartbe.trionixsolution.com'; + +// Rebuild the sitemap at most once an hour +export const revalidate = 3600; + +const STATIC_ROUTES: MetadataRoute.Sitemap = [ + { url: `${SITE_URL}/`, changeFrequency: 'daily', priority: 1 }, + { url: `${SITE_URL}/shop`, changeFrequency: 'daily', priority: 0.9 }, + { url: `${SITE_URL}/repair-services`, changeFrequency: 'weekly', priority: 0.8 }, + { url: `${SITE_URL}/about`, changeFrequency: 'monthly', priority: 0.4 }, + { url: `${SITE_URL}/contact`, changeFrequency: 'monthly', priority: 0.4 }, + { url: `${SITE_URL}/faqs`, changeFrequency: 'monthly', priority: 0.3 }, + { url: `${SITE_URL}/blog`, changeFrequency: 'weekly', priority: 0.5 }, +]; + +interface CatalogCard { + slug: string; + variant_sku?: string | null; + variant_url?: string | null; +} + +/** + * Emits one URL per product variant (Sunsky-style): + * /products/[slug]?variant=[sku] + * Google indexes query-param variants as long as they are internally linked + * and each PDP URL carries a self-referential canonical tag. + */ +export default async function sitemap(): Promise { + const entries: MetadataRoute.Sitemap = [...STATIC_ROUTES]; + const seen = new Set(); + + try { + // 40 pages x 100 = up to 4000 variant cards per sitemap build + for (let page = 1; page <= 40; page++) { + const res = await fetch( + `${API_URL}/api/v1/catalog/products?page=${page}&limit=100&expand_variants=true`, + { next: { revalidate: 3600, tags: ['products'] } } + ); + if (!res.ok) break; + const data = await res.json(); + const products: CatalogCard[] = data?.products || []; + if (products.length === 0) break; + + for (const p of products) { + const path = p.variant_url || `/products/${p.slug}`; + if (seen.has(path)) continue; + seen.add(path); + entries.push({ + url: `${SITE_URL}${path}`, + changeFrequency: 'weekly', + priority: p.variant_url ? 0.7 : 0.8, + }); + } + + const total = typeof data?.total === 'number' ? data.total : 0; + if (page * 100 >= total) break; + } + } catch (err) { + // Backend unreachable: sitemap still ships with static routes + console.error('Sitemap: failed to fetch catalog for variant URLs:', err); + } + + return entries; +} diff --git a/components/FloatingButtons.tsx b/components/FloatingButtons.tsx index 76ec6d7..304a66a 100644 --- a/components/FloatingButtons.tsx +++ b/components/FloatingButtons.tsx @@ -1,20 +1,59 @@ "use client"; -import React, { useState, useEffect } from 'react'; +import React, { useState, useEffect, useCallback } from 'react'; +import { usePathname } from 'next/navigation'; import { ChevronUp } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; +import { useCartStore } from '@/store/cartStore'; + +/** Height of the fixed compare strip at the bottom (CompareBar: py-3 + 36px row + border). */ +const COMPARE_BAR_HEIGHT_PX = 76; export const FloatingButtons: React.FC = () => { const [showScrollTop, setShowScrollTop] = useState(false); + /** Extra bottom offset so this button is never covered by fixed bottom bars. */ + const [barOffset, setBarOffset] = useState(0); + const pathname = usePathname(); + + const compareList = useCartStore((s) => s.compareList) || []; + const hydrated = useCartStore((s) => s._hasHydrated); + const compareBarVisible = + hydrated && pathname !== '/compare' && compareList.length > 0; + + const measure = useCallback(() => { + // PDP sticky purchase bar (rendered in ProductInteractiveGrid) — only counts + // while it is actually in the layout and visible. + const bar = document.querySelector('.sticky-purchase-bar'); + const purchaseBarH = + bar && bar.offsetHeight > 0 && bar.getBoundingClientRect().height > 0 + ? bar.offsetHeight + : 0; + const compareH = compareBarVisible ? COMPARE_BAR_HEIGHT_PX : 0; + setBarOffset((prev) => { + const next = Math.max(purchaseBarH, compareH); + return prev === next ? prev : next; + }); + }, [compareBarVisible]); useEffect(() => { const handleScroll = () => { setShowScrollTop(window.scrollY > 400); + measure(); }; - window.addEventListener('scroll', handleScroll); - return () => window.removeEventListener('scroll', handleScroll); - }, []); + handleScroll(); + window.addEventListener('scroll', handleScroll, { passive: true }); + window.addEventListener('resize', measure, { passive: true }); + return () => { + window.removeEventListener('scroll', handleScroll); + window.removeEventListener('resize', measure); + }; + }, [measure]); + + // Re-measure when the compare strip appears/disappears without scrolling. + useEffect(() => { + measure(); + }, [measure]); const scrollToTop = () => { window.scrollTo({ @@ -24,9 +63,14 @@ export const FloatingButtons: React.FC = () => { }; return ( -
- - {/* Scroll to Top */} +
+ {/* Scroll to Top — hidden on phones (<640px): fixed bottom bars live there, + and both iOS and Android scroll to top from the status bar. */} {showScrollTop && ( {
); }; - diff --git a/components/MobileDrawer.tsx b/components/MobileDrawer.tsx index 9e9797d..c03d08d 100644 --- a/components/MobileDrawer.tsx +++ b/components/MobileDrawer.tsx @@ -31,11 +31,22 @@ export const MobileDrawer: React.FC = ({ isOpen, onClose }) = return () => document.removeEventListener('keydown', handleKeyDown); }, [isOpen, onClose]); + // Lock background scroll while the drawer is open (same pattern as CartDrawer), + // and restore the previous value on close. + React.useEffect(() => { + if (!isOpen) return; + const prev = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + return () => { + document.body.style.overflow = prev; + }; + }, [isOpen]); + const links = [ { name: 'Home', href: '/' }, { name: 'Shop', href: '/shop' }, - { name: 'Services', href: '/service' }, - { name: 'Top Deals', href: '/shop' }, + { name: 'Top Deals', href: '/shop?tag=deals' }, + { name: 'Services', href: '/services' }, ]; return ( @@ -57,7 +68,7 @@ export const MobileDrawer: React.FC = ({ isOpen, onClose }) = animate={{ x: 0 }} exit={{ x: '-100%' }} transition={{ type: 'tween', duration: 0.3 }} - className="fixed top-0 left-0 bottom-0 w-[280px] bg-white z-50 xl:hidden flex flex-col justify-between shadow-xl overflow-y-auto" + className="fixed top-0 left-0 bottom-0 w-[280px] max-w-[85vw] bg-white z-50 xl:hidden flex flex-col justify-between shadow-xl overflow-y-auto overscroll-contain" >
{/* Header */} @@ -67,9 +78,10 @@ export const MobileDrawer: React.FC = ({ isOpen, onClose }) =
@@ -113,8 +125,8 @@ export const MobileDrawer: React.FC = ({ isOpen, onClose }) = )}
- {/* Footer */} -
+ {/* Footer — honors iOS home indicator / Android gesture bar */} +
© {new Date().getFullYear()} iFixKart. All Rights Reserved.
diff --git a/components/QuickViewModal.tsx b/components/QuickViewModal.tsx index 235a823..91af5da 100644 --- a/components/QuickViewModal.tsx +++ b/components/QuickViewModal.tsx @@ -242,7 +242,7 @@ export const QuickViewModal: React.FC = ({
e.stopPropagation()} - className="bg-white w-full max-w-[1000px] md:h-[min(500px,82vh)] md:w-[min(1000px,calc(82vh*2))] overflow-hidden shadow-2xl relative flex flex-col md:flex-row text-left mx-10 md:mx-16" + className="bg-white w-full max-w-[1000px] md:h-[min(500px,82dvh)] md:w-[min(1000px,calc(82dvh*2))] overflow-hidden shadow-2xl relative flex flex-col md:flex-row text-left mx-3 md:mx-16" > ) : ( diff --git a/components/catalog/ParentFeatureCatalog.tsx b/components/catalog/ParentFeatureCatalog.tsx index 08f3c17..48b7ccc 100644 --- a/components/catalog/ParentFeatureCatalog.tsx +++ b/components/catalog/ParentFeatureCatalog.tsx @@ -368,16 +368,18 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) { return (
- + + + {p.badge && ( {p.badge} @@ -411,7 +413,7 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) {
- +

{p.name}

diff --git a/components/catalog/StandardCatalog.tsx b/components/catalog/StandardCatalog.tsx index 46be943..65dcece 100644 --- a/components/catalog/StandardCatalog.tsx +++ b/components/catalog/StandardCatalog.tsx @@ -81,12 +81,13 @@ function CatalogProductCard({ const compareList = useCartStore((s) => s.compareList) || []; const variant = product.variants?.[0]; + const productUrl = product.variant_url || `/products/${product.slug}`; const { price, oldPrice, discount: mappedDiscount } = getCatalogPriceInfo(product); const compare = oldPrice || 0; const discount = mappedDiscount || (compare > price ? Math.round(((compare - price) / compare) * 100) : 0); - const image = getImageUrl(product.images[0]?.image_url); + const image = getImageUrl((product as any).thumbnail_url || product.images?.[0]?.image_url); const rating = getDisplayStarCount(product); const isWishlisted = wishlist.some((i) => i.product_id === product.product_id); const isCompared = compareList.some((i) => i.product_id === product.product_id); @@ -98,7 +99,7 @@ function CatalogProductCard({ e.stopPropagation(); if (!variant) return; if (hasOptions) { - window.location.href = `/products/${product.slug}`; + window.location.href = productUrl; return; } void addToCart(product, variant, 1); @@ -107,7 +108,7 @@ function CatalogProductCard({ if (viewMode === 'list') { return (
- + {discount > 0 && ( -{discount}% @@ -121,7 +122,7 @@ function CatalogProductCard({
{product.name} @@ -215,7 +216,7 @@ function CatalogProductCard({
{image ? ( @@ -233,7 +234,7 @@ function CatalogProductCard({
{product.name} @@ -400,7 +401,11 @@ export function StandardCatalog({ }; if (selectedCategory !== 'all') paramsBase.category = selectedCategory; if (selectedBrand !== 'all') paramsBase.brand = selectedBrand; - if (searchQuery) paramsBase.search = searchQuery; + if (searchQuery) { + paramsBase.search = searchQuery; + // Sunsky-style: keyword searches expand each active variant into its own card + paramsBase.expand_variants = 'true'; + } const accumulated: ProductResponse[] = []; const seen = new Set(); @@ -421,8 +426,10 @@ export function StandardCatalog({ let added = 0; for (const product of mapped) { - if (seen.has(product.product_id)) continue; - seen.add(product.product_id); + // Variant-expanded cards share the same product_id — dedupe per variant + const dedupeKey = product.variant_url || product.product_id; + if (seen.has(dedupeKey)) continue; + seen.add(dedupeKey); accumulated.push(product); added += 1; } @@ -753,13 +760,13 @@ export function StandardCatalog({ ) : viewMode === 'grid' ? (
{displayed.map((p) => ( - + ))}
) : (
{displayed.map((p) => ( - + ))}
)} diff --git a/components/compare/CompareBar.tsx b/components/compare/CompareBar.tsx index acd1108..f1779f8 100644 --- a/components/compare/CompareBar.tsx +++ b/components/compare/CompareBar.tsx @@ -18,7 +18,10 @@ export function CompareBar() { if (!hydrated || pathname === '/compare' || compareList.length === 0) return null; return ( -
+
diff --git a/components/pdp/ProductInteractiveGrid.tsx b/components/pdp/ProductInteractiveGrid.tsx index c52d381..4da0414 100644 --- a/components/pdp/ProductInteractiveGrid.tsx +++ b/components/pdp/ProductInteractiveGrid.tsx @@ -33,6 +33,7 @@ interface ProductInteractiveGridProps { product: ProductResponse; initialReviewsCount: number; relatedProducts?: ProductResponse[]; + initialVariantSku?: string; } const FALLBACK_TECH_IMAGES: string[] = ['/images/placeholder-product.webp']; @@ -84,13 +85,26 @@ export const ProductInteractiveGrid: React.FC = ({ product, initialReviewsCount, relatedProducts = [], + initialVariantSku, }) => { const searchParams = useSearchParams(); const router = useRouter(); + const getInitialIndex = () => { + const key = initialVariantSku || searchParams?.get('variant') || searchParams?.get('sku'); + if (key && product?.variants?.length) { + const decoded = decodeURIComponent(key); + const idx = product.variants.findIndex( + (v: any) => v.sku === decoded || String(v.variant_id) === decoded + ); + if (idx !== -1) return idx; + } + return 0; + }; + const [failedImages, setFailedImages] = useState>(new Set()); - const [selectedImage, setSelectedImage] = useState(() => resolveInitialImage(product, 0)); - const [selectedVariantIndex, setSelectedVariantIndex] = useState(0); + const [selectedVariantIndex, setSelectedVariantIndex] = useState(getInitialIndex); + const [selectedImage, setSelectedImage] = useState(() => resolveInitialImage(product, getInitialIndex())); const [quantity, setQuantity] = useState(1); const [added, setAdded] = useState(false); const [selections, setSelections] = useState>({}); @@ -113,6 +127,30 @@ export const ProductInteractiveGrid: React.FC = ({ variantAttrsMap: Map>; validValuesByDimension: Map>; } | null>(null); + // Tracks the last variant SKU written to the URL by this component so the + // URL-sync effect can skip re-applying selection after history.replaceState. + const urlWrittenByUs = useRef(null); + + // SEO: silently sync the browser URL to the selected variant (no reload, + // no server round-trip) so every color/spec combination gets a shareable + // /products/[slug]?variant=[sku] URL. + const syncVariantUrl = (variant: any) => { + const sku = variant?.sku; + if (!sku || typeof window === 'undefined') return; + const slug = (product as any).slug || product.product_id; + if (!slug) return; + try { + const newUrl = `/products/${slug}?variant=${encodeURIComponent(sku)}`; + window.history.replaceState( + { ...(window.history.state || {}), as: newUrl, url: newUrl }, + '', + newUrl + ); + urlWrittenByUs.current = sku; + } catch { + // URL sync is best-effort; never block variant selection on it + } + }; // Initialize lookup maps and default state on mount/product change useEffect(() => { @@ -135,13 +173,30 @@ export const ProductInteractiveGrid: React.FC = ({ lookupIndex.current = { variantAttrsMap, validValuesByDimension }; - // Select variant based on URL params or default to first index - const urlVariantId = searchParams.get('variant'); + // Select variant based on URL params or default to first index. + // `?variant=` accepts either the SKU or the variant_id (SEO URLs use SKU); + // `?sku=` is kept for backwards compatibility. + const urlVariantKey = initialVariantSku || searchParams.get('variant'); const urlSku = searchParams.get('sku'); - let activeIdx = product.variants.findIndex((v: any) => v.variant_id === urlVariantId || v.sku === urlSku); + const decodedKey = urlVariantKey ? decodeURIComponent(urlVariantKey) : null; + let activeIdx = product.variants.findIndex( + (v: any) => + (decodedKey && (v.sku === decodedKey || String(v.variant_id) === decodedKey)) || + (urlSku && v.sku === urlSku) + ); if (activeIdx === -1) { activeIdx = 0; } + + // If this URL value was written by our own history.replaceState and the + // user's selection already matches, don't reset image/zoom state. + if ( + urlWrittenByUs.current && + decodedKey === urlWrittenByUs.current && + product.variants[selectedVariantIndex]?.sku === decodedKey + ) { + return; + } setSelectedVariantIndex(activeIdx); setSelectedImage(resolveInitialImage(product, activeIdx, failedImages)); @@ -154,7 +209,7 @@ export const ProductInteractiveGrid: React.FC = ({ }); } setSelections(initial); - }, [product, searchParams]); + }, [product, searchParams, initialVariantSku]); useEffect(() => { const named = (product as ProductResponse & { brand_name?: string }).brand_name; @@ -625,6 +680,7 @@ export const ProductInteractiveGrid: React.FC = ({ if (varImg) { setSelectedImage(getImageUrl(varImg)); } + syncVariantUrl(match); } }} className={`px-3 py-1.5 rounded text-[12px] font-semibold transition border cursor-pointer ${ @@ -662,6 +718,7 @@ export const ProductInteractiveGrid: React.FC = ({ if (varImg) { setSelectedImage(getImageUrl(varImg)); } + syncVariantUrl(v); }} className={`px-3 py-1.5 rounded text-[12px] font-semibold transition border cursor-pointer ${isSelected ? 'border-primary bg-primary/10 text-primary font-bold shadow-xs' diff --git a/components/store/LiveSearch.tsx b/components/store/LiveSearch.tsx index fb45996..b845679 100644 --- a/components/store/LiveSearch.tsx +++ b/components/store/LiveSearch.tsx @@ -12,12 +12,29 @@ import Image from 'next/image'; import { Loader2, X, ChevronDown, Check, LayoutGrid, Search } from 'lucide-react'; import { storefrontService, LiveSearchResult } from '@/services/api/storefrontService'; import { catalogService, CategoryResponse } from '@/services/api/catalogService'; -import { getImageUrl } from '@/lib/utils'; +import { formatCurrency, getImageUrl } from '@/lib/utils'; import { getCategoryMenuItems, menuItemCategoryParam, } from '@/components/CategorySidebar'; +function SearchItemImage({ src, alt }: { src: string; alt: string }) { + const [imgSrc, setImgSrc] = useState(src); + useEffect(() => { + setImgSrc(src); + }, [src]); + + return ( + {alt} setImgSrc('/images/placeholder-product.webp')} + /> + ); +} + export function LiveSearch() { const router = useRouter(); const [query, setQuery] = useState(''); @@ -282,33 +299,35 @@ export function LiveSearch() { {!loading && hasResults && (
- {results.products.slice(0, 5).map((product) => ( - setIsOpen(false)} - className="flex items-center gap-3 p-2 hover:bg-gray-50 rounded-md transition-colors" - > -
- {product.images[0]?.image_url ? ( - {product.name} - ) : ( -
- )} -
-
-
{product.name}
-
- ₹{Number(product.variants[0]?.price || 0).toFixed(2)} + {results.products.slice(0, 8).map((product) => { + const imgUrl = (product as any).thumbnail_url || product.images?.[0]?.image_url; + const price = (product as any).price ?? product.variants?.[0]?.price ?? 0; + return ( + setIsOpen(false)} + className="flex items-center gap-3 p-2 hover:bg-gray-50 rounded-md transition-colors" + > +
+ {imgUrl ? ( + + ) : ( +
+ )}
-
- - ))} +
+
{product.name}
+
+ {formatCurrency(price)} +
+
+ + ); + })}
)}
diff --git a/components/store/ProductCard.tsx b/components/store/ProductCard.tsx index ad772ae..07d3ba2 100644 --- a/components/store/ProductCard.tsx +++ b/components/store/ProductCard.tsx @@ -34,6 +34,7 @@ export function ProductCard({ product }: ProductCardProps) { const primaryVariant = product.variants[0]; const primaryImage = getImageUrl(product.images[0]?.image_url); const secondaryImage = getImageUrl(product.images[1]?.image_url) || primaryImage; + const productUrl = (product as any).variant_url || `/products/${product.slug}`; const price = Number(primaryVariant?.price || 0); const comparePrice = primaryVariant?.compare_price != null ? Number(primaryVariant.compare_price) : null; @@ -107,7 +108,7 @@ export function ProductCard({ product }: ProductCardProps) {
{/* Image Gallery Flip Container */} - + {product.name} diff --git a/layout/Header.tsx b/layout/Header.tsx index 5cfd5ab..4304b4b 100644 --- a/layout/Header.tsx +++ b/layout/Header.tsx @@ -25,7 +25,7 @@ export const Header: React.FC = () => { return (
{ href="/" className="flex items-center select-none tracking-tighter hover:opacity-95 transition-opacity" > - + iFix - + Kart diff --git a/layout/HeaderActions.tsx b/layout/HeaderActions.tsx index 6ec786d..c5d9eb2 100644 --- a/layout/HeaderActions.tsx +++ b/layout/HeaderActions.tsx @@ -45,7 +45,7 @@ export const HeaderActions: React.FC = () => {