feat(storefront): update PDP interactive grid, dynamic sitemap, catalog filters, and navigation links
This commit is contained in:
parent
16dbaa0916
commit
5424420acc
23 changed files with 516 additions and 119 deletions
|
|
@ -1106,7 +1106,7 @@ function AccountDashboardPage() {
|
|||
{addressModalOpen && (
|
||||
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/50 p-4 sm:p-6 overflow-y-auto">
|
||||
<div
|
||||
className="relative w-full max-w-md my-auto bg-white border border-[#e5e5e5] shadow-xl flex flex-col max-h-[min(640px,calc(100vh-2rem))]"
|
||||
className="relative w-full max-w-md my-auto bg-white border border-[#e5e5e5] shadow-xl flex flex-col max-h-[min(640px,calc(100dvh-2rem))]"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="address-modal-title"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { Metadata } from 'next';
|
||||
import type { Metadata, Viewport } from 'next';
|
||||
import './globals.css';
|
||||
import '../styles/mobile-overrides.css';
|
||||
import { Suspense } from 'react';
|
||||
|
|
@ -9,6 +9,7 @@ import { GoogleAnalytics } from '@/components/analytics/GoogleAnalytics';
|
|||
import { Toaster } from 'sonner';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
metadataBase: new URL('https://ifixkart.trionixsolution.com'),
|
||||
title: 'iFixKart TechShop | Electronics & Certified Repair Hub',
|
||||
description:
|
||||
'Shop top smartphones, laptops, smartwatches, OEM replacement spare parts, and book certified device repair services.',
|
||||
|
|
@ -20,6 +21,19 @@ export const metadata: Metadata = {
|
|||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* viewportFit: 'cover' is required for env(safe-area-inset-bottom) to return
|
||||
* non-zero on iPhone X+ (notch / Dynamic Island / home indicator) — the PDP
|
||||
* sticky purchase bar and other fixed bottom elements rely on it.
|
||||
* themeColor tints the browser UI bar on Android Chrome and iOS Safari.
|
||||
*/
|
||||
export const viewport: Viewport = {
|
||||
width: 'device-width',
|
||||
initialScale: 1,
|
||||
viewportFit: 'cover',
|
||||
themeColor: '#1976F3',
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { Metadata } from 'next';
|
||||
import React from 'react';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
|
|
@ -19,6 +20,88 @@ import { YouMayAlsoLike } from '@/components/pdp/YouMayAlsoLike';
|
|||
|
||||
interface ProductDetailPageProps {
|
||||
params: Promise<{ slug: string }>;
|
||||
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<Metadata> {
|
||||
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
|
|||
</table>
|
||||
);
|
||||
|
||||
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}
|
||||
/>
|
||||
|
||||
<div className="mt-10">
|
||||
|
|
|
|||
71
app/sitemap.ts
Normal file
71
app/sitemap.ts
Normal file
|
|
@ -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<MetadataRoute.Sitemap> {
|
||||
const entries: MetadataRoute.Sitemap = [...STATIC_ROUTES];
|
||||
const seen = new Set<string>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
@ -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<HTMLElement>('.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 (
|
||||
<div className="fixed bottom-6 right-6 z-50 flex flex-col items-center gap-3">
|
||||
|
||||
{/* Scroll to Top */}
|
||||
<div
|
||||
className="fixed right-6 z-50 hidden sm:flex flex-col items-center gap-3"
|
||||
style={{
|
||||
bottom: `calc(${barOffset}px + max(1.5rem, env(safe-area-inset-bottom, 0px) + 0.75rem))`,
|
||||
}}
|
||||
>
|
||||
{/* Scroll to Top — hidden on phones (<640px): fixed bottom bars live there,
|
||||
and both iOS and Android scroll to top from the status bar. */}
|
||||
<AnimatePresence>
|
||||
{showScrollTop && (
|
||||
<motion.button
|
||||
|
|
@ -45,4 +89,3 @@ export const FloatingButtons: React.FC = () => {
|
|||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -31,11 +31,22 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ 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<MobileDrawerProps> = ({ 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"
|
||||
>
|
||||
<div>
|
||||
{/* Header */}
|
||||
|
|
@ -67,9 +78,10 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
|
|||
</span>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1.5 text-gray-400 hover:text-gray-650 hover:bg-gray-50 rounded-lg transition-colors"
|
||||
className="p-2.5 -mr-1 text-gray-400 hover:text-gray-650 hover:bg-gray-50 rounded-lg transition-colors cursor-pointer"
|
||||
aria-label="Close Menu"
|
||||
>
|
||||
<X size={20} />
|
||||
<X size={22} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
|
@ -113,8 +125,8 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
|
|||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="p-4 border-t border-gray-100 text-xs text-gray-400 text-center font-medium bg-gray-50">
|
||||
{/* Footer — honors iOS home indicator / Android gesture bar */}
|
||||
<div className="p-4 pt-3 border-t border-gray-100 text-xs text-gray-400 text-center font-medium bg-gray-50 pb-[max(1rem,env(safe-area-inset-bottom))]">
|
||||
© {new Date().getFullYear()} iFixKart. All Rights Reserved.
|
||||
</div>
|
||||
</motion.div>
|
||||
|
|
|
|||
|
|
@ -242,7 +242,7 @@ export const QuickViewModal: React.FC<QuickViewModalProps> = ({
|
|||
|
||||
<div
|
||||
onClick={(e) => 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"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -37,6 +37,27 @@ function mapCategories(cats: CategoryResponse[]): ShopByItem[] {
|
|||
}));
|
||||
}
|
||||
|
||||
const CategoryItemIcon: React.FC<{ src?: string; alt: string }> = ({ src, alt }) => {
|
||||
const [hasError, setHasError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setHasError(false);
|
||||
}, [src]);
|
||||
|
||||
if (!src || hasError) {
|
||||
return <Layers className="w-6 h-6 text-gray-400 group-hover/item:text-primary transition-colors" />;
|
||||
}
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt={alt}
|
||||
loading="lazy"
|
||||
className="max-w-full max-h-full object-contain"
|
||||
onError={() => setHasError(true)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
function mapProducts(products: ProductCardResponse[]): RatedItem[] {
|
||||
return products.slice(0, 6).map((p) => ({
|
||||
id: p.product_id,
|
||||
|
|
@ -136,15 +157,7 @@ export const TopDealsMegaMenu: React.FC<{ cms?: MegaMenuData | null }> = ({
|
|||
className="flex flex-col items-center gap-2 group/item text-center min-w-0"
|
||||
>
|
||||
<span className="w-[64px] h-[64px] lg:w-[72px] lg:h-[72px] rounded-full border border-gray-200 bg-white flex items-center justify-center overflow-hidden p-2 group-hover/item:border-primary/40 transition-colors shrink-0">
|
||||
{item.image ? (
|
||||
<img
|
||||
src={item.image}
|
||||
alt={item.name}
|
||||
className="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<Layers className="w-6 h-6 text-gray-400 group-hover/item:text-primary transition-colors" />
|
||||
)}
|
||||
<CategoryItemIcon src={item.image} alt={item.name} />
|
||||
</span>
|
||||
<span className="text-[11px] lg:text-[12px] font-medium text-[#333] group-hover/item:text-primary transition-colors line-clamp-2 leading-snug px-0.5 w-full">
|
||||
{item.name}
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ export const WishlistModal: React.FC<WishlistModalProps> = ({ onClose }) => {
|
|||
>
|
||||
<div
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-white w-full max-w-[740px] rounded-2xl shadow-2xl overflow-hidden relative flex flex-col max-h-[85vh] text-left"
|
||||
className="bg-white w-full max-w-[740px] rounded-2xl shadow-2xl overflow-hidden relative flex flex-col max-h-[85dvh] text-left"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="bg-[#1E1E1E] text-white px-7 py-4 flex items-center justify-between">
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [csrfToken, setCsrfToken] = useState('');
|
||||
const [fetchingCsrf, setFetchingCsrf] = useState(false);
|
||||
const [mode, setMode] = useState<'login' | 'link'>('login');
|
||||
const [linkEmail, setLinkEmail] = useState('');
|
||||
const [linkPassword, setLinkPassword] = useState('');
|
||||
|
|
@ -64,21 +65,36 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
|
||||
const setAuth = useAuthStore((state) => state.setAuth);
|
||||
|
||||
const fetchCsrfToken = async () => {
|
||||
setFetchingCsrf(true);
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/v1/customer/auth/google/state`, {
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data?.state) {
|
||||
setCsrfToken(data.state);
|
||||
return data.state;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch OAuth state token:', err);
|
||||
} finally {
|
||||
setFetchingCsrf(false);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const prev = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
|
||||
const array = new Uint32Array(4);
|
||||
if (typeof window !== 'undefined' && window.crypto) {
|
||||
window.crypto.getRandomValues(array);
|
||||
setCsrfToken(Array.from(array, (dec) => dec.toString(16)).join(''));
|
||||
} else {
|
||||
setCsrfToken(
|
||||
Math.random().toString(36).substring(2, 15) +
|
||||
Math.random().toString(36).substring(2, 15)
|
||||
);
|
||||
}
|
||||
// Fetch HMAC-signed CSRF state token from backend
|
||||
fetchCsrfToken();
|
||||
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
|
|
@ -99,7 +115,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleAuthCodeSubmit = async (code: string) => {
|
||||
const handleAuthCodeSubmit = async (code: string, returnedState?: string) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
|
|
@ -108,6 +124,8 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
? localStorage.getItem('guest_session_id') || undefined
|
||||
: undefined;
|
||||
|
||||
const stateToSend = returnedState || csrfToken;
|
||||
|
||||
const res = await fetch(`${API_BASE_URL}/api/v1/customer/auth/google`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
|
@ -117,7 +135,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
code,
|
||||
state: csrfToken,
|
||||
state: stateToSend,
|
||||
guest_session_id: guestSessionId,
|
||||
redirect_uri: 'postmessage',
|
||||
}),
|
||||
|
|
@ -147,6 +165,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
onClose();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Google authentication failed. Please try again.');
|
||||
fetchCsrfToken();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
|
@ -205,12 +224,26 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
}
|
||||
};
|
||||
|
||||
const handleGoogleClick = async () => {
|
||||
setError(null);
|
||||
let token = csrfToken;
|
||||
if (!token) {
|
||||
token = await fetchCsrfToken();
|
||||
}
|
||||
if (token) {
|
||||
googleLogin();
|
||||
} else {
|
||||
setError('Unable to establish secure authentication session. Please retry.');
|
||||
}
|
||||
};
|
||||
|
||||
const googleLogin = useGoogleLogin({
|
||||
onSuccess: (codeResponse) => {
|
||||
if (codeResponse.code) handleAuthCodeSubmit(codeResponse.code);
|
||||
if (codeResponse.code) handleAuthCodeSubmit(codeResponse.code, codeResponse.state);
|
||||
},
|
||||
onError: () => {
|
||||
setError('Google Login popup was closed or authentication failed.');
|
||||
fetchCsrfToken();
|
||||
},
|
||||
flow: 'auth-code',
|
||||
state: csrfToken,
|
||||
|
|
@ -305,12 +338,12 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
|
|||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => googleLogin()}
|
||||
disabled={loading}
|
||||
onClick={handleGoogleClick}
|
||||
disabled={loading || fetchingCsrf}
|
||||
className="w-full flex items-center justify-center gap-3 px-4 py-3.5 rounded-lg font-semibold text-[14px] text-[#1a1a1a] bg-white border border-gray-200 hover:border-primary/40 hover:bg-[#F8FBFF] shadow-sm transition-colors disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
<GoogleIcon />
|
||||
{loading ? 'Connecting Google...' : 'Continue with Google'}
|
||||
{loading ? 'Connecting Google...' : fetchingCsrf ? 'Securing session...' : 'Continue with Google'}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -368,16 +368,18 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) {
|
|||
|
||||
return (
|
||||
<div
|
||||
key={p.product_id}
|
||||
key={(p as any).variant_sku || p.product_id}
|
||||
className="group bg-white rounded-2xl border border-gray-200 p-4 shadow-xs hover:shadow-lg hover:border-gray-300 transition-all duration-300 flex flex-col justify-between"
|
||||
>
|
||||
<div className="relative aspect-square mb-3 bg-gray-50 rounded-xl overflow-hidden">
|
||||
<Link href={p.variant_url || `/products/${p.slug}`} className="block w-full h-full">
|
||||
<BlurHashImage
|
||||
src={primaryImage}
|
||||
alt={p.name}
|
||||
fill
|
||||
className="object-contain p-2 group-hover:scale-105 transition-transform duration-300"
|
||||
/>
|
||||
</Link>
|
||||
{p.badge && (
|
||||
<span className="absolute top-2 left-2 bg-red-600 text-white text-[10px] font-bold px-2.5 py-0.5 rounded-full">
|
||||
{p.badge}
|
||||
|
|
@ -411,7 +413,7 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) {
|
|||
|
||||
<div className="flex-1 flex flex-col justify-between">
|
||||
<div>
|
||||
<Link href={`/products/${p.slug}`}>
|
||||
<Link href={p.variant_url || `/products/${p.slug}`}>
|
||||
<h4 className="text-xs font-bold text-gray-900 hover:text-red-600 transition-colors line-clamp-2 mb-2">
|
||||
{p.name}
|
||||
</h4>
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<div className="flex gap-5 p-5 border-b border-[#e8e8e8] bg-white hover:bg-[#fafafa] transition-colors group">
|
||||
<Link href={`/products/${product.slug}`} className="relative w-36 h-36 shrink-0 bg-white">
|
||||
<Link href={productUrl} className="relative w-36 h-36 shrink-0 bg-white">
|
||||
{discount > 0 && (
|
||||
<span className="absolute top-0 right-0 z-10 bg-primary text-white text-[10px] font-bold px-1.5 py-0.5">
|
||||
-{discount}%
|
||||
|
|
@ -121,7 +122,7 @@ function CatalogProductCard({
|
|||
</Link>
|
||||
<div className="flex-1 min-w-0 flex flex-col justify-center">
|
||||
<Link
|
||||
href={`/products/${product.slug}`}
|
||||
href={productUrl}
|
||||
className="text-[14px] font-semibold text-[#222] hover:text-primary line-clamp-2 mb-1.5"
|
||||
>
|
||||
{product.name}
|
||||
|
|
@ -215,7 +216,7 @@ function CatalogProductCard({
|
|||
</div>
|
||||
|
||||
<Link
|
||||
href={`/products/${product.slug}`}
|
||||
href={productUrl}
|
||||
className="relative flex-1 flex items-center justify-center min-h-[160px] mb-3"
|
||||
>
|
||||
{image ? (
|
||||
|
|
@ -233,7 +234,7 @@ function CatalogProductCard({
|
|||
|
||||
<div className="text-left mt-auto">
|
||||
<Link
|
||||
href={`/products/${product.slug}`}
|
||||
href={productUrl}
|
||||
className="block text-[13px] font-semibold text-[#222] hover:text-primary line-clamp-2 leading-snug min-h-[36px] mb-1.5"
|
||||
>
|
||||
{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<string>();
|
||||
|
|
@ -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' ? (
|
||||
<div className="border border-[#e8e8e8] border-b-0 border-r-0 grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4">
|
||||
{displayed.map((p) => (
|
||||
<CatalogProductCard key={p.product_id} product={p} viewMode="grid" />
|
||||
<CatalogProductCard key={(p as any).variant_sku || p.variant_url || p.product_id} product={p} viewMode="grid" />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-[#e8e8e8] rounded-sm overflow-hidden">
|
||||
{displayed.map((p) => (
|
||||
<CatalogProductCard key={p.product_id} product={p} viewMode="list" />
|
||||
<CatalogProductCard key={(p as any).variant_sku || p.variant_url || p.product_id} product={p} viewMode="list" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,10 @@ export function CompareBar() {
|
|||
if (!hydrated || pathname === '/compare' || compareList.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-0 left-0 right-0 z-[90] border-t border-gray-200 bg-white/95 backdrop-blur-md shadow-[0_-12px_40px_rgba(16,24,40,0.12)]">
|
||||
<div
|
||||
className="fixed bottom-0 left-0 right-0 z-[90] border-t border-gray-200 bg-white/95 backdrop-blur-md shadow-[0_-12px_40px_rgba(16,24,40,0.12)]"
|
||||
style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}
|
||||
>
|
||||
<div className="max-w-7xl mx-auto px-4 py-3 flex items-center gap-4">
|
||||
<div className="hidden md:flex items-center gap-2 shrink-0">
|
||||
<div className="w-9 h-9 rounded-lg bg-primary/10 text-primary flex items-center justify-center">
|
||||
|
|
|
|||
|
|
@ -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<ProductInteractiveGridProps> = ({
|
|||
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<Set<string>>(new Set());
|
||||
const [selectedImage, setSelectedImage] = useState<string>(() => resolveInitialImage(product, 0));
|
||||
const [selectedVariantIndex, setSelectedVariantIndex] = useState(0);
|
||||
const [selectedVariantIndex, setSelectedVariantIndex] = useState<number>(getInitialIndex);
|
||||
const [selectedImage, setSelectedImage] = useState<string>(() => resolveInitialImage(product, getInitialIndex()));
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [added, setAdded] = useState(false);
|
||||
const [selections, setSelections] = useState<Record<string, string>>({});
|
||||
|
|
@ -113,6 +127,30 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
|
|||
variantAttrsMap: Map<string, Map<string, string>>;
|
||||
validValuesByDimension: Map<string, Set<string>>;
|
||||
} | 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<string | null>(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<ProductInteractiveGridProps> = ({
|
|||
|
||||
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<ProductInteractiveGridProps> = ({
|
|||
});
|
||||
}
|
||||
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<ProductInteractiveGridProps> = ({
|
|||
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<ProductInteractiveGridProps> = ({
|
|||
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'
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<Image
|
||||
src={imgSrc}
|
||||
alt={alt}
|
||||
fill
|
||||
className="object-contain"
|
||||
onError={() => setImgSrc('/images/placeholder-product.webp')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function LiveSearch() {
|
||||
const router = useRouter();
|
||||
const [query, setQuery] = useState('');
|
||||
|
|
@ -282,20 +299,21 @@ export function LiveSearch() {
|
|||
|
||||
{!loading && hasResults && (
|
||||
<div className="p-2 divide-y divide-gray-100 text-xs">
|
||||
{results.products.slice(0, 5).map((product) => (
|
||||
{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 (
|
||||
<Link
|
||||
key={product.product_id}
|
||||
href={`/products/${product.slug}`}
|
||||
key={(product as any).variant_sku || (product as any).variant_url || product.product_id}
|
||||
href={(product as any).variant_url || `/products/${product.slug}`}
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="flex items-center gap-3 p-2 hover:bg-gray-50 rounded-md transition-colors"
|
||||
>
|
||||
<div className="relative w-10 h-10 rounded border border-gray-100 overflow-hidden bg-gray-50 shrink-0">
|
||||
{product.images[0]?.image_url ? (
|
||||
<Image
|
||||
src={getImageUrl(product.images[0].image_url)}
|
||||
{imgUrl ? (
|
||||
<SearchItemImage
|
||||
src={getImageUrl(imgUrl)}
|
||||
alt={product.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full bg-gray-100" />
|
||||
|
|
@ -304,11 +322,12 @@ export function LiveSearch() {
|
|||
<div className="flex-1 min-w-0">
|
||||
<div className="font-semibold text-gray-800 truncate">{product.name}</div>
|
||||
<div className="text-xs text-[#1877f2] font-bold">
|
||||
₹{Number(product.variants[0]?.price || 0).toFixed(2)}
|
||||
{formatCurrency(price)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -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) {
|
|||
</div>
|
||||
|
||||
{/* Image Gallery Flip Container */}
|
||||
<Link href={`/products/${product.slug}`} className="block relative w-full pt-[85%] bg-gray-50 overflow-hidden">
|
||||
<Link href={productUrl} className="block relative w-full pt-[85%] bg-gray-50 overflow-hidden">
|
||||
<BlurHashImage
|
||||
src={primaryImage}
|
||||
blurHash={(product as any).blur_hash || null}
|
||||
|
|
@ -138,7 +139,7 @@ export function ProductCard({ product }: ProductCardProps) {
|
|||
|
||||
{/* Title */}
|
||||
<Link
|
||||
href={`/products/${product.slug}`}
|
||||
href={productUrl}
|
||||
className="text-xs font-bold text-[#1b2559] hover:text-[#e4382f] transition-colors line-clamp-2 leading-snug mb-2"
|
||||
>
|
||||
{product.name}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export const Header: React.FC = () => {
|
|||
return (
|
||||
<header
|
||||
data-storefront-header
|
||||
className={`bg-white z-[110] border-b border-gray-100 transition-shadow duration-200 ${
|
||||
className={`mobile-sticky-header bg-white z-[110] border-b border-gray-100 transition-shadow duration-200 ${
|
||||
isSticky
|
||||
? 'fixed top-0 left-0 right-0 shadow-md py-2.5'
|
||||
: 'relative pt-6 pb-4 shadow-2xs'
|
||||
|
|
@ -36,10 +36,10 @@ export const Header: React.FC = () => {
|
|||
href="/"
|
||||
className="flex items-center select-none tracking-tighter hover:opacity-95 transition-opacity"
|
||||
>
|
||||
<span className="text-[#0073EC] text-[38px] font-black leading-none">
|
||||
<span className="text-[#0073EC] text-[28px] min-[400px]:text-[38px] font-black leading-none">
|
||||
iFix
|
||||
</span>
|
||||
<span className="text-gray-900 text-[38px] font-black leading-none">
|
||||
<span className="text-gray-900 text-[28px] min-[400px]:text-[38px] font-black leading-none">
|
||||
Kart
|
||||
</span>
|
||||
</Link>
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ export const HeaderActions: React.FC = () => {
|
|||
|
||||
<button
|
||||
onClick={triggerMobileDrawer}
|
||||
className="lg:hidden p-2 text-gray-650 hover:text-primary transition-colors hover:bg-gray-50 rounded-lg cursor-pointer"
|
||||
className="xl:hidden p-2 text-gray-650 hover:text-primary transition-colors hover:bg-gray-50 rounded-lg cursor-pointer"
|
||||
aria-label="Open Menu"
|
||||
>
|
||||
<Menu size={24} className="stroke-[2.5]" />
|
||||
|
|
@ -53,7 +53,7 @@ export const HeaderActions: React.FC = () => {
|
|||
|
||||
<Link
|
||||
href="/compare"
|
||||
className="relative p-2 text-gray-650 hover:text-primary transition-colors hover:bg-gray-50 rounded-lg group focus:outline-none"
|
||||
className="relative p-2 text-gray-650 hover:text-primary transition-colors hover:bg-gray-50 rounded-lg group focus:outline-none hidden sm:block"
|
||||
aria-label="Compare products"
|
||||
>
|
||||
<GitCompare
|
||||
|
|
@ -113,7 +113,7 @@ export const HeaderActions: React.FC = () => {
|
|||
initial={{ opacity: 0, height: 0 }}
|
||||
animate={{ opacity: 1, height: 'auto' }}
|
||||
exit={{ opacity: 0, height: 0 }}
|
||||
className="lg:hidden border-t border-gray-100 px-4 pt-3 pb-2 bg-white w-full absolute left-0 right-0 top-full z-[120] shadow-md"
|
||||
className="lg:hidden mobile-search-overlay border-t border-gray-100 px-4 pt-3 pb-2 bg-white w-full absolute left-0 right-0 top-full z-[120] shadow-md"
|
||||
>
|
||||
<div className="flex gap-2 items-center relative z-55">
|
||||
<LiveSearch />
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ const nextConfig: NextConfig = {
|
|||
},
|
||||
async rewrites() {
|
||||
const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'https://ifixkartbe.trionixsolution.com';
|
||||
const mediaUrl = 'https://ifixkartbe.trionixsolution.com';
|
||||
const mediaUrl = process.env.NEXT_PUBLIC_MEDIA_URL || process.env.NEXT_PUBLIC_API_URL || 'https://ifixkartbe.trionixsolution.com';
|
||||
return [
|
||||
{
|
||||
source: '/api/v1/:path*',
|
||||
|
|
|
|||
|
|
@ -130,6 +130,9 @@ export interface ProductResponse {
|
|||
device_type?: string | null;
|
||||
mapped_service_category_id?: string | null;
|
||||
is_service_booking?: boolean;
|
||||
/** Variant-expanded search cards: deep link to this exact variant on the PDP */
|
||||
variant_url?: string | null;
|
||||
variant_sku?: string | null;
|
||||
}
|
||||
|
||||
export interface DeviceModelResponse {
|
||||
|
|
@ -179,6 +182,10 @@ export interface ProductCardResponse {
|
|||
brand_name: string | null;
|
||||
color?: string | null;
|
||||
colors?: string[];
|
||||
/** Variant-expanded search cards (expand_variants=true) */
|
||||
variant_sku?: string | null;
|
||||
variant_name?: string | null;
|
||||
variant_url?: string | null;
|
||||
}
|
||||
|
||||
export interface ProductPaginatedResponse {
|
||||
|
|
@ -221,6 +228,9 @@ export const catalogService = {
|
|||
|
||||
async getProductsPaginated(params: Record<string, any> = {}): Promise<ProductPaginatedResponse> {
|
||||
const query = new URLSearchParams();
|
||||
if (!('expand_variants' in params)) {
|
||||
query.append('expand_variants', 'true');
|
||||
}
|
||||
Object.entries(params).forEach(([key, val]) => {
|
||||
if (val !== undefined && val !== null && val !== '') {
|
||||
query.append(key, String(val));
|
||||
|
|
|
|||
|
|
@ -121,7 +121,11 @@ export const storefrontService = {
|
|||
}
|
||||
|
||||
try {
|
||||
return await apiFetch<LiveSearchResult>(API_ENDPOINTS.STOREFRONT_LIVE_SEARCH(query.trim(), category));
|
||||
const data = await apiFetch<LiveSearchResult>(API_ENDPOINTS.STOREFRONT_LIVE_SEARCH(query.trim(), category));
|
||||
return {
|
||||
...data,
|
||||
products: (data.products || []).map((p: any) => mapProductCardToProductResponse(p)),
|
||||
};
|
||||
} catch {
|
||||
try {
|
||||
const res = await catalogService.getProductsPaginated({
|
||||
|
|
|
|||
|
|
@ -11,6 +11,17 @@ a,
|
|||
}
|
||||
|
||||
/* 2. Responsive viewports & safe area overrides */
|
||||
|
||||
/* iOS Safari auto-zooms the page when focusing any form field with
|
||||
font-size < 16px and never zooms back. Force 16px on mobile. */
|
||||
@media (max-width: 767px) {
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font-size: 16px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
/* Selective backdrop-filter resets for slow scroll frame performance */
|
||||
.mobile-sticky-header,
|
||||
|
|
|
|||
|
|
@ -33,7 +33,9 @@ export function mapProductCardToProductResponse(
|
|||
{
|
||||
variant_id: p.first_variant_id || p.product_id,
|
||||
product_id: p.product_id,
|
||||
sku: (p as any).sku || '',
|
||||
// Variant-expanded cards carry their own SKU so add-to-cart and
|
||||
// PDP deep links (/products/[slug]?variant=[sku]) resolve correctly
|
||||
sku: (p as any).variant_sku || (p as any).sku || '',
|
||||
barcode: null,
|
||||
price,
|
||||
compare_price: comparePrice && comparePrice > 0 ? comparePrice : null,
|
||||
|
|
@ -61,7 +63,9 @@ export function mapProductCardToProductResponse(
|
|||
device_model_id: (p as any).device_model_id || null,
|
||||
name: p.name,
|
||||
slug: p.slug,
|
||||
full_path: (p as any).full_path || `/products/${p.slug}`,
|
||||
full_path: (p as any).variant_url || (p as any).full_path || `/products/${p.slug}`,
|
||||
variant_url: (p as any).variant_url || null,
|
||||
variant_sku: (p as any).variant_sku || null,
|
||||
description: (p as any).description ?? null,
|
||||
status: (p as any).status || 'active',
|
||||
created_at: (p as any).created_at || '',
|
||||
|
|
|
|||
Loading…
Reference in a new issue