feat(storefront): update PDP interactive grid, dynamic sitemap, catalog filters, and navigation links

This commit is contained in:
iFixKart Dev 2026-11-16 14:59:16 +05:30
parent 16dbaa0916
commit 5424420acc
23 changed files with 516 additions and 119 deletions

View file

@ -1106,7 +1106,7 @@ function AccountDashboardPage() {
{addressModalOpen && ( {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="fixed inset-0 z-[200] flex items-center justify-center bg-black/50 p-4 sm:p-6 overflow-y-auto">
<div <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" role="dialog"
aria-modal="true" aria-modal="true"
aria-labelledby="address-modal-title" aria-labelledby="address-modal-title"

View file

@ -1,4 +1,4 @@
import type { Metadata } from 'next'; import type { Metadata, Viewport } from 'next';
import './globals.css'; import './globals.css';
import '../styles/mobile-overrides.css'; import '../styles/mobile-overrides.css';
import { Suspense } from 'react'; import { Suspense } from 'react';
@ -9,6 +9,7 @@ import { GoogleAnalytics } from '@/components/analytics/GoogleAnalytics';
import { Toaster } from 'sonner'; import { Toaster } from 'sonner';
export const metadata: Metadata = { export const metadata: Metadata = {
metadataBase: new URL('https://ifixkart.trionixsolution.com'),
title: 'iFixKart TechShop | Electronics & Certified Repair Hub', title: 'iFixKart TechShop | Electronics & Certified Repair Hub',
description: description:
'Shop top smartphones, laptops, smartwatches, OEM replacement spare parts, and book certified device repair services.', '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({ export default function RootLayout({
children, children,
}: { }: {

View file

@ -1,3 +1,4 @@
import type { Metadata } from 'next';
import React from 'react'; import React from 'react';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
@ -19,6 +20,88 @@ import { YouMayAlsoLike } from '@/components/pdp/YouMayAlsoLike';
interface ProductDetailPageProps { interface ProductDetailPageProps {
params: Promise<{ slug: string }>; 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 = [ const HIDDEN_SPEC_KEYS = [
@ -227,8 +310,9 @@ function groupSpecs(specifications: any[], product: any) {
return groups; return groups;
} }
export default async function ProductDetailPage({ params }: ProductDetailPageProps) { export default async function ProductDetailPage({ params, searchParams }: ProductDetailPageProps) {
const { slug } = await params; const { slug } = await params;
const { variant: variantKey } = await searchParams;
if (!slug) { if (!slug) {
return notFound(); return notFound();
@ -390,30 +474,38 @@ export default async function ProductDetailPage({ params }: ProductDetailPagePro
</table> </table>
); );
const primaryVariant = product.variants?.[0]; const matchedVariant = pickVariant(product, variantKey);
const primaryImage = product.images?.[0]?.image_url || '/images/placeholder-product.webp'; 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 resolvedImageUrl = getImageUrl(primaryImage);
const variantOfferUrl = activeVariant?.sku
? `${SITE_URL}/products/${product.slug}?variant=${encodeURIComponent(activeVariant.sku)}`
: `${SITE_URL}/products/${product.slug}`;
const jsonLd = { const jsonLd = {
'@context': 'https://schema.org/', '@context': 'https://schema.org/',
'@type': 'Product', '@type': 'Product',
name: product.name, name: displayTitle,
image: [resolvedImageUrl], image: [resolvedImageUrl],
description: product.seo_description || product.description || `${product.name} with certified warranty at iFixKart.`, description: product.seo_description || product.description || `${displayTitle} with certified warranty at iFixKart.`,
sku: primaryVariant?.sku || String(product.product_id), sku: activeVariant?.sku || String(product.product_id),
mpn: primaryVariant?.barcode || primaryVariant?.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: { brand: {
'@type': 'Brand', '@type': 'Brand',
name: product.brand?.name || 'iFixKart', name: product.brand?.name || 'iFixKart',
}, },
offers: { offers: {
'@type': 'Offer', '@type': 'Offer',
url: `https://ifixkart.trionixsolution.com/products/${product.slug}`, url: variantOfferUrl,
priceCurrency: 'INR', priceCurrency: 'INR',
price: primaryVariant?.price || 0, price: activeVariant?.price || 0,
priceValidUntil: '2027-12-31', priceValidUntil: '2027-12-31',
itemCondition: 'https://schema.org/NewCondition', 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/InStock'
: 'https://schema.org/OutOfStock', : 'https://schema.org/OutOfStock',
seller: { seller: {
@ -445,6 +537,7 @@ export default async function ProductDetailPage({ params }: ProductDetailPagePro
product={product} product={product}
initialReviewsCount={reviews.length} initialReviewsCount={reviews.length}
relatedProducts={related} relatedProducts={related}
initialVariantSku={activeVariant?.sku}
/> />
<div className="mt-10"> <div className="mt-10">

71
app/sitemap.ts Normal file
View 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;
}

View file

@ -1,20 +1,59 @@
"use client"; "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 { ChevronUp } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion'; 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 = () => { export const FloatingButtons: React.FC = () => {
const [showScrollTop, setShowScrollTop] = useState(false); 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(() => { useEffect(() => {
const handleScroll = () => { const handleScroll = () => {
setShowScrollTop(window.scrollY > 400); setShowScrollTop(window.scrollY > 400);
measure();
}; };
window.addEventListener('scroll', handleScroll); handleScroll();
return () => window.removeEventListener('scroll', 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 = () => { const scrollToTop = () => {
window.scrollTo({ window.scrollTo({
@ -24,9 +63,14 @@ export const FloatingButtons: React.FC = () => {
}; };
return ( return (
<div className="fixed bottom-6 right-6 z-50 flex flex-col items-center gap-3"> <div
className="fixed right-6 z-50 hidden sm:flex flex-col items-center gap-3"
{/* Scroll to Top */} 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> <AnimatePresence>
{showScrollTop && ( {showScrollTop && (
<motion.button <motion.button
@ -45,4 +89,3 @@ export const FloatingButtons: React.FC = () => {
</div> </div>
); );
}; };

View file

@ -31,11 +31,22 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
return () => document.removeEventListener('keydown', handleKeyDown); return () => document.removeEventListener('keydown', handleKeyDown);
}, [isOpen, onClose]); }, [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 = [ const links = [
{ name: 'Home', href: '/' }, { name: 'Home', href: '/' },
{ name: 'Shop', href: '/shop' }, { name: 'Shop', href: '/shop' },
{ name: 'Services', href: '/service' }, { name: 'Top Deals', href: '/shop?tag=deals' },
{ name: 'Top Deals', href: '/shop' }, { name: 'Services', href: '/services' },
]; ];
return ( return (
@ -57,7 +68,7 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
animate={{ x: 0 }} animate={{ x: 0 }}
exit={{ x: '-100%' }} exit={{ x: '-100%' }}
transition={{ type: 'tween', duration: 0.3 }} 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> <div>
{/* Header */} {/* Header */}
@ -67,9 +78,10 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
</span> </span>
<button <button
onClick={onClose} 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> </button>
</div> </div>
@ -113,8 +125,8 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
)} )}
</div> </div>
{/* Footer */} {/* Footer — honors iOS home indicator / Android gesture bar */}
<div className="p-4 border-t border-gray-100 text-xs text-gray-400 text-center font-medium bg-gray-50"> <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. © {new Date().getFullYear()} iFixKart. All Rights Reserved.
</div> </div>
</motion.div> </motion.div>

View file

@ -242,7 +242,7 @@ export const QuickViewModal: React.FC<QuickViewModalProps> = ({
<div <div
onClick={(e) => e.stopPropagation()} 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 <button
type="button" type="button"

View file

@ -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[] { function mapProducts(products: ProductCardResponse[]): RatedItem[] {
return products.slice(0, 6).map((p) => ({ return products.slice(0, 6).map((p) => ({
id: p.product_id, 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" 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"> <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 ? ( <CategoryItemIcon src={item.image} alt={item.name} />
<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" />
)}
</span> </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"> <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} {item.name}

View file

@ -52,7 +52,7 @@ export const WishlistModal: React.FC<WishlistModalProps> = ({ onClose }) => {
> >
<div <div
onClick={(e) => e.stopPropagation()} 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 */} {/* Header */}
<div className="bg-[#1E1E1E] text-white px-7 py-4 flex items-center justify-between"> <div className="bg-[#1E1E1E] text-white px-7 py-4 flex items-center justify-between">

View file

@ -57,6 +57,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [csrfToken, setCsrfToken] = useState(''); const [csrfToken, setCsrfToken] = useState('');
const [fetchingCsrf, setFetchingCsrf] = useState(false);
const [mode, setMode] = useState<'login' | 'link'>('login'); const [mode, setMode] = useState<'login' | 'link'>('login');
const [linkEmail, setLinkEmail] = useState(''); const [linkEmail, setLinkEmail] = useState('');
const [linkPassword, setLinkPassword] = useState(''); const [linkPassword, setLinkPassword] = useState('');
@ -64,21 +65,36 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
const setAuth = useAuthStore((state) => state.setAuth); 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(() => { useEffect(() => {
if (!isOpen) return; if (!isOpen) return;
const prev = document.body.style.overflow; const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden'; document.body.style.overflow = 'hidden';
const array = new Uint32Array(4); // Fetch HMAC-signed CSRF state token from backend
if (typeof window !== 'undefined' && window.crypto) { fetchCsrfToken();
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)
);
}
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose(); if (e.key === 'Escape') onClose();
@ -99,7 +115,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
} }
}, [isOpen]); }, [isOpen]);
const handleAuthCodeSubmit = async (code: string) => { const handleAuthCodeSubmit = async (code: string, returnedState?: string) => {
setLoading(true); setLoading(true);
setError(null); setError(null);
try { try {
@ -108,6 +124,8 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
? localStorage.getItem('guest_session_id') || undefined ? localStorage.getItem('guest_session_id') || undefined
: undefined; : undefined;
const stateToSend = returnedState || csrfToken;
const res = await fetch(`${API_BASE_URL}/api/v1/customer/auth/google`, { const res = await fetch(`${API_BASE_URL}/api/v1/customer/auth/google`, {
method: 'POST', method: 'POST',
headers: { headers: {
@ -117,7 +135,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
credentials: 'include', credentials: 'include',
body: JSON.stringify({ body: JSON.stringify({
code, code,
state: csrfToken, state: stateToSend,
guest_session_id: guestSessionId, guest_session_id: guestSessionId,
redirect_uri: 'postmessage', redirect_uri: 'postmessage',
}), }),
@ -147,6 +165,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
onClose(); onClose();
} catch (err: any) { } catch (err: any) {
setError(err.message || 'Google authentication failed. Please try again.'); setError(err.message || 'Google authentication failed. Please try again.');
fetchCsrfToken();
} finally { } finally {
setLoading(false); 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({ const googleLogin = useGoogleLogin({
onSuccess: (codeResponse) => { onSuccess: (codeResponse) => {
if (codeResponse.code) handleAuthCodeSubmit(codeResponse.code); if (codeResponse.code) handleAuthCodeSubmit(codeResponse.code, codeResponse.state);
}, },
onError: () => { onError: () => {
setError('Google Login popup was closed or authentication failed.'); setError('Google Login popup was closed or authentication failed.');
fetchCsrfToken();
}, },
flow: 'auth-code', flow: 'auth-code',
state: csrfToken, state: csrfToken,
@ -305,12 +338,12 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
<button <button
type="button" type="button"
onClick={() => googleLogin()} onClick={handleGoogleClick}
disabled={loading} 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" 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 /> <GoogleIcon />
{loading ? 'Connecting Google...' : 'Continue with Google'} {loading ? 'Connecting Google...' : fetchingCsrf ? 'Securing session...' : 'Continue with Google'}
</button> </button>
</> </>
) : ( ) : (

View file

@ -368,16 +368,18 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) {
return ( return (
<div <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" 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"> <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 <BlurHashImage
src={primaryImage} src={primaryImage}
alt={p.name} alt={p.name}
fill fill
className="object-contain p-2 group-hover:scale-105 transition-transform duration-300" className="object-contain p-2 group-hover:scale-105 transition-transform duration-300"
/> />
</Link>
{p.badge && ( {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"> <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} {p.badge}
@ -411,7 +413,7 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) {
<div className="flex-1 flex flex-col justify-between"> <div className="flex-1 flex flex-col justify-between">
<div> <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"> <h4 className="text-xs font-bold text-gray-900 hover:text-red-600 transition-colors line-clamp-2 mb-2">
{p.name} {p.name}
</h4> </h4>

View file

@ -81,12 +81,13 @@ function CatalogProductCard({
const compareList = useCartStore((s) => s.compareList) || []; const compareList = useCartStore((s) => s.compareList) || [];
const variant = product.variants?.[0]; const variant = product.variants?.[0];
const productUrl = product.variant_url || `/products/${product.slug}`;
const { price, oldPrice, discount: mappedDiscount } = getCatalogPriceInfo(product); const { price, oldPrice, discount: mappedDiscount } = getCatalogPriceInfo(product);
const compare = oldPrice || 0; const compare = oldPrice || 0;
const discount = const discount =
mappedDiscount || mappedDiscount ||
(compare > price ? Math.round(((compare - price) / compare) * 100) : 0); (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 rating = getDisplayStarCount(product);
const isWishlisted = wishlist.some((i) => i.product_id === product.product_id); const isWishlisted = wishlist.some((i) => i.product_id === product.product_id);
const isCompared = compareList.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(); e.stopPropagation();
if (!variant) return; if (!variant) return;
if (hasOptions) { if (hasOptions) {
window.location.href = `/products/${product.slug}`; window.location.href = productUrl;
return; return;
} }
void addToCart(product, variant, 1); void addToCart(product, variant, 1);
@ -107,7 +108,7 @@ function CatalogProductCard({
if (viewMode === 'list') { if (viewMode === 'list') {
return ( return (
<div className="flex gap-5 p-5 border-b border-[#e8e8e8] bg-white hover:bg-[#fafafa] transition-colors group"> <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 && ( {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"> <span className="absolute top-0 right-0 z-10 bg-primary text-white text-[10px] font-bold px-1.5 py-0.5">
-{discount}% -{discount}%
@ -121,7 +122,7 @@ function CatalogProductCard({
</Link> </Link>
<div className="flex-1 min-w-0 flex flex-col justify-center"> <div className="flex-1 min-w-0 flex flex-col justify-center">
<Link <Link
href={`/products/${product.slug}`} href={productUrl}
className="text-[14px] font-semibold text-[#222] hover:text-primary line-clamp-2 mb-1.5" className="text-[14px] font-semibold text-[#222] hover:text-primary line-clamp-2 mb-1.5"
> >
{product.name} {product.name}
@ -215,7 +216,7 @@ function CatalogProductCard({
</div> </div>
<Link <Link
href={`/products/${product.slug}`} href={productUrl}
className="relative flex-1 flex items-center justify-center min-h-[160px] mb-3" className="relative flex-1 flex items-center justify-center min-h-[160px] mb-3"
> >
{image ? ( {image ? (
@ -233,7 +234,7 @@ function CatalogProductCard({
<div className="text-left mt-auto"> <div className="text-left mt-auto">
<Link <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" className="block text-[13px] font-semibold text-[#222] hover:text-primary line-clamp-2 leading-snug min-h-[36px] mb-1.5"
> >
{product.name} {product.name}
@ -400,7 +401,11 @@ export function StandardCatalog({
}; };
if (selectedCategory !== 'all') paramsBase.category = selectedCategory; if (selectedCategory !== 'all') paramsBase.category = selectedCategory;
if (selectedBrand !== 'all') paramsBase.brand = selectedBrand; 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 accumulated: ProductResponse[] = [];
const seen = new Set<string>(); const seen = new Set<string>();
@ -421,8 +426,10 @@ export function StandardCatalog({
let added = 0; let added = 0;
for (const product of mapped) { for (const product of mapped) {
if (seen.has(product.product_id)) continue; // Variant-expanded cards share the same product_id — dedupe per variant
seen.add(product.product_id); const dedupeKey = product.variant_url || product.product_id;
if (seen.has(dedupeKey)) continue;
seen.add(dedupeKey);
accumulated.push(product); accumulated.push(product);
added += 1; added += 1;
} }
@ -753,13 +760,13 @@ export function StandardCatalog({
) : viewMode === 'grid' ? ( ) : 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"> <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) => ( {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>
) : ( ) : (
<div className="border border-[#e8e8e8] rounded-sm overflow-hidden"> <div className="border border-[#e8e8e8] rounded-sm overflow-hidden">
{displayed.map((p) => ( {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> </div>
)} )}

View file

@ -18,7 +18,10 @@ export function CompareBar() {
if (!hydrated || pathname === '/compare' || compareList.length === 0) return null; if (!hydrated || pathname === '/compare' || compareList.length === 0) return null;
return ( 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="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="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"> <div className="w-9 h-9 rounded-lg bg-primary/10 text-primary flex items-center justify-center">

View file

@ -33,6 +33,7 @@ interface ProductInteractiveGridProps {
product: ProductResponse; product: ProductResponse;
initialReviewsCount: number; initialReviewsCount: number;
relatedProducts?: ProductResponse[]; relatedProducts?: ProductResponse[];
initialVariantSku?: string;
} }
const FALLBACK_TECH_IMAGES: string[] = ['/images/placeholder-product.webp']; const FALLBACK_TECH_IMAGES: string[] = ['/images/placeholder-product.webp'];
@ -84,13 +85,26 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
product, product,
initialReviewsCount, initialReviewsCount,
relatedProducts = [], relatedProducts = [],
initialVariantSku,
}) => { }) => {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const router = useRouter(); 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 [failedImages, setFailedImages] = useState<Set<string>>(new Set());
const [selectedImage, setSelectedImage] = useState<string>(() => resolveInitialImage(product, 0)); const [selectedVariantIndex, setSelectedVariantIndex] = useState<number>(getInitialIndex);
const [selectedVariantIndex, setSelectedVariantIndex] = useState(0); const [selectedImage, setSelectedImage] = useState<string>(() => resolveInitialImage(product, getInitialIndex()));
const [quantity, setQuantity] = useState(1); const [quantity, setQuantity] = useState(1);
const [added, setAdded] = useState(false); const [added, setAdded] = useState(false);
const [selections, setSelections] = useState<Record<string, string>>({}); const [selections, setSelections] = useState<Record<string, string>>({});
@ -113,6 +127,30 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
variantAttrsMap: Map<string, Map<string, string>>; variantAttrsMap: Map<string, Map<string, string>>;
validValuesByDimension: Map<string, Set<string>>; validValuesByDimension: Map<string, Set<string>>;
} | null>(null); } | 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 // Initialize lookup maps and default state on mount/product change
useEffect(() => { useEffect(() => {
@ -135,13 +173,30 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
lookupIndex.current = { variantAttrsMap, validValuesByDimension }; lookupIndex.current = { variantAttrsMap, validValuesByDimension };
// Select variant based on URL params or default to first index // Select variant based on URL params or default to first index.
const urlVariantId = searchParams.get('variant'); // `?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'); 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) { if (activeIdx === -1) {
activeIdx = 0; 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); setSelectedVariantIndex(activeIdx);
setSelectedImage(resolveInitialImage(product, activeIdx, failedImages)); setSelectedImage(resolveInitialImage(product, activeIdx, failedImages));
@ -154,7 +209,7 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
}); });
} }
setSelections(initial); setSelections(initial);
}, [product, searchParams]); }, [product, searchParams, initialVariantSku]);
useEffect(() => { useEffect(() => {
const named = (product as ProductResponse & { brand_name?: string }).brand_name; const named = (product as ProductResponse & { brand_name?: string }).brand_name;
@ -625,6 +680,7 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
if (varImg) { if (varImg) {
setSelectedImage(getImageUrl(varImg)); setSelectedImage(getImageUrl(varImg));
} }
syncVariantUrl(match);
} }
}} }}
className={`px-3 py-1.5 rounded text-[12px] font-semibold transition border cursor-pointer ${ 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) { if (varImg) {
setSelectedImage(getImageUrl(varImg)); setSelectedImage(getImageUrl(varImg));
} }
syncVariantUrl(v);
}} }}
className={`px-3 py-1.5 rounded text-[12px] font-semibold transition border cursor-pointer ${isSelected 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' ? 'border-primary bg-primary/10 text-primary font-bold shadow-xs'

View file

@ -12,12 +12,29 @@ import Image from 'next/image';
import { Loader2, X, ChevronDown, Check, LayoutGrid, Search } from 'lucide-react'; import { Loader2, X, ChevronDown, Check, LayoutGrid, Search } from 'lucide-react';
import { storefrontService, LiveSearchResult } from '@/services/api/storefrontService'; import { storefrontService, LiveSearchResult } from '@/services/api/storefrontService';
import { catalogService, CategoryResponse } from '@/services/api/catalogService'; import { catalogService, CategoryResponse } from '@/services/api/catalogService';
import { getImageUrl } from '@/lib/utils'; import { formatCurrency, getImageUrl } from '@/lib/utils';
import { import {
getCategoryMenuItems, getCategoryMenuItems,
menuItemCategoryParam, menuItemCategoryParam,
} from '@/components/CategorySidebar'; } 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() { export function LiveSearch() {
const router = useRouter(); const router = useRouter();
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
@ -282,20 +299,21 @@ export function LiveSearch() {
{!loading && hasResults && ( {!loading && hasResults && (
<div className="p-2 divide-y divide-gray-100 text-xs"> <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 <Link
key={product.product_id} key={(product as any).variant_sku || (product as any).variant_url || product.product_id}
href={`/products/${product.slug}`} href={(product as any).variant_url || `/products/${product.slug}`}
onClick={() => setIsOpen(false)} onClick={() => setIsOpen(false)}
className="flex items-center gap-3 p-2 hover:bg-gray-50 rounded-md transition-colors" 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"> <div className="relative w-10 h-10 rounded border border-gray-100 overflow-hidden bg-gray-50 shrink-0">
{product.images[0]?.image_url ? ( {imgUrl ? (
<Image <SearchItemImage
src={getImageUrl(product.images[0].image_url)} src={getImageUrl(imgUrl)}
alt={product.name} alt={product.name}
fill
className="object-cover"
/> />
) : ( ) : (
<div className="w-full h-full bg-gray-100" /> <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="flex-1 min-w-0">
<div className="font-semibold text-gray-800 truncate">{product.name}</div> <div className="font-semibold text-gray-800 truncate">{product.name}</div>
<div className="text-xs text-[#1877f2] font-bold"> <div className="text-xs text-[#1877f2] font-bold">
₹{Number(product.variants[0]?.price || 0).toFixed(2)} {formatCurrency(price)}
</div> </div>
</div> </div>
</Link> </Link>
))} );
})}
</div> </div>
)} )}
</div> </div>

View file

@ -34,6 +34,7 @@ export function ProductCard({ product }: ProductCardProps) {
const primaryVariant = product.variants[0]; const primaryVariant = product.variants[0];
const primaryImage = getImageUrl(product.images[0]?.image_url); const primaryImage = getImageUrl(product.images[0]?.image_url);
const secondaryImage = getImageUrl(product.images[1]?.image_url) || primaryImage; 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 price = Number(primaryVariant?.price || 0);
const comparePrice = primaryVariant?.compare_price != null ? Number(primaryVariant.compare_price) : null; const comparePrice = primaryVariant?.compare_price != null ? Number(primaryVariant.compare_price) : null;
@ -107,7 +108,7 @@ export function ProductCard({ product }: ProductCardProps) {
</div> </div>
{/* Image Gallery Flip Container */} {/* 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 <BlurHashImage
src={primaryImage} src={primaryImage}
blurHash={(product as any).blur_hash || null} blurHash={(product as any).blur_hash || null}
@ -138,7 +139,7 @@ export function ProductCard({ product }: ProductCardProps) {
{/* Title */} {/* Title */}
<Link <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" className="text-xs font-bold text-[#1b2559] hover:text-[#e4382f] transition-colors line-clamp-2 leading-snug mb-2"
> >
{product.name} {product.name}

View file

@ -25,7 +25,7 @@ export const Header: React.FC = () => {
return ( return (
<header <header
data-storefront-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 isSticky
? 'fixed top-0 left-0 right-0 shadow-md py-2.5' ? 'fixed top-0 left-0 right-0 shadow-md py-2.5'
: 'relative pt-6 pb-4 shadow-2xs' : 'relative pt-6 pb-4 shadow-2xs'
@ -36,10 +36,10 @@ export const Header: React.FC = () => {
href="/" href="/"
className="flex items-center select-none tracking-tighter hover:opacity-95 transition-opacity" 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 iFix
</span> </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 Kart
</span> </span>
</Link> </Link>

View file

@ -45,7 +45,7 @@ export const HeaderActions: React.FC = () => {
<button <button
onClick={triggerMobileDrawer} 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" aria-label="Open Menu"
> >
<Menu size={24} className="stroke-[2.5]" /> <Menu size={24} className="stroke-[2.5]" />
@ -53,7 +53,7 @@ export const HeaderActions: React.FC = () => {
<Link <Link
href="/compare" 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" aria-label="Compare products"
> >
<GitCompare <GitCompare
@ -113,7 +113,7 @@ export const HeaderActions: React.FC = () => {
initial={{ opacity: 0, height: 0 }} initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }} animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }} 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"> <div className="flex gap-2 items-center relative z-55">
<LiveSearch /> <LiveSearch />

View file

@ -9,7 +9,7 @@ const nextConfig: NextConfig = {
}, },
async rewrites() { async rewrites() {
const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'https://ifixkartbe.trionixsolution.com'; 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 [ return [
{ {
source: '/api/v1/:path*', source: '/api/v1/:path*',

View file

@ -130,6 +130,9 @@ export interface ProductResponse {
device_type?: string | null; device_type?: string | null;
mapped_service_category_id?: string | null; mapped_service_category_id?: string | null;
is_service_booking?: boolean; 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 { export interface DeviceModelResponse {
@ -179,6 +182,10 @@ export interface ProductCardResponse {
brand_name: string | null; brand_name: string | null;
color?: string | null; color?: string | null;
colors?: string[]; colors?: string[];
/** Variant-expanded search cards (expand_variants=true) */
variant_sku?: string | null;
variant_name?: string | null;
variant_url?: string | null;
} }
export interface ProductPaginatedResponse { export interface ProductPaginatedResponse {
@ -221,6 +228,9 @@ export const catalogService = {
async getProductsPaginated(params: Record<string, any> = {}): Promise<ProductPaginatedResponse> { async getProductsPaginated(params: Record<string, any> = {}): Promise<ProductPaginatedResponse> {
const query = new URLSearchParams(); const query = new URLSearchParams();
if (!('expand_variants' in params)) {
query.append('expand_variants', 'true');
}
Object.entries(params).forEach(([key, val]) => { Object.entries(params).forEach(([key, val]) => {
if (val !== undefined && val !== null && val !== '') { if (val !== undefined && val !== null && val !== '') {
query.append(key, String(val)); query.append(key, String(val));

View file

@ -121,7 +121,11 @@ export const storefrontService = {
} }
try { 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 { } catch {
try { try {
const res = await catalogService.getProductsPaginated({ const res = await catalogService.getProductsPaginated({

View file

@ -11,6 +11,17 @@ a,
} }
/* 2. Responsive viewports & safe area overrides */ /* 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) { @media (max-width: 767px) {
/* Selective backdrop-filter resets for slow scroll frame performance */ /* Selective backdrop-filter resets for slow scroll frame performance */
.mobile-sticky-header, .mobile-sticky-header,

View file

@ -33,7 +33,9 @@ export function mapProductCardToProductResponse(
{ {
variant_id: p.first_variant_id || p.product_id, variant_id: p.first_variant_id || p.product_id,
product_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, barcode: null,
price, price,
compare_price: comparePrice && comparePrice > 0 ? comparePrice : null, compare_price: comparePrice && comparePrice > 0 ? comparePrice : null,
@ -61,7 +63,9 @@ export function mapProductCardToProductResponse(
device_model_id: (p as any).device_model_id || null, device_model_id: (p as any).device_model_id || null,
name: p.name, name: p.name,
slug: p.slug, 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, description: (p as any).description ?? null,
status: (p as any).status || 'active', status: (p as any).status || 'active',
created_at: (p as any).created_at || '', created_at: (p as any).created_at || '',