Compare commits

..

No commits in common. "main" and "robin" have entirely different histories.
main ... robin

74 changed files with 1046 additions and 4922 deletions

View file

@ -19,19 +19,16 @@ import {
export default function AboutPage() {
const [footer, setFooter] = useState<FooterInfo>(MOCK_FOOTER_INFO);
const [settings, setSettings] = useState<StorefrontSettings>({ store_name: 'iFixKart' });
const [layoutSections, setLayoutSections] = useState<any[]>([]);
useEffect(() => {
let cancelled = false;
Promise.all([
storefrontService.getFooterInfo(),
storefrontService.getSettings(),
storefrontService.getPageLayout('about'),
]).then(([info, store, layout]) => {
]).then(([info, store]) => {
if (cancelled) return;
if (info) setFooter(info);
if (store) setSettings(store);
if (layout && layout.length > 0) setLayoutSections(layout);
});
return () => {
cancelled = true;
@ -39,32 +36,9 @@ export default function AboutPage() {
}, []);
const storeName = settings.store_name || 'iFixKart';
const heroSec = layoutSections.find((s) => s.region === 'about_hero' || s.type === 'about_hero');
const featuresSec = layoutSections.find((s) => s.region === 'about_features' || s.type === 'about_features');
const contactSec = layoutSections.find((s) => s.region === 'about_contact' || s.type === 'about_contact');
const pageTitle = heroSec?.title || 'About Us';
const pageSubtitle = heroSec?.subtitle || '';
const heroMeta = heroSec?.metadata || heroSec?.metadata_json || {};
const storyParagraphs: string[] = Array.isArray(heroMeta.story_paragraphs) && heroMeta.story_paragraphs.length > 0
? heroMeta.story_paragraphs
: [
`${storeName} sells tested refurbished phones and accessories, and books device repairs. You can shop online, get a screen or battery replaced, or exchange the phone you already have.`,
`Repairs are done at our Bengaluru service center or at your doorstep. Refurbished phones are checked before listing and sold with a limited warranty.`,
];
const featureCards: any[] = Array.isArray(featuresSec?.metadata?.cards || featuresSec?.metadata_json?.cards) && (featuresSec?.metadata?.cards || featuresSec?.metadata_json?.cards).length > 0
? (featuresSec?.metadata?.cards || featuresSec?.metadata_json?.cards)
: [
{ id: '1', title: 'Shop', desc: 'Refurbished phones, spare parts, and accessories.', link: '/shop', icon: 'smartphone' },
{ id: '2', title: 'Repair', desc: 'Screens, batteries, charging ports, and other common jobs.', link: '/repair-services', icon: 'wrench' },
];
const contactMeta = contactSec?.metadata || contactSec?.metadata_json || {};
const phone = contactMeta.phone || footer.phone || settings.support_phone || '';
const email = contactMeta.email || footer.email || '';
const address = contactMeta.address || footer.address || '';
const hours = contactMeta.hours || '';
const phone = footer.phone || settings.support_phone || '';
const email = footer.email || '';
const address = footer.address || '';
return (
<div className="min-h-screen bg-[#F8F9FB] text-[#1E293B] flex flex-col font-sans">
@ -76,42 +50,39 @@ export default function AboutPage() {
<main className="flex-grow py-10 pb-20">
<div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-[860px]">
<h1 className="text-[28px] md:text-[32px] font-bold text-[#1E293B]">
{pageTitle}
About Us
</h1>
{pageSubtitle ? (
<p className="text-[16px] text-primary font-medium mt-1">
{pageSubtitle}
</p>
) : null}
<p className="text-[15px] text-gray-600 leading-relaxed mt-3">
{storeName} sells tested refurbished phones and accessories, and books device repairs.
You can shop online, get a screen or battery replaced, or exchange the phone you
already have.
</p>
<p className="text-[15px] text-gray-600 leading-relaxed mt-3">
Repairs are done at our Bengaluru service center or at your doorstep. Refurbished
phones are checked before listing and sold with a limited warranty.
</p>
{storyParagraphs.map((para, i) => (
<p key={i} className="text-[15px] text-gray-600 leading-relaxed mt-3">
{para}
</p>
))}
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 mt-8">
{featureCards.map((card, i) => {
const isRepair = (card.icon || '').toLowerCase().includes('wrench') || (card.title || '').toLowerCase().includes('repair');
const to = card.link || (isRepair ? '/repair-services' : '/shop');
return (
<Link
key={card.id || i}
href={to}
className="bg-white border border-gray-200 rounded-xl p-5 hover:border-primary/40 hover:shadow-sm transition-all"
>
{isRepair ? (
<Wrench className="w-5 h-5 text-primary mb-3" />
) : (
<Smartphone className="w-5 h-5 text-primary mb-3" />
)}
<h2 className="text-[16px] font-bold text-[#1E293B]">{card.title}</h2>
<p className="text-[13px] text-gray-500 mt-1 leading-relaxed">
{card.desc}
</p>
</Link>
);
})}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-8">
<Link
href="/shop"
className="bg-white border border-gray-200 rounded-xl p-5 hover:border-primary/40 transition-colors"
>
<Smartphone className="w-5 h-5 text-primary mb-3" />
<h2 className="text-[16px] font-bold text-[#1E293B]">Shop</h2>
<p className="text-[13px] text-gray-500 mt-1 leading-relaxed">
Refurbished phones, spare parts, and accessories.
</p>
</Link>
<Link
href="/repair-services"
className="bg-white border border-gray-200 rounded-xl p-5 hover:border-primary/40 transition-colors"
>
<Wrench className="w-5 h-5 text-primary mb-3" />
<h2 className="text-[16px] font-bold text-[#1E293B]">Repair</h2>
<p className="text-[13px] text-gray-500 mt-1 leading-relaxed">
Screens, batteries, charging ports, and other common jobs.
</p>
</Link>
</div>
<div className="mt-8 bg-white border border-gray-200 rounded-xl p-5 md:p-6 space-y-4">
@ -121,12 +92,6 @@ export default function AboutPage() {
<p className="text-[14px] text-gray-600 leading-relaxed">{address}</p>
</div>
) : null}
{hours ? (
<div className="flex gap-3 text-[14px] text-gray-600">
<span className="w-4 h-4 text-gray-400 mt-0.5 shrink-0 font-bold text-center">⏱</span>
<p className="text-[14px] text-gray-600 leading-relaxed">{hours}</p>
</div>
) : null}
{phone ? (
<a
href={`tel:${phone.replace(/[^\d+]/g, '')}`}

View file

@ -19,21 +19,13 @@ import {
Trash2,
Check,
ShieldCheck,
Shield,
ShoppingBag,
Loader2,
KeyRound,
X,
Wallet,
Clock,
Coins,
Sparkles,
ArrowUpRight,
ArrowDownRight,
} from 'lucide-react';
import { useAuthStore } from '@/store/authStore';
import { apiFetch, clearTokens } from '@/services/api/client';
import { creditService, WalletSummary } from '@/services/api/creditService';
import { formatCurrency } from '@/lib/utils';
import GoogleAuthModal from '@/components/auth/GoogleAuthModal';
import { AnnouncementBar } from '@/layout/AnnouncementBar';
@ -45,14 +37,12 @@ import { PhoneInput, PincodeInput } from '@/components/PhoneInput';
import { validatePhone, validatePincode, validateAddress } from '@/lib/validation';
import { FloatingButtons } from '@/components/FloatingButtons';
type TabType = 'dashboard' | 'orders' | 'wallet' | 'addresses' | 'warranties' | 'settings';
type TabType = 'dashboard' | 'orders' | 'addresses' | 'settings';
const VALID_TABS: TabType[] = [
'dashboard',
'orders',
'wallet',
'addresses',
'warranties',
'settings',
];
@ -80,28 +70,12 @@ interface Order {
status: string;
payment_status: string;
created_at: string;
logistics_provider?: string;
tracking_number?: string;
courier_name?: string;
}
interface Warranty {
warranty_id: string;
reference_type: string;
reference_id: string;
serial_no_imei?: string;
start_date: string;
end_date: string;
status: string;
warranty_type: string;
}
const TABS: { id: TabType; label: string; icon: any }[] = [
const TABS: { id: TabType; label: string; icon: typeof User }[] = [
{ id: 'dashboard', label: 'Dashboard', icon: User },
{ id: 'orders', label: 'Order History', icon: Package },
{ id: 'wallet', label: 'Store Credits & Wallet', icon: Wallet },
{ id: 'addresses', label: 'Address Book', icon: MapPin },
{ id: 'warranties', label: 'My Warranties', icon: ShieldCheck },
{ id: 'settings', label: 'Settings', icon: Settings },
];
@ -128,9 +102,7 @@ function AccountDashboardPage() {
const [profile, setProfile] = useState<any>(null);
const [addresses, setAddresses] = useState<Address[]>([]);
const [warranties, setWarranties] = useState<Warranty[]>([]);
const [orders, setOrders] = useState<Order[]>([]);
const [wallet, setWallet] = useState<WalletSummary | null>(null);
const [loading, setLoading] = useState(true);
const [addressModalOpen, setAddressModalOpen] = useState(false);
@ -199,12 +171,6 @@ function AccountDashboardPage() {
const ords = await apiFetch<Order[]>('/api/v1/orders');
setOrders(ords);
const warrs = await apiFetch<Warranty[]>('/api/v1/warranties');
setWarranties(warrs);
const walletData = await creditService.getMyWallet().catch(() => null);
setWallet(walletData);
} catch (err: any) {
console.error(err);
setErrorMsg(err.message || 'Failed to retrieve account records.');
@ -548,35 +514,7 @@ function AccountDashboardPage() {
manage your account here.
</p>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="border border-[#e5e5e5] p-5 flex flex-col justify-between min-h-[160px] bg-gradient-to-br from-white to-emerald-50/30">
<div>
<div className="flex items-center justify-between mb-2">
<span className="text-[11px] font-semibold text-[#888] uppercase tracking-wide">
Store Credits
</span>
<span className="text-[9px] font-bold bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full uppercase">
Spendable
</span>
</div>
<p className="text-[24px] font-black text-emerald-700 tracking-tight">
{formatCurrency(wallet?.active_balance || 0)}
</p>
{Boolean(wallet?.pending_balance && wallet.pending_balance > 0) && (
<p className="text-[12px] text-amber-700 font-medium mt-1 flex items-center gap-1">
<Clock className="w-3.5 h-3.5 text-amber-600 inline shrink-0" />
{formatCurrency(wallet?.pending_balance || 0)} pending unlock
</p>
)}
</div>
<button
type="button"
onClick={() => goToTab('wallet')}
className="mt-4 text-emerald-700 hover:text-emerald-800 hover:underline text-[13px] font-semibold text-left w-max cursor-pointer flex items-center gap-1"
>
Open My Wallet <ArrowUpRight className="w-3.5 h-3.5" />
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="border border-[#e5e5e5] p-5 flex flex-col justify-between min-h-[160px]">
<div>
<span className="text-[11px] font-semibold text-[#888] uppercase tracking-wide block mb-2.5">
@ -725,20 +663,6 @@ function AccountDashboardPage() {
Cancel
</button>
)}
{order.tracking_number && (
<a
href={
order.logistics_provider === 'DELHIVERY'
? `https://www.delhivery.com/track/package/${order.tracking_number}`
: `https://shiprocket.co/tracking/${order.tracking_number}`
}
target="_blank"
rel="noopener noreferrer"
className="px-3 py-1 border border-primary/30 text-primary hover:bg-primary/5 font-semibold text-[11px] uppercase tracking-wider transition inline-flex items-center gap-1"
>
Track ({order.logistics_provider === 'DELHIVERY' ? 'Delhivery' : 'Shiprocket'})
</a>
)}
</div>
</div>
))}
@ -896,223 +820,6 @@ function AccountDashboardPage() {
</button>
</form>
)}
{/* Store Credits & Wallet Tab */}
{activeTab === 'wallet' && (
<div className="space-y-6">
{/* Metric Stat Cards */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="border border-emerald-200/90 bg-gradient-to-br from-emerald-50/70 via-emerald-50/30 to-white p-5 rounded-lg">
<div className="flex items-center justify-between mb-2">
<span className="text-[11px] font-bold text-emerald-800 uppercase tracking-wider">
Spendable Credits
</span>
<div className="p-1.5 bg-emerald-100 rounded-md text-emerald-700">
<Wallet className="w-4 h-4" />
</div>
</div>
<p className="text-[26px] font-black text-emerald-700 tracking-tight">
{formatCurrency(wallet?.active_balance || 0)}
</p>
<p className="text-[11px] text-emerald-600 font-medium mt-1">
✓ Ready to apply at checkout
</p>
</div>
<div className="border border-amber-200/90 bg-gradient-to-br from-amber-50/70 via-amber-50/30 to-white p-5 rounded-lg">
<div className="flex items-center justify-between mb-2">
<span className="text-[11px] font-bold text-amber-800 uppercase tracking-wider">
Pending Credits
</span>
<div className="p-1.5 bg-amber-100 rounded-md text-amber-700">
<Clock className="w-4 h-4" />
</div>
</div>
<p className="text-[26px] font-black text-amber-700 tracking-tight">
{formatCurrency(wallet?.pending_balance || 0)}
</p>
<p className="text-[11px] text-amber-600 font-medium mt-1">
⏳ Locked during return window
</p>
</div>
<div className="border border-blue-200/90 bg-gradient-to-br from-blue-50/70 via-blue-50/30 to-white p-5 rounded-lg">
<div className="flex items-center justify-between mb-2">
<span className="text-[11px] font-bold text-blue-800 uppercase tracking-wider">
Lifetime Earned
</span>
<div className="p-1.5 bg-blue-100 rounded-md text-blue-700">
<Coins className="w-4 h-4" />
</div>
</div>
<p className="text-[26px] font-black text-blue-700 tracking-tight">
{formatCurrency(wallet?.lifetime_earned || 0)}
</p>
<p className="text-[11px] text-blue-600 font-medium mt-1">
Total rewards accumulated
</p>
</div>
</div>
{/* Educational Cashback Rules Card */}
<div className="border border-[#e5e5e5] bg-[#fafafa] p-5 rounded-lg space-y-3">
<h4 className="text-[13px] font-bold text-[#1a1a1a] flex items-center gap-2">
<Sparkles className="w-4 h-4 text-primary" />
How iFixKart Store Credits Work
</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-[12px] text-gray-600">
<div className="space-y-1">
<p className="font-semibold text-[#1a1a1a]">1. 🛒 Purchases & Services</p>
<p className="leading-relaxed">
You earn 5% Store Credit cashback on all delivered product orders and repair jobs.
</p>
</div>
<div className="space-y-1">
<p className="font-semibold text-[#1a1a1a]">2. ⏳ Return Window Maturation</p>
<p className="leading-relaxed">
Credits remain pending during the active return window (e.g. 7 days for sales, 3 days for repairs).
</p>
</div>
<div className="space-y-1">
<p className="font-semibold text-[#1a1a1a]">3. 🎁 1-Click Checkout Use</p>
<p className="leading-relaxed">
Once the window closes, credits unlock automatically to spendable balance for future checkout orders.
</p>
</div>
</div>
</div>
{/* Transaction Ledger Table */}
<div className="border border-[#e5e5e5] bg-white rounded-lg overflow-hidden">
<div className="px-5 py-3.5 border-b border-[#e5e5e5] bg-gray-50 flex items-center justify-between">
<h4 className="text-[13px] font-bold text-[#1a1a1a]">
Credits Ledger & History
</h4>
<span className="text-[11px] text-gray-500">
{wallet?.transactions?.length || 0} transaction{wallet?.transactions?.length === 1 ? '' : 's'}
</span>
</div>
{!wallet?.transactions || wallet.transactions.length === 0 ? (
<div className="py-12 text-center text-gray-400">
<Wallet className="w-10 h-10 mx-auto text-gray-300 mb-2" />
<p className="text-[13px] font-semibold text-gray-600">No credit activity yet</p>
<p className="text-[12px] text-gray-400 mt-1">
Place an order or complete a repair service to start accumulating store credits!
</p>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-left text-[12px]">
<thead>
<tr className="border-b border-[#e5e5e5] bg-gray-50/50 text-[#666] font-semibold">
<th className="px-4 py-3">Date</th>
<th className="px-4 py-3">Description</th>
<th className="px-4 py-3">Reference</th>
<th className="px-4 py-3">Status</th>
<th className="px-4 py-3">Unlock Date</th>
<th className="px-4 py-3 text-right">Credit Amount</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e5e5e5]">
{wallet.transactions.map((tx) => {
const isCredit = tx.credit_amount > 0;
return (
<tr key={tx.transaction_id} className="hover:bg-gray-50/80 transition-colors">
<td className="px-4 py-3 text-gray-500 whitespace-nowrap">
{tx.created_at ? new Date(tx.created_at).toLocaleDateString() : '—'}
</td>
<td className="px-4 py-3 font-medium text-[#222]">
{tx.description || `${tx.transaction_type} for ${tx.reference_type}`}
</td>
<td className="px-4 py-3 text-gray-600 whitespace-nowrap font-mono text-[11px]">
{tx.reference_no || tx.reference_id}
</td>
<td className="px-4 py-3 whitespace-nowrap">
{tx.status === 'COMPLETED' || tx.status === 'MATURED' ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-100 text-emerald-800">
✓ Active
</span>
) : tx.status === 'PENDING' ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold bg-amber-100 text-amber-800">
⏳ Pending
</span>
) : tx.status === 'VOIDED' ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold bg-red-100 text-red-800">
✕ Voided
</span>
) : (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold bg-gray-100 text-gray-700">
{tx.status}
</span>
)}
</td>
<td className="px-4 py-3 text-gray-500 whitespace-nowrap text-[11px]">
{tx.status === 'PENDING' && tx.matures_at ? (
<span className="text-amber-700 font-medium">
Unlocks {new Date(tx.matures_at).toLocaleDateString()}
</span>
) : tx.status === 'COMPLETED' || tx.status === 'MATURED' ? (
<span className="text-gray-400">Unlocked</span>
) : (
'—'
)}
</td>
<td className={`px-4 py-3 text-right font-bold whitespace-nowrap ${
isCredit ? 'text-emerald-600' : 'text-purple-600'
}`}>
{isCredit ? `+${formatCurrency(tx.credit_amount)}` : formatCurrency(tx.credit_amount)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
</div>
)}
{/* Warranties */}
{activeTab === 'warranties' && (
<div className="space-y-4">
{warranties.length === 0 ? (
<div className="py-14 text-center border border-dashed border-[#e5e5e5]">
<ShieldCheck className="w-10 h-10 mx-auto text-gray-300 mb-3" />
<p className="text-[13px] font-semibold text-[#444]">
No active warranties found.
</p>
<p className="text-[12px] text-gray-500 mt-1">
Warranties for purchased products and repair services will appear here automatically.
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{warranties.map((warr) => (
<div key={warr.warranty_id} className="border border-[#e5e5e5] p-5 rounded-lg space-y-2">
<div className="flex items-center justify-between">
<span className="font-bold text-[#1a1a1a] text-[13px]">
{warr.warranty_type}
</span>
<span className="text-[10px] font-bold px-2 py-0.5 rounded bg-emerald-100 text-emerald-800">
{warr.status}
</span>
</div>
{warr.serial_no_imei && (
<p className="text-[12px] text-gray-600 font-mono">
IMEI / Serial: {warr.serial_no_imei}
</p>
)}
<p className="text-[11px] text-gray-500">
Valid: {new Date(warr.start_date).toLocaleDateString()} – {new Date(warr.end_date).toLocaleDateString()}
</p>
</div>
))}
</div>
)}
</div>
)}
</div>
</div>
</div>
@ -1123,7 +830,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(100dvh-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(100vh-2rem))]"
role="dialog"
aria-modal="true"
aria-labelledby="address-modal-title"

View file

@ -5,11 +5,10 @@
*/
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCartStore } from '@/store/cartStore';
import { formatCurrency, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCurrency, getImageUrl } from '@/lib/utils';
import { requireLoginForCheckout } from '@/lib/requireLoginForCheckout';
import { Header } from '@/layout/Header';
import { Footer } from '@/layout/Footer';
@ -24,15 +23,16 @@ import {
Truck,
Tag,
} from 'lucide-react';
import { deliveryService, DeliverySettings } from '@/services/api/deliveryService';
const FREE_SHIPPING_THRESHOLD = 999;
function resolveItemImage(item: {
product: any;
selectedVariant: any;
product: { images?: { image_url?: string }[]; name?: string };
selectedVariant: { images?: { image_url?: string }[] };
}): string {
const fromVariant = item.selectedVariant?.thumbnail_url || item.selectedVariant?.images?.[0]?.image_url;
if (fromVariant) return getImageUrl(fromVariant);
return resolveProductImage(item.product);
const fromVariant = item.selectedVariant?.images?.[0]?.image_url;
const fromProduct = item.product?.images?.[0]?.image_url;
return getImageUrl(fromVariant || fromProduct || '');
}
export default function CartPage() {
@ -41,27 +41,12 @@ export default function CartPage() {
const removeFromCart = useCartStore((state) => state.removeFromCart);
const updateQuantity = useCartStore((state) => state.updateQuantity);
const getCartTotal = useCartStore((state) => state.getCartTotal);
const [deliverySettings, setDeliverySettings] = useState<DeliverySettings | null>(null);
useEffect(() => {
deliveryService.getDeliverySettings().then(setDeliverySettings).catch(() => {});
}, []);
const subtotal = getCartTotal();
const tax = Math.round((subtotal * (18 / 82)) * 100) / 100;
const grossSubtotal = subtotal + tax;
const isFreeDelivery = Boolean(
deliverySettings?.free_delivery_enabled &&
deliverySettings?.free_delivery_min_order_amount &&
grossSubtotal >= deliverySettings.free_delivery_min_order_amount
);
const baseDeliveryFee = deliverySettings ? deliverySettings.delivery_charge : 99.0;
const shipping = subtotal > 0 ? (isFreeDelivery ? 0 : baseDeliveryFee) : 0;
const total = subtotal + tax + shipping;
const freeThreshold = deliverySettings?.free_delivery_min_order_amount || 999;
const progressPercent = Math.min(100, (grossSubtotal / freeThreshold) * 100);
const amountNeeded = Math.max(0, freeThreshold - grossSubtotal);
const shipping = subtotal > 0 && subtotal < FREE_SHIPPING_THRESHOLD ? 15.0 : 0;
const total = subtotal + shipping;
const progressPercent = Math.min(100, (subtotal / FREE_SHIPPING_THRESHOLD) * 100);
const amountNeeded = Math.max(0, FREE_SHIPPING_THRESHOLD - subtotal);
return (
<div className="w-full min-h-screen bg-[#F8F9FB] flex flex-col">
@ -213,49 +198,41 @@ export default function CartPage() {
Order summary
</h3>
{/* Dynamic Free shipping progress (only when enabled by admin) */}
{deliverySettings?.free_delivery_enabled && (
<div className="rounded-lg bg-primary/5 border border-primary/10 p-3 space-y-2">
<div className="flex items-start gap-2">
<Truck className="w-4 h-4 text-primary shrink-0 mt-0.5" />
<p className="text-[12px] text-gray-600 leading-snug">
{shipping === 0 ? (
<span className="font-semibold text-emerald-600">
You&apos;ve unlocked free shipping!
</span>
) : (
<>
Add{' '}
<span className="font-bold text-primary">
{formatCurrency(amountNeeded)}
</span>{' '}
more for free shipping
</>
)}
</p>
</div>
<div className="h-1.5 bg-white rounded-full overflow-hidden border border-primary/10">
<div
className="h-full bg-primary rounded-full transition-all duration-300"
style={{ width: `${progressPercent}%` }}
/>
</div>
{/* Free shipping progress */}
<div className="rounded-lg bg-primary/5 border border-primary/10 p-3 space-y-2">
<div className="flex items-start gap-2">
<Truck className="w-4 h-4 text-primary shrink-0 mt-0.5" />
<p className="text-[12px] text-gray-600 leading-snug">
{shipping === 0 ? (
<span className="font-semibold text-emerald-600">
You&apos;ve unlocked free shipping!
</span>
) : (
<>
Add{' '}
<span className="font-bold text-primary">
{formatCurrency(amountNeeded)}
</span>{' '}
more for free shipping
</>
)}
</p>
</div>
)}
<div className="h-1.5 bg-white rounded-full overflow-hidden border border-primary/10">
<div
className="h-full bg-primary rounded-full transition-all duration-300"
style={{ width: `${progressPercent}%` }}
/>
</div>
</div>
<div className="space-y-2.5 text-gray-500">
<div className="flex justify-between">
<span>Taxable Subtotal</span>
<span>Subtotal</span>
<span className="font-semibold text-[#1a1a1a]">
{formatCurrency(subtotal)}
</span>
</div>
<div className="flex justify-between text-[13px]">
<span>GST (18%)</span>
<span className="font-semibold text-[#1a1a1a]">
{formatCurrency(tax)}
</span>
</div>
<div className="flex justify-between items-center">
<span>Shipping</span>
<span>

View file

@ -69,84 +69,44 @@ export default function AllCategoriesPage() {
</Link>
</div>
) : (
<div className="space-y-10">
{(() => {
const parents = categories.filter((c) => !c.parent_category_id);
const displayParents = parents.length > 0 ? parents : categories;
return displayParents.map((parent) => {
const subs = categories.filter((c) => c.parent_category_id === parent.category_id);
const parentImg = getImageUrl(parent.image_url || (parent as any).image || (parent as any).icon_url);
return (
<div key={parent.category_id || parent.slug} className="bg-white rounded-2xl p-6 sm:p-8 border border-gray-200/80 shadow-xs">
<div className="flex flex-wrap items-center justify-between pb-5 mb-6 border-b border-gray-100 gap-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center font-bold">
<Layers className="w-5 h-5" />
</div>
<div>
<h2 className="text-lg font-bold text-gray-900">{parent.name}</h2>
<p className="text-xs text-gray-400 mt-0.5">
{subs.length > 0 ? `${subs.length} Sub-categories • ` : ''}
{parent.product_count !== undefined ? `${parent.product_count} Total Products` : 'Catalog Category'}
</p>
</div>
</div>
<Link
href={`/shop?category=${parent.slug}`}
className="text-xs font-bold text-primary hover:underline flex items-center gap-1 bg-primary/5 hover:bg-primary/10 px-3.5 py-1.5 rounded-lg transition-colors"
>
View All in {parent.name} &rarr;
</Link>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-6">
{categories.map((cat: any) => {
const catImage = getImageUrl(cat.image_url || cat.image || cat.icon_url);
return (
<motion.div
key={cat.category_id || cat.slug}
whileHover={{ y: -6 }}
transition={{ type: 'spring', stiffness: 300, damping: 25 }}
>
<Link
href={`/products?category=${cat.slug}`}
className="flex flex-col items-center group text-center"
>
{/* Image Box */}
<div className="w-full aspect-square bg-white rounded-theme flex items-center justify-center p-6 border border-gray-200 group-hover:border-blue-200 group-hover:bg-blue-50/10 transition-all duration-300 relative overflow-hidden shadow-xs">
{catImage ? (
<motion.img
whileHover={{ scale: 1.06 }}
src={catImage}
alt={cat.name}
className="max-h-full max-w-full object-contain rounded-lg drop-shadow-md"
/>
) : (
<Layers className="w-12 h-12 text-gray-400 group-hover:text-primary transition-colors stroke-[1.5]" />
)}
</div>
{subs.length > 0 ? (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
{subs.map((sub: any) => {
const subImage = getImageUrl(sub.image_url || sub.image || sub.icon_url);
return (
<motion.div
key={sub.category_id || sub.slug}
whileHover={{ y: -4 }}
transition={{ type: 'spring', stiffness: 300, damping: 25 }}
>
<Link
href={`/products?category=${sub.slug}`}
className="flex flex-col items-center group text-center p-4 rounded-xl border border-gray-100 hover:border-primary/40 hover:bg-primary/5 transition-all"
>
<div className="w-full aspect-square bg-[#F8F9FA] rounded-xl flex items-center justify-center p-4 mb-3 border border-gray-100 group-hover:bg-white transition-colors relative overflow-hidden">
{subImage ? (
<motion.img
whileHover={{ scale: 1.05 }}
src={subImage}
alt={sub.name}
className="max-h-full max-w-full object-contain"
/>
) : (
<Layers className="w-8 h-8 text-gray-300 group-hover:text-primary transition-colors stroke-[1.5]" />
)}
</div>
<h3 className="text-[13px] font-bold text-gray-800 group-hover:text-primary transition-colors line-clamp-1">
{sub.name}
</h3>
<span className="text-[11px] font-medium text-gray-400 mt-0.5">
{sub.product_count !== undefined ? `${sub.product_count} Products` : 'Browse'}
</span>
</Link>
</motion.div>
);
})}
</div>
) : (
<div className="py-4 text-center text-xs text-gray-400">
<p>No sub-categories defined. Direct catalog products are under this category.</p>
</div>
)}
</div>
);
});
})()}
{/* Title & Count */}
<h3 className="text-[13px] font-bold text-gray-800 mt-3.5 group-hover:text-primary transition-colors line-clamp-1">
{cat.name}
</h3>
<span className="text-[10px] font-bold text-gray-400 mt-0.5 tracking-wide">
{cat.product_count !== undefined ? `${cat.product_count} Products` : 'Catalog Item'}
</span>
</Link>
</motion.div>
);
})}
</div>
)}
</div>

View file

@ -11,7 +11,7 @@ import Link from 'next/link';
import { useCartStore } from '@/store/cartStore';
import { useAuthStore } from '@/store/authStore';
import { formatCurrency, getImageUrl, parseMoney } from '@/lib/utils';
import { setAccessToken, apiFetch } from '@/services/api/client';
import { setAccessToken } from '@/services/api/client';
import {
createCheckoutOrder,
createCustomerAddress,
@ -20,12 +20,9 @@ import {
initiatePayment,
cancelPayment,
verifyPayment,
fetchAvailableCoupons,
type CustomerAddress,
type CheckoutCreateResponse,
type AvailableCoupon,
} from '@/services/api/checkoutService';
import { deliveryService, DeliverySettings } from '@/services/api/deliveryService';
import GoogleAuthModal from '@/components/auth/GoogleAuthModal';
import { Header } from '@/layout/Header';
import { Footer } from '@/layout/Footer';
@ -50,11 +47,8 @@ import {
RefreshCw,
Trash2,
KeyRound,
Sparkles,
Tag,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { creditService, WalletSummary } from '@/services/api/creditService';
type CheckoutStep = 'shipping' | 'payment' | 'review';
@ -75,10 +69,7 @@ export default function CheckoutPage() {
const [authModalOpen, setAuthModalOpen] = useState(false);
const [addresses, setAddresses] = useState<CustomerAddress[]>([]);
const [selectedAddressId, setSelectedAddressId] = useState<string | null>(null);
const paymentMethod = 'RAZORPAY';
const [wallet, setWallet] = useState<WalletSummary | null>(null);
const [deliverySettings, setDeliverySettings] = useState<DeliverySettings | null>(null);
const [useWalletCredits, setUseWalletCredits] = useState<boolean>(false);
const [paymentMethod, setPaymentMethod] = useState<'COD' | 'RAZORPAY'>('COD');
const [loadingAddresses, setLoadingAddresses] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
@ -87,15 +78,6 @@ export default function CheckoutPage() {
const [outOfStockVariantIds, setOutOfStockVariantIds] = useState<Set<string>>(
new Set()
);
// Promo code & coupon states
const [couponCodeInput, setCouponCodeInput] = useState('');
const [appliedCoupon, setAppliedCoupon] = useState<any | null>(null);
const [appliedCouponDiscount, setAppliedCouponDiscount] = useState<number>(0);
const [couponApplying, setCouponApplying] = useState(false);
const [availableCoupons, setAvailableCoupons] = useState<AvailableCoupon[]>([]);
const [loadingCoupons, setLoadingCoupons] = useState(false);
const [addressForm, setAddressForm] = useState({
address_type: 'SHIPPING',
full_name: '',
@ -108,46 +90,11 @@ export default function CheckoutPage() {
});
const subtotal = getCartTotal();
// Dynamic shipping calculation from backend admin settings
const isFreeDelivery = Boolean(
deliverySettings?.free_delivery_enabled &&
deliverySettings?.free_delivery_min_order_amount &&
subtotal >= deliverySettings.free_delivery_min_order_amount
);
const baseDeliveryFee = deliverySettings ? deliverySettings.delivery_charge : 99.0;
const shipping = subtotal > 0 ? (isFreeDelivery ? 0 : baseDeliveryFee) : 0;
// Free shipping on INR orders over ₹999; ₹99 flat shipping for orders below ₹999
const shipping = subtotal > 0 && subtotal < 999 ? 99.0 : 0;
// Coupon discount deduction
let couponDiscount = 0;
if (appliedCoupon) {
if (appliedCoupon.discount_amount !== undefined && appliedCoupon.discount_amount !== null) {
couponDiscount = Number(appliedCoupon.discount_amount);
} else if (appliedCoupon.discount_type === 'PERCENT' || appliedCoupon.discount_type === 'PERCENTAGE') {
couponDiscount = (subtotal * Number(appliedCoupon.discount_value || 0)) / 100;
if (appliedCoupon.max_discount_cap) {
couponDiscount = Math.min(couponDiscount, Number(appliedCoupon.max_discount_cap));
}
} else {
couponDiscount = Number(appliedCoupon.discount_value || 0);
}
}
if (appliedCouponDiscount > 0 && couponDiscount === 0) {
couponDiscount = appliedCouponDiscount;
}
couponDiscount = Math.min(subtotal, Math.max(0, couponDiscount));
const postDiscountSubtotal = Math.max(0, subtotal - couponDiscount);
// Pre-tax base pricing: subtotal is pre-tax base (e.g. 820), 18% GST is added (e.g. 180) to equal catalog MRP (1000)
const tax = Math.round((postDiscountSubtotal * (18 / 82)) * 100) / 100;
const grossTotal = Math.round(postDiscountSubtotal + tax + shipping);
// Store credits deduction calculation
const availableCredits = wallet?.active_balance || 0;
const maxCreditsToApply = Math.min(availableCredits, grossTotal);
const appliedCredits = useWalletCredits ? maxCreditsToApply : 0;
const finalPayableTotal = Math.max(0, grossTotal - appliedCredits);
const total = finalPayableTotal;
const estimatedCashback = Math.round(finalPayableTotal * 0.05);
const tax = Math.round(subtotal * 0.18 * 100) / 100;
const total = subtotal + shipping + tax;
const hasOutOfStockItems = cart.some((item) =>
outOfStockVariantIds.has(item.selectedVariant.variant_id)
@ -155,7 +102,6 @@ export default function CheckoutPage() {
useEffect(() => {
void bootstrapAuth();
deliveryService.getDeliverySettings().then(setDeliverySettings).catch(() => {});
}, [bootstrapAuth]);
useEffect(() => {
@ -176,17 +122,6 @@ export default function CheckoutPage() {
setAuthModalOpen(false);
loadAddresses();
void syncAndValidateCart();
creditService.getMyWallet().then(setWallet).catch(() => null);
}, [isAuthenticated, authReady]);
useEffect(() => {
setLoadingCoupons(true);
fetchAvailableCoupons()
.then((coupons) => {
setAvailableCoupons(coupons || []);
})
.catch(() => {})
.finally(() => setLoadingCoupons(false));
}, [isAuthenticated, authReady]);
const syncAndValidateCart = async () => {
@ -388,49 +323,6 @@ export default function CheckoutPage() {
});
};
const handleApplyCoupon = async (customCode?: string) => {
const code = (customCode || couponCodeInput).trim().toUpperCase();
if (!code) {
toast.error('Please enter a coupon code');
return;
}
setCouponCodeInput(code);
setCouponApplying(true);
try {
await syncCartItems(
cart.map((item) => ({
variant_id: item.selectedVariant.variant_id,
qty: item.quantity,
}))
);
const res = await apiFetch<any>('/api/v1/cart/coupon/apply', {
method: 'POST',
body: JSON.stringify({ code, coupon_code: code }),
});
if (res && res.coupon) {
setAppliedCoupon(res.coupon);
setAppliedCouponDiscount(Number(res.discount || res.discount_amount || 0));
toast.success(`Coupon ${code} applied successfully! Saved ₹${Number(res.discount || res.discount_amount || 0).toFixed(0)}`);
} else {
toast.error('Could not apply coupon');
}
} catch (err: any) {
toast.error(err.message || 'Invalid or ineligible coupon code');
} finally {
setCouponApplying(false);
}
};
const handleRemoveCoupon = async () => {
setAppliedCoupon(null);
setAppliedCouponDiscount(0);
setCouponCodeInput('');
try {
await apiFetch('/api/v1/cart/coupon/remove', { method: 'DELETE' });
} catch {}
toast.info('Coupon removed');
};
const handlePlaceOrder = async (e: React.FormEvent) => {
e.preventDefault();
setErrorMsg(null);
@ -466,90 +358,94 @@ export default function CheckoutPage() {
const orderData = await createCheckoutOrder({
address_id: selectedAddressId,
payment_method: paymentMethod,
use_wallet_credits: useWalletCredits,
coupon_code: appliedCoupon?.code || undefined,
});
const scriptLoaded = await loadRazorpayScript();
if (!scriptLoaded) {
throw new Error(
'Razorpay SDK failed to load. Please check your internet connection.'
);
}
const initRes = await initiatePayment(orderData.order_id);
if (initRes.zero_amount) {
if (paymentMethod === 'COD') {
clearCart();
setOrderResult({
...orderData,
payment_status: 'PAYMENT_CAPTURED',
status: 'ORDER_CONFIRMED',
invoice_id: initRes.invoice_id || orderData.invoice_id,
invoice_no: initRes.invoice_no || orderData.invoice_no,
});
setOrderResult(orderData);
setSubmitting(false);
return;
}
} else {
const scriptLoaded = await loadRazorpayScript();
if (!scriptLoaded) {
throw new Error(
'Razorpay SDK failed to load. Please check your internet connection.'
);
}
const selAddr = addresses.find((a) => a.address_id === selectedAddressId);
const initRes = await initiatePayment(orderData.order_id);
const options = {
key: initRes.rzp_key_id,
amount: initRes.amount,
currency: initRes.currency,
name: 'iFixKart',
description: `Order #${orderData.order_no}`,
order_id: initRes.rzp_order_id,
redirect: false,
prefill: {
name: selAddr?.full_name || '',
contact: selAddr?.phone || '',
},
theme: {
color: '#1976F3',
},
handler: async function (response: any) {
try {
setSubmitting(true);
const verifyRes = await verifyPayment({
order_id: orderData.order_id,
razorpay_order_id: response.razorpay_order_id,
razorpay_payment_id: response.razorpay_payment_id,
razorpay_signature: response.razorpay_signature,
});
if (initRes.zero_amount) {
clearCart();
setOrderResult({
...orderData,
payment_status: 'PAYMENT_CAPTURED',
status: 'ORDER_CONFIRMED',
invoice_id: initRes.invoice_id || orderData.invoice_id,
invoice_no: initRes.invoice_no || orderData.invoice_no,
});
setSubmitting(false);
return;
}
clearCart();
setOrderResult({
...orderData,
payment_status: 'PAYMENT_CAPTURED',
status: 'ORDER_CONFIRMED',
invoice_no: verifyRes.invoice_no || orderData.invoice_no,
});
} catch (vErr: any) {
setErrorMsg(vErr.message || 'Payment verification failed.');
} finally {
setSubmitting(false);
}
},
modal: {
escape: true,
handleback: true,
confirm_close: true,
ondismiss: async function () {
setSubmitting(false);
setErrorMsg('Payment popup was closed before completion. Order cancelled.');
const selAddr = addresses.find((a) => a.address_id === selectedAddressId);
const options = {
key: initRes.rzp_key_id,
amount: initRes.amount,
currency: initRes.currency,
name: 'iFixKart',
description: `Order #${orderData.order_no}`,
order_id: initRes.rzp_order_id,
redirect: false,
prefill: {
name: selAddr?.full_name || '',
contact: selAddr?.phone || '',
},
theme: {
color: '#1976F3',
},
handler: async function (response: any) {
try {
await cancelPayment(orderData.order_id, 'Payment popup closed by customer');
} catch (cErr) {
console.error('Failed to cancel payment session:', cErr);
setSubmitting(true);
const verifyRes = await verifyPayment({
order_id: orderData.order_id,
razorpay_order_id: response.razorpay_order_id,
razorpay_payment_id: response.razorpay_payment_id,
razorpay_signature: response.razorpay_signature,
});
clearCart();
setOrderResult({
...orderData,
payment_status: 'PAYMENT_CAPTURED',
status: 'ORDER_CONFIRMED',
invoice_no: verifyRes.invoice_no || orderData.invoice_no,
});
} catch (vErr: any) {
setErrorMsg(vErr.message || 'Payment verification failed.');
} finally {
setSubmitting(false);
}
},
},
};
modal: {
escape: true,
handleback: true,
confirm_close: true,
ondismiss: async function () {
setSubmitting(false);
setErrorMsg('Payment popup was closed before completion. Order cancelled.');
try {
await cancelPayment(orderData.order_id, 'Payment popup closed by customer');
} catch (cErr) {
console.error('Failed to cancel payment session:', cErr);
}
},
},
};
const rzp = new (window as any).Razorpay(options);
rzp.open();
const rzp = new (window as any).Razorpay(options);
rzp.open();
}
} catch (err: any) {
const detail = err.message || 'Failed to place order';
@ -939,25 +835,65 @@ export default function CheckoutPage() {
</div>
<div className="space-y-3">
<div className="flex items-start gap-3 p-4 border border-primary bg-primary/5 ring-1 ring-primary rounded-lg transition-all">
<div className="mt-1 w-4 h-4 rounded-full border-2 border-primary flex items-center justify-center bg-primary">
<div className="w-1.5 h-1.5 rounded-full bg-white" />
</div>
<label
className={`flex items-start gap-3 p-4 border rounded-lg cursor-pointer transition-all ${
paymentMethod === 'RAZORPAY'
? 'border-primary bg-primary/5 ring-1 ring-primary'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<input
type="radio"
name="payment"
value="RAZORPAY"
checked={paymentMethod === 'RAZORPAY'}
onChange={() => setPaymentMethod('RAZORPAY')}
className="mt-1 accent-[var(--color-primary,#1976F3)] w-4 h-4"
/>
<div className="flex-1 space-y-1.5">
<div className="flex items-center justify-between gap-2">
<span className="font-bold text-[#1a1a1a] text-[13px] flex items-center gap-2">
Online payment
<span className="bg-emerald-50 text-emerald-700 text-[9px] font-bold px-1.5 py-0.5 rounded uppercase">
Instant & Secure
Instant
</span>
</span>
<Wallet className="w-5 h-5 text-primary" />
</div>
<p className="text-[12px] text-gray-500 leading-relaxed">
Cards, UPI (GPay, PhonePe, Paytm), Netbanking, and Wallets via Razorpay.
Cards, net banking, wallets, or UPI (GPay, PhonePe,
Paytm).
</p>
</div>
</div>
</label>
<label
className={`flex items-start gap-3 p-4 border rounded-lg cursor-pointer transition-all ${
paymentMethod === 'COD'
? 'border-primary bg-primary/5 ring-1 ring-primary'
: 'border-gray-200 hover:border-gray-300'
}`}
>
<input
type="radio"
name="payment"
value="COD"
checked={paymentMethod === 'COD'}
onChange={() => setPaymentMethod('COD')}
className="mt-1 accent-[var(--color-primary,#1976F3)] w-4 h-4"
/>
<div className="flex-1 space-y-1.5">
<div className="flex items-center justify-between gap-2">
<span className="font-bold text-[#1a1a1a] text-[13px]">
Cash on delivery
</span>
<CreditCard className="w-5 h-5 text-gray-400" />
</div>
<p className="text-[12px] text-gray-500 leading-relaxed">
Pay in cash when your order arrives at the door.
</p>
</div>
</label>
</div>
<div className="flex items-center justify-between pt-4 border-t border-gray-100">
@ -1026,20 +962,18 @@ export default function CheckoutPage() {
Payment
</h4>
<p className="font-semibold text-[#1a1a1a] flex items-center gap-2">
Online payment
{paymentMethod === 'RAZORPAY'
? 'Online payment'
: 'Cash on delivery'}
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded uppercase bg-primary/10 text-primary">
RAZORPAY
{paymentMethod}
</span>
</p>
<p className="text-gray-500 text-[12px]">
Secured via Razorpay (UPI, Cards, Netbanking).
{paymentMethod === 'RAZORPAY'
? 'Secured via Razorpay.'
: 'Pay in cash on delivery.'}
</p>
{useWalletCredits && appliedCredits > 0 && (
<div className="pt-1.5 flex items-center gap-1.5 text-[12px] font-bold text-emerald-700">
<Wallet className="w-3.5 h-3.5 text-emerald-600" />
<span>Store Credits Applied: -{formatCurrency(appliedCredits)}</span>
</div>
)}
</div>
</div>
@ -1178,12 +1112,12 @@ export default function CheckoutPage() {
<div className="space-y-2 text-[#1a1a1a] border-t border-gray-100 pt-3">
<div className="flex justify-between text-gray-500">
<span>Taxable Subtotal</span>
<span>Subtotal</span>
<span className="font-semibold text-[#1a1a1a]">
{formatCurrency(subtotal)}
</span>
</div>
<div className="flex justify-between text-gray-500 text-[13px]">
<div className="flex justify-between text-gray-500">
<span>GST (18%)</span>
<span className="font-semibold text-[#1a1a1a]">
{formatCurrency(tax)}
@ -1203,181 +1137,12 @@ export default function CheckoutPage() {
)}
</span>
</div>
{/* Coupon Discount Row */}
{appliedCoupon && couponDiscount > 0 && (
<div className="flex justify-between text-emerald-700 font-semibold text-[13px] pt-1">
<span className="flex items-center gap-1">
<Tag className="w-3.5 h-3.5" /> Coupon ({appliedCoupon.code})
</span>
<span>-{formatCurrency(couponDiscount)}</span>
</div>
)}
{/* Store Credits Applied Row */}
{useWalletCredits && appliedCredits > 0 && (
<div className="flex justify-between text-emerald-700 font-semibold text-[13px] pt-1">
<span className="flex items-center gap-1">
<Wallet className="w-3.5 h-3.5" /> Store Credits Applied
</span>
<span>-{formatCurrency(appliedCredits)}</span>
</div>
)}
</div>
{/* Promo Code Input or Applied Badge */}
<div className="pt-2 border-t border-gray-100 space-y-2.5">
{!appliedCoupon ? (
<>
<div className="flex gap-2">
<div className="relative flex-1">
<Tag className="w-3.5 h-3.5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="Promo / Coupon code"
value={couponCodeInput}
onChange={(e) => setCouponCodeInput(e.target.value.toUpperCase())}
className="w-full bg-gray-50 border border-gray-200 rounded-lg pl-9 pr-3 py-2 outline-none text-[12px] font-mono uppercase focus:border-primary focus:ring-1 focus:ring-primary/20"
/>
</div>
<button
type="button"
onClick={() => handleApplyCoupon()}
disabled={couponApplying || !couponCodeInput.trim()}
className="bg-primary hover:brightness-95 text-white font-bold px-3 py-2 rounded-lg text-[12px] transition cursor-pointer disabled:opacity-50"
>
{couponApplying ? 'Applying...' : 'Apply'}
</button>
</div>
{/* Available Promotional Coupons List */}
{availableCoupons.length > 0 && (
<div className="pt-1.5 space-y-2">
<div className="flex items-center justify-between">
<span className="text-[11px] font-bold text-gray-700 uppercase tracking-wide flex items-center gap-1.5">
<Sparkles className="w-3.5 h-3.5 text-primary" /> Available Offers & Coupons
</span>
<span className="text-[10px] font-bold text-primary bg-primary/10 px-2 py-0.5 rounded-full">
{availableCoupons.length} {availableCoupons.length === 1 ? 'offer' : 'offers'}
</span>
</div>
<div className="space-y-2 max-h-56 overflow-y-auto pr-0.5">
{availableCoupons.map((c) => {
const isEligible = c.is_eligible !== false;
return (
<div
key={c.coupon_id}
className={`p-2.5 rounded-lg border transition-all ${
isEligible
? 'border-dashed border-primary/40 bg-primary/5 hover:border-primary hover:bg-primary/10'
: 'border-gray-200 bg-gray-50/70 opacity-60'
}`}
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<span className="font-mono font-bold text-[12px] tracking-wider text-primary px-1.5 py-0.5 bg-white border border-primary/30 rounded">
{c.code}
</span>
<span className="text-[11px] font-bold text-gray-800">
{c.discount_type === 'PERCENTAGE' || (c.discount_type as string) === 'PERCENT'
? `${c.discount_value}% OFF`
: `₹${c.discount_value} OFF`}
{c.max_discount_cap ? ` (Up to ₹${c.max_discount_cap})` : ''}
</span>
</div>
<p className="text-[11px] text-gray-600 mt-1 line-clamp-2">
{c.description || c.title}
</p>
<div className="flex flex-wrap items-center gap-2 mt-1 text-[10px] text-gray-500">
{c.min_order_amount > 0 && (
<span>Min spend: ₹{c.min_order_amount}</span>
)}
{c.first_order_only && (
<span className="text-amber-700 font-semibold">★ First Order Only</span>
)}
{!isEligible && c.ineligibility_reason && (
<span className="text-red-500 font-medium">({c.ineligibility_reason})</span>
)}
</div>
</div>
<button
type="button"
disabled={couponApplying || !isEligible}
onClick={() => handleApplyCoupon(c.code)}
className="shrink-0 px-2.5 py-1 text-[11px] font-bold text-white bg-primary hover:brightness-95 rounded-md cursor-pointer transition disabled:opacity-40 disabled:cursor-not-allowed shadow-xs"
>
{couponApplying && couponCodeInput === c.code ? 'Applying...' : 'Apply'}
</button>
</div>
</div>
);
})}
</div>
</div>
)}
</>
) : (
<div className="p-2.5 bg-emerald-50 border border-emerald-200 rounded-lg flex items-center justify-between text-[12px]">
<div className="flex items-center gap-1.5">
<Tag className="w-3.5 h-3.5 text-emerald-600" />
<span className="font-bold font-mono text-emerald-900">{appliedCoupon.code}</span>
<span className="text-[11px] text-emerald-700 font-semibold">
(-{formatCurrency(couponDiscount)})
</span>
</div>
<button
type="button"
onClick={handleRemoveCoupon}
className="text-[11px] font-semibold text-red-600 hover:underline cursor-pointer"
>
Remove
</button>
</div>
)}
</div>
{/* Store Credit Redemption Card */}
{Boolean(wallet && wallet.active_balance > 0) && (
<div className="p-3 bg-emerald-50/70 border border-emerald-200/90 rounded-lg space-y-1.5">
<label className="flex items-center justify-between cursor-pointer">
<div className="flex items-center gap-2">
<input
type="checkbox"
checked={useWalletCredits}
onChange={(e) => setUseWalletCredits(e.target.checked)}
className="w-4 h-4 rounded text-emerald-600 accent-emerald-600 focus:ring-emerald-500 cursor-pointer"
/>
<span className="text-[12px] font-bold text-emerald-950">
Redeem Store Credits
</span>
</div>
<span className="text-[11px] font-bold px-1.5 py-0.5 rounded bg-emerald-100 text-emerald-800">
{formatCurrency(wallet?.active_balance || 0)} Available
</span>
</label>
<p className="text-[11px] text-emerald-800/80 pl-6 leading-tight">
{useWalletCredits
? `Deducting ${formatCurrency(appliedCredits)} from your order total.`
: 'Check to deduct available store credits from this order.'}
</p>
</div>
)}
<div className="border-t border-gray-200 pt-3 flex justify-between items-center">
<span className="font-bold text-[#1a1a1a]">Payable Amount</span>
<span className="font-bold text-[#1a1a1a]">Total</span>
<span className="text-lg font-bold text-primary">
{formatCurrency(finalPayableTotal)}
</span>
</div>
{/* Cashback Reward Earn Preview */}
<div className="p-2.5 bg-blue-50/60 border border-blue-200/70 rounded-lg flex items-center gap-2 text-[11px] text-blue-900 font-medium">
<Sparkles className="w-4 h-4 text-blue-600 shrink-0" />
<span>
You will earn <strong>≈ {formatCurrency(estimatedCashback)}</strong> Store Credit (5%) after the return window.
{formatCurrency(total)}
</span>
</div>
</div>

View file

@ -10,7 +10,7 @@ import Image from 'next/image';
import { useCartStore } from '@/store/cartStore';
import { catalogService, ProductResponse } from '@/services/api/catalogService';
import { mapProductCardToProductResponse } from '@/utils/productMapper';
import { formatCatalogPriceLabel, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCatalogPriceLabel, getImageUrl } from '@/lib/utils';
import { ArrowLeftRight, Trash2 } from 'lucide-react';
import { AnnouncementBar } from '@/layout/AnnouncementBar';
import { Header } from '@/layout/Header';
@ -155,7 +155,7 @@ export default function ComparePage() {
<tr className="bg-gray-50 border-b border-gray-200 text-gray-900">
<th className="p-4 w-44 font-extrabold">Feature</th>
{products.map((product) => {
const img = resolveProductImage(product);
const img = getImageUrl(product.images?.[0]?.image_url);
return (
<th key={product.product_id} className="p-4 min-w-[200px]">
<div className="flex flex-col items-center text-center">

View file

@ -1,8 +1,7 @@
'use client';
import React, { useEffect, useState } from 'react';
import { RefreshCw, Home, ChevronDown } from 'lucide-react';
import Link from 'next/link';
import React, { useEffect } from 'react';
import { AlertTriangle, RefreshCw } from 'lucide-react';
interface ErrorProps {
error: Error & { digest?: string };
@ -10,168 +9,27 @@ interface ErrorProps {
}
export default function Error({ error, reset }: ErrorProps) {
const [isRetrying, setIsRetrying] = useState(false);
const [showDetails, setShowDetails] = useState(false);
useEffect(() => {
console.error('Storefront error boundary caught:', error);
// Auto-recover from chunk load errors caused by production redeployments
const msg = (error?.message || '').toLowerCase();
const isChunkError =
error?.name === 'ChunkLoadError' ||
msg.includes('loading chunk') ||
msg.includes('failed to fetch dynamically imported module');
if (isChunkError && typeof window !== 'undefined') {
const retryKey = `chunk_reload_${window.location.pathname}`;
const hasRetried = sessionStorage.getItem(retryKey);
if (!hasRetried) {
sessionStorage.setItem(retryKey, '1');
window.location.reload();
}
}
}, [error]);
const handleRefresh = () => {
setIsRetrying(true);
if (typeof window !== 'undefined') {
window.location.reload();
} else {
reset();
}
};
return (
<div className="w-full min-h-screen bg-[#EEF2F6] flex flex-col items-center justify-center p-4 sm:p-6 font-sans">
<div className="max-w-[620px] w-full bg-white rounded-2xl overflow-hidden shadow-2xl border border-gray-100">
{/* Top Navy Banner matching Image 2 */}
<div className="bg-[#2D4364] px-6 py-8 sm:px-10 sm:py-10 flex items-center gap-6 sm:gap-8">
{/* White Circular Badge with crossed wrench & screwdriver */}
<div className="w-24 h-24 sm:w-32 sm:h-32 rounded-full bg-white flex items-center justify-center shadow-lg flex-shrink-0 overflow-hidden relative">
<svg
viewBox="0 0 100 100"
className="w-20 h-20 sm:w-28 sm:h-28"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
{/* Long 45-deg flat shadow */}
<polygon
points="38,38 98,98 100,80 100,50 62,12 50,24"
fill="#E2E8F0"
opacity="0.8"
/>
{/* Screwdriver (top-left to bottom-right) */}
<g transform="rotate(-45 50 50)">
<rect x="48" y="14" width="4" height="36" fill="#2D4364" />
<polygon points="46,14 54,14 52,9 48,9" fill="#2D4364" />
<rect x="43" y="50" width="14" height="34" rx="3" fill="#2D4364" />
<line
x1="47"
y1="55"
x2="47"
y2="79"
stroke="#FFFFFF"
strokeWidth="1.5"
strokeLinecap="round"
opacity="0.3"
/>
<line
x1="53"
y1="55"
x2="53"
y2="79"
stroke="#FFFFFF"
strokeWidth="1.5"
strokeLinecap="round"
opacity="0.3"
/>
</g>
{/* Wrench (bottom-left to top-right) */}
<g transform="rotate(45 50 50)">
<rect x="45.5" y="28" width="9" height="40" rx="2" fill="#2D4364" />
<path
d="M36 26 C36 14 42 9 50 9 C58 9 64 14 64 26 C64 29 62 31 57 31 L55 21 L45 21 L43 31 C38 31 36 29 36 26 Z"
fill="#2D4364"
/>
<circle cx="50" cy="74" r="9" fill="#2D4364" />
<circle cx="50" cy="74" r="4.5" fill="white" />
</g>
</svg>
</div>
{/* Heading Text */}
<div className="text-white font-black tracking-tight uppercase leading-[1.05] text-2xl sm:text-4xl select-none font-outfit">
WEBSITE<br />
UNDER<br />
MAINTENANCE
</div>
</div>
{/* Bottom Content Body */}
<div className="p-6 sm:p-10">
<h1 className="text-xl sm:text-2xl font-extrabold text-[#1E293B] mb-3 font-outfit">
We’ll be back soon!
</h1>
<p className="text-sm sm:text-[15px] leading-relaxed text-[#475569] mb-5">
Sorry for the inconvenience but we&apos;re performing some maintenance at the moment. If you need to you can always{' '}
<Link
href="/contact"
className="text-[#D97706] hover:text-[#B45309] font-semibold underline underline-offset-2 transition-colors"
>
contact us
</Link>
, otherwise we&apos;ll be back online shortly!
</p>
<p className="text-sm sm:text-[15px] font-semibold text-[#64748B] mb-7">
— The iFixKart Team
</p>
{/* Action Buttons */}
<div className="flex flex-wrap items-center gap-3">
<button
type="button"
onClick={handleRefresh}
disabled={isRetrying}
className="inline-flex items-center justify-center gap-2 bg-[#2D4364] hover:bg-[#1E293B] text-white font-bold text-sm px-6 py-3 rounded-lg shadow-sm transition-all cursor-pointer disabled:opacity-70 active:scale-[0.99]"
>
<RefreshCw size={16} className={isRetrying ? 'animate-spin' : ''} />
<span>{isRetrying ? 'Refreshing...' : 'Refresh Page'}</span>
</button>
<a
href="/"
className="inline-flex items-center justify-center gap-2 bg-[#F1F5F9] hover:bg-[#E2E8F0] text-[#334155] border border-[#CBD5E1] font-bold text-sm px-6 py-3 rounded-lg transition-all cursor-pointer active:scale-[0.99]"
>
<Home size={16} />
<span>Return Home</span>
</a>
</div>
{/* Technical Diagnostics (Collapsible for dev & debugging) */}
{error?.message && (
<div className="mt-8 pt-5 border-t border-gray-100">
<button
type="button"
onClick={() => setShowDetails(!showDetails)}
className="text-xs font-medium text-gray-400 hover:text-gray-600 flex items-center gap-1 cursor-pointer"
>
<span>Diagnostics</span>
<ChevronDown
size={13}
className={`transition-transform duration-200 ${showDetails ? 'rotate-180' : ''}`}
/>
</button>
{showDetails && (
<div className="mt-2 p-3 bg-gray-50 rounded-lg text-left text-xs font-mono text-gray-500 overflow-x-auto border border-gray-200">
<p className="font-semibold text-gray-700">{error.name || 'Error'}: {error.message}</p>
{error.digest && <p className="text-[11px] text-gray-400 mt-1">Digest: {error.digest}</p>}
</div>
)}
</div>
)}
<div className="w-full min-h-screen bg-[#F8F9FB] flex flex-col items-center justify-center p-6 font-sans">
<div className="max-w-md w-full bg-white border border-gray-250 rounded-2xl p-8 text-center shadow-soft">
<div className="w-12 h-12 bg-red-50 text-red-500 rounded-full flex items-center justify-center mx-auto mb-4">
<AlertTriangle size={24} className="stroke-[2.5]" />
</div>
<h2 className="text-lg font-extrabold text-gray-900 mb-2 font-outfit">Something Went Wrong</h2>
<p className="text-xs text-gray-500 font-medium mb-6">
{error.message || 'We ran into an unexpected error loading this page. Please try refreshing.'}
</p>
<button
onClick={() => reset()}
className="inline-flex items-center justify-center gap-2 bg-[#0073EC] hover:bg-[#1565C0] text-white font-bold text-xs uppercase tracking-wider py-3.5 px-6 rounded-xl transition-all shadow-md active:scale-[0.99] cursor-pointer"
>
<RefreshCw size={14} className="animate-spin-slow" />
<span>Try Again</span>
</button>
</div>
</div>
);

View file

@ -17,13 +17,8 @@ export default function FaqsPage() {
useEffect(() => {
let cancelled = false;
Promise.all([
storefrontService.getPageLayout('faqs'),
storefrontService.getFaqLayout(),
]).then(([faqsData, legacyData]) => {
if (cancelled) return;
const raw = Array.isArray(faqsData) && faqsData.length > 0 ? faqsData : legacyData;
setData(parseFaqPageData(raw));
storefrontService.getFaqLayout().then((raw) => {
if (!cancelled) setData(parseFaqPageData(raw));
});
return () => {
cancelled = true;

View file

@ -31,7 +31,6 @@ const labelClass = 'block text-[12px] font-bold text-[#1E293B] mb-1.5';
export default function FeedbackPage() {
const [footer, setFooter] = useState<FooterInfo>(MOCK_FOOTER_INFO);
const [settings, setSettings] = useState<StorefrontSettings>({ store_name: 'iFixKart' });
const [layoutSections, setLayoutSections] = useState<any[]>([]);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [topic, setTopic] = useState('suggestion');
@ -39,19 +38,16 @@ export default function FeedbackPage() {
const [rating, setRating] = useState(0);
const [message, setMessage] = useState('');
const [submitted, setSubmitted] = useState(false);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
let cancelled = false;
Promise.all([
storefrontService.getFooterInfo(),
storefrontService.getSettings(),
storefrontService.getPageLayout('feedback'),
]).then(([info, store, layout]) => {
]).then(([info, store]) => {
if (cancelled) return;
if (info) setFooter(info);
if (store) setSettings(store);
if (layout && layout.length > 0) setLayoutSections(layout);
});
return () => {
cancelled = true;
@ -62,34 +58,26 @@ export default function FeedbackPage() {
const supportEmail = footer.email || 'support@ifixkart.com';
const doc = useMemo(() => buildFeedbackPage(storeName), [storeName]);
const heroSec = layoutSections.find((s) => s.region === 'feedback_hero' || s.type === 'feedback_hero');
const heading = heroSec?.title || doc.heading;
const intro = heroSec?.subtitle || doc.intro;
const handleSubmit = async (e: FormEvent) => {
const handleSubmit = (e: FormEvent) => {
e.preventDefault();
if (!message.trim() || !email.trim()) return;
setSubmitting(true);
try {
await storefrontService.submitFeedback({
name: name.trim() || 'Valued Customer',
email: email.trim(),
topic,
order_no: orderNo.trim() || undefined,
rating: rating || 5,
message: message.trim(),
});
setSubmitted(true);
} catch {
const topicLabel = doc.topics.find((t) => t.id === topic)?.label || topic;
const body = `Name: ${name}\nEmail: ${email}\nTopic: ${topicLabel}\nRating: ${rating}\n\n${message}`;
window.location.href = `mailto:${supportEmail}?subject=${encodeURIComponent(
`${storeName} feedback — ${topicLabel}`
)}&body=${encodeURIComponent(body)}`;
setSubmitted(true);
} finally {
setSubmitting(false);
}
const topicLabel = doc.topics.find((t) => t.id === topic)?.label || topic;
const body = [
`Name: ${name}`,
`Email: ${email}`,
`Topic: ${topicLabel}`,
orderNo ? `Order / job: ${orderNo}` : '',
rating ? `Rating: ${rating} / 5` : '',
'',
message,
]
.filter((line) => line !== '')
.join('\n');
const href = `mailto:${supportEmail}?subject=${encodeURIComponent(
`${storeName} feedback — ${topicLabel}`
)}&body=${encodeURIComponent(body)}`;
window.location.href = href;
setSubmitted(true);
};
return (
@ -102,9 +90,9 @@ export default function FeedbackPage() {
<main className="flex-grow py-10 pb-20">
<div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-[900px]">
<h1 className="text-[28px] md:text-[32px] font-bold text-[#1E293B]">
{heading}
{doc.heading}
</h1>
<p className="text-[14px] text-gray-500 mt-2 max-w-2xl">{intro}</p>
<p className="text-[14px] text-gray-500 mt-2 max-w-2xl">{doc.intro}</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-8">
{doc.highlights.map((item) => {
@ -259,10 +247,9 @@ export default function FeedbackPage() {
<button
type="submit"
disabled={submitting}
className="w-full sm:w-auto px-6 py-3 bg-primary text-white text-[14px] font-semibold rounded-lg hover:brightness-95 cursor-pointer disabled:opacity-50"
className="w-full sm:w-auto px-6 py-3 bg-primary text-white text-[14px] font-semibold rounded-lg hover:brightness-95 cursor-pointer"
>
{submitting ? 'Sending feedback...' : 'Send feedback'}
Send feedback
</button>
</form>
)}

View file

@ -1,119 +0,0 @@
'use client';
import React, { useEffect, useState } from 'react';
import { RefreshCw, Home } from 'lucide-react';
interface GlobalErrorProps {
error: Error & { digest?: string };
reset: () => void;
}
export default function GlobalError({ error, reset }: GlobalErrorProps) {
const [isRetrying, setIsRetrying] = useState(false);
useEffect(() => {
console.error('Global error boundary caught:', error);
const msg = (error?.message || '').toLowerCase();
const isChunkError =
error?.name === 'ChunkLoadError' ||
msg.includes('loading chunk') ||
msg.includes('failed to fetch dynamically imported module');
if (isChunkError && typeof window !== 'undefined') {
const retryKey = `chunk_reload_global_${window.location.pathname}`;
if (!sessionStorage.getItem(retryKey)) {
sessionStorage.setItem(retryKey, '1');
window.location.reload();
}
}
}, [error]);
const handleRefresh = () => {
setIsRetrying(true);
if (typeof window !== 'undefined') {
window.location.reload();
} else {
reset();
}
};
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Website Under Maintenance | iFixKart</title>
<style>{`
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #EEF2F6; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 16px; }
.card { max-width: 620px; width: 100%; background: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 20px 40px rgba(0,0,0,0.12); }
.banner { background: #2D4364; padding: 36px 32px; display: flex; align-items: center; gap: 24px; }
.circle { width: 110px; height: 110px; border-radius: 50%; background: #ffffff; display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 8px 24px rgba(0,0,0,0.18); overflow: hidden; }
.banner-title { color: #ffffff; font-weight: 900; text-transform: uppercase; line-height: 1.05; font-size: 32px; letter-spacing: 0.5px; }
.content { padding: 36px 32px; }
.headline { font-size: 24px; font-weight: 800; color: #1E293B; margin-bottom: 14px; }
.paragraph { font-size: 15px; line-height: 1.6; color: #475569; margin-bottom: 20px; }
.contact-link { color: #D97706; text-decoration: underline; font-weight: 600; }
.sign { font-size: 15px; font-weight: 600; color: #64748B; margin-bottom: 28px; }
.actions { display: flex; flex-wrap: wrap; gap: 12px; }
.btn-primary { background: #2D4364; color: #ffffff; border: none; padding: 12px 24px; border-radius: 8px; font-weight: 700; font-size: 14px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; }
.btn-primary:hover { background: #1E293B; }
.btn-secondary { background: #F1F5F9; color: #334155; border: 1px solid #CBD5E1; padding: 12px 24px; border-radius: 8px; font-weight: 700; font-size: 14px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; }
.btn-secondary:hover { background: #E2E8F0; }
`}</style>
</head>
<body>
<div className="card">
<div className="banner">
<div className="circle">
<svg viewBox="0 0 100 100" width="85" height="85" fill="none">
<polygon points="38,38 98,98 100,80 100,50 62,12 50,24" fill="#E2E8F0" opacity="0.8" />
<g transform="rotate(-45 50 50)">
<rect x="48" y="14" width="4" height="36" fill="#2D4364" />
<polygon points="46,14 54,14 52,9 48,9" fill="#2D4364" />
<rect x="43" y="50" width="14" height="34" rx="3" fill="#2D4364" />
<line x1="47" y1="55" x2="47" y2="79" stroke="#FFFFFF" strokeWidth="1.5" strokeLinecap="round" opacity="0.3" />
<line x1="53" y1="55" x2="53" y2="79" stroke="#FFFFFF" strokeWidth="1.5" strokeLinecap="round" opacity="0.3" />
</g>
<g transform="rotate(45 50 50)">
<rect x="45.5" y="28" width="9" height="40" rx="2" fill="#2D4364" />
<path d="M36 26 C36 14 42 9 50 9 C58 9 64 14 64 26 C64 29 62 31 57 31 L55 21 L45 21 L43 31 C38 31 36 29 36 26 Z" fill="#2D4364" />
<circle cx="50" cy="74" r="9" fill="#2D4364" />
<circle cx="50" cy="74" r="4.5" fill="white" />
</g>
</svg>
</div>
<div className="banner-title">
WEBSITE<br />
UNDER<br />
MAINTENANCE
</div>
</div>
<div className="content">
<div className="headline">We’ll be back soon!</div>
<p className="paragraph">
Sorry for the inconvenience but we&apos;re performing some maintenance at the moment. If you need to you can always{' '}
<a href="/contact" className="contact-link">
contact us
</a>
, otherwise we&apos;ll be back online shortly!
</p>
<div className="sign">— The iFixKart Team</div>
<div className="actions">
<button type="button" onClick={handleRefresh} disabled={isRetrying} className="btn-primary">
<RefreshCw size={16} className={isRetrying ? 'animate-spin' : ''} />
<span>{isRetrying ? 'Refreshing...' : 'Refresh Page'}</span>
</button>
<a href="/" className="btn-secondary">
<Home size={16} />
<span>Return Home</span>
</a>
</div>
</div>
</div>
</body>
</html>
);
}

View file

@ -4,18 +4,12 @@
@layer base {
html {
scroll-behavior: smooth;
overflow-x: hidden;
width: 100%;
max-width: 100vw;
}
body {
background-color: #F8F9FB;
color: #1E293B;
font-family: 'Inter', sans-serif;
-webkit-font-smoothing: antialiased;
overflow-x: hidden;
width: 100%;
max-width: 100vw;
}
}

View file

@ -43,19 +43,16 @@ function telHref(phone: string): string {
export default function HelpCenterPage() {
const [footer, setFooter] = useState<FooterInfo>(MOCK_FOOTER_INFO);
const [settings, setSettings] = useState<StorefrontSettings>({ store_name: 'iFixKart' });
const [layoutSections, setLayoutSections] = useState<any[]>([]);
useEffect(() => {
let cancelled = false;
Promise.all([
storefrontService.getFooterInfo(),
storefrontService.getSettings(),
storefrontService.getPageLayout('help'),
]).then(([info, store, layout]) => {
]).then(([info, store]) => {
if (cancelled) return;
if (info) setFooter(info);
if (store) setSettings(store);
if (layout && layout.length > 0) setLayoutSections(layout);
});
return () => {
cancelled = true;
@ -67,21 +64,6 @@ export default function HelpCenterPage() {
const email = footer.email || '';
const doc = useMemo(() => buildHelpDoc(storeName), [storeName]);
const heroSec = layoutSections.find((s) => s.region === 'help_hero' || s.type === 'help_hero');
const topicsSec = layoutSections.find((s) => s.region === 'help_topics' || s.type === 'help_topics');
const heading = heroSec?.title || doc.heading;
const intro = heroSec?.subtitle || doc.intro;
const topicsMeta = topicsSec?.metadata || topicsSec?.metadata_json || {};
const topics = Array.isArray(topicsMeta.topics) && topicsMeta.topics.length > 0
? topicsMeta.topics.map((t: any) => ({
id: t.id || 'general',
title: t.title || t.name,
desc: t.desc || t.description,
href: t.href || t.link || '/help',
}))
: doc.topics;
return (
<div className="min-h-screen bg-[#F8F9FB] text-[#1E293B] flex flex-col font-sans">
<AnnouncementBar />
@ -92,12 +74,12 @@ export default function HelpCenterPage() {
<main className="flex-grow py-10 pb-20">
<div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-[900px]">
<h1 className="text-[28px] md:text-[32px] font-bold text-[#1E293B]">
{heading}
{doc.heading}
</h1>
<p className="text-[14px] text-gray-500 mt-2 max-w-2xl">{intro}</p>
<p className="text-[14px] text-gray-500 mt-2 max-w-2xl">{doc.intro}</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-8">
{topics.map((item: any) => {
{doc.topics.map((item) => {
const Icon = TOPIC_ICONS[item.id as keyof typeof TOPIC_ICONS] || CircleHelp;
return (
<Link

View file

@ -1,15 +1,12 @@
import type { Metadata, Viewport } from 'next';
import type { Metadata } from 'next';
import './globals.css';
import '../styles/mobile-overrides.css';
import { Suspense } from 'react';
import { AuthBootstrap } from '@/components/auth/AuthBootstrap';
import { StorefrontChrome } from '@/components/store/StorefrontChrome';
import { ClientModalsContainer } from '@/components/ClientModalsContainer';
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.',
@ -21,30 +18,14 @@ 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,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className="h-full overflow-x-hidden">
<body className="flex flex-col min-h-screen bg-[#F8F9FB] text-[#1E293B] font-sans antialiased overflow-x-hidden w-full max-w-full">
<Suspense fallback={null}>
<GoogleAnalytics />
</Suspense>
<html lang="en" className="h-full">
<body className="flex flex-col min-h-screen bg-[#F8F9FB] text-[#1E293B] font-sans antialiased">
<Toaster position="top-right" richColors closeButton expand={true} />
<AuthBootstrap />
<StorefrontChrome />

View file

@ -168,7 +168,7 @@ export default async function Home() {
};
return (
<div className="min-h-screen bg-[#F8F9FB] text-[#1E293B] flex flex-col font-sans overflow-x-hidden w-full max-w-full">
<div className="min-h-screen bg-[#F8F9FB] text-[#1E293B] flex flex-col font-sans">
<AnnouncementBar
config={sectionsData.announcement_bar}
isActive={show('announcement_bar')}
@ -183,7 +183,7 @@ export default async function Home() {
{/* After Header + Navbar so sticky chrome reserves full height */}
<StickyHeaderSpacer />
<main className="flex-grow min-w-0 w-full max-w-full overflow-x-hidden">
<main className="flex-grow">
{orderedKeys.map((key) => sectionNodes[key] ?? null)}
</main>

View file

@ -32,19 +32,16 @@ function telHref(phone: string): string {
export default function PaymentsPage() {
const [footer, setFooter] = useState<FooterInfo>(MOCK_FOOTER_INFO);
const [settings, setSettings] = useState<StorefrontSettings>({ store_name: 'iFixKart' });
const [layoutSections, setLayoutSections] = useState<any[]>([]);
useEffect(() => {
let cancelled = false;
Promise.all([
storefrontService.getFooterInfo(),
storefrontService.getSettings(),
storefrontService.getPageLayout('payments'),
]).then(([info, store, layout]) => {
]).then(([info, store]) => {
if (cancelled) return;
if (info) setFooter(info);
if (store) setSettings(store);
if (layout && layout.length > 0) setLayoutSections(layout);
});
return () => {
cancelled = true;
@ -57,10 +54,6 @@ export default function PaymentsPage() {
const doc = useMemo(() => buildPaymentsDoc(storeName), [storeName]);
const methods = (footer.payment_methods || []).filter((p) => p?.name || p?.icon_url);
const heroSec = layoutSections.find((s) => s.region === 'payments_hero' || s.type === 'payments_hero');
const heading = heroSec?.title || doc.heading;
const intro = heroSec?.subtitle || doc.intro;
return (
<div className="min-h-screen bg-[#F8F9FB] text-[#1E293B] flex flex-col font-sans">
<AnnouncementBar />
@ -71,9 +64,9 @@ export default function PaymentsPage() {
<main className="flex-grow py-10 pb-20">
<div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-[900px]">
<h1 className="text-[28px] md:text-[32px] font-bold text-[#1E293B]">
{heading}
{doc.heading}
</h1>
<p className="text-[14px] text-gray-500 mt-2 max-w-2xl">{intro}</p>
<p className="text-[14px] text-gray-500 mt-2 max-w-2xl">{doc.intro}</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-8">
{doc.highlights.map((item) => {

View file

@ -1,4 +1,3 @@
import type { Metadata } from 'next';
import React from 'react';
import { notFound } from 'next/navigation';
@ -10,7 +9,6 @@ import { FloatingButtons } from '@/components/FloatingButtons';
import { StickyHeaderSpacer } from '@/components/StickyHeaderSpacer';
import { catalogServerService } from '@/services/api/catalogServerService';
import { getImageUrl } from '@/lib/utils';
import { ProductInteractiveGrid } from '@/components/pdp/ProductInteractiveGrid';
@ -20,88 +18,6 @@ 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 = [
@ -114,8 +30,6 @@ const HIDDEN_SPEC_KEYS = [
'sku',
'barcode',
'compare_price',
'is_active',
'is_parent_feature',
];
function normalizeSpecKey(code: string): string {
@ -310,9 +224,8 @@ function groupSpecs(specifications: any[], product: any) {
return groups;
}
export default async function ProductDetailPage({ params, searchParams }: ProductDetailPageProps) {
export default async function ProductDetailPage({ params }: ProductDetailPageProps) {
const { slug } = await params;
const { variant: variantKey } = await searchParams;
if (!slug) {
return notFound();
@ -331,14 +244,8 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
}
const { product, reviews = [], related_products = [], specifications = [] } = data;
const validRatings = (reviews || [])
.map((r: any) => Number(r.rating))
.filter((r: number) => !isNaN(r) && r > 0);
const calculatedRating = validRatings.length > 0
? Number((validRatings.reduce((sum: number, r: number) => sum + r, 0) / validRatings.length).toFixed(1))
: (product.rating ? Number(product.rating) : 5.0);
const totalReviewsCount = reviews.length;
const related = related_products.slice(0, 5);
const comparisonProducts = [product, ...related_products.filter((p: any) => p.product_id !== product.product_id)].slice(0, 5);
const specGroups = groupSpecs(specifications, product);
const additionalInfoRows: { label: string; value: string }[] = [];
@ -481,58 +388,8 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
</table>
);
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: displayTitle,
image: [resolvedImageUrl],
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: variantOfferUrl,
priceCurrency: 'INR',
price: activeVariant?.price || 0,
priceValidUntil: '2027-12-31',
itemCondition: 'https://schema.org/NewCondition',
availability: (activeVariant?.price && Number(activeVariant?.price) > 0)
? 'https://schema.org/InStock'
: 'https://schema.org/OutOfStock',
seller: {
'@type': 'Organization',
name: 'iFixKart TechShop',
},
},
aggregateRating: totalReviewsCount > 0 ? {
'@type': 'AggregateRating',
ratingValue: String(calculatedRating),
reviewCount: String(totalReviewsCount),
} : undefined,
};
return (
<div className="min-h-screen bg-white text-[#1E293B] flex flex-col font-sans">
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<AnnouncementBar />
<Header />
<StickyHeaderSpacer />
@ -542,17 +399,12 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
<div className="container mx-auto px-4 sm:px-6 lg:px-8 py-5">
<ProductInteractiveGrid
product={product}
rating={calculatedRating}
initialReviewsCount={totalReviewsCount}
initialReviewsCount={reviews.length}
relatedProducts={related}
initialVariantSku={activeVariant?.sku}
/>
<div className="mt-10">
<ProductTabsWrapper
productId={product.product_id}
productName={product.name}
initialReviewsCount={reviews.length}
descriptionHtml={descriptionHtml}
specsHtml={specsHtml}
showSpecifications={product.show_specifications ?? true}
@ -561,8 +413,8 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
{related.length > 0 && <YouMayAlsoLike products={related} />}
{(product.variants?.length || 0) > 1 && (
<QuickComparisonTable product={product} />
{comparisonProducts.length > 0 && (
<QuickComparisonTable products={comparisonProducts} />
)}
</div>
</main>

View file

@ -94,7 +94,6 @@ export default function ServiceBookingPage() {
null | 'preparing' | 'verifying'
>(null);
const paymentHandledRef = useRef(false);
const isPrefillingRef = useRef(false);
// Dynamic CMS Layout Sections State
const [layoutCMS, setLayoutCMS] = useState<any[]>([]);
@ -253,73 +252,9 @@ export default function ServiceBookingPage() {
void loadLocations();
}, []);
// Pre-fill from URL
useEffect(() => {
if (typeof window === 'undefined') return;
const qs = new URLSearchParams(window.location.search);
const prefillBrandId = qs.get('brand_id');
const prefillSeriesId = qs.get('series_id');
const prefillModelId = qs.get('model_id');
const prefillServiceTypeId = qs.get('service_type_id');
const prefillVariantSku = qs.get('variant_sku');
if (prefillBrandId && prefillSeriesId && prefillModelId) {
isPrefillingRef.current = true;
const initFlow = async () => {
try {
const type = qs.get('device_type') || 'mobile';
setDeviceType(type);
const brandsData = await serviceBookingService.fetchBrands(type);
setBrands(brandsData);
const brandObj = brandsData.find((b: any) => b.brand_id === prefillBrandId);
if (brandObj) setSelectedBrand(brandObj);
const seriesData = await serviceBookingService.fetchSeriesByBrand(prefillBrandId, type);
setSeriesList(seriesData);
const seriesObj = seriesData.find((s: any) => s.series_id === prefillSeriesId);
if (seriesObj) setSelectedSeries(seriesObj);
const modelsData = await serviceBookingService.fetchModelsBySeries(prefillSeriesId);
setModels(modelsData);
const modelObj = modelsData.find((m: any) => m.model_id === prefillModelId);
if (modelObj) {
setSelectedModel(modelObj);
const config = await serviceBookingService.fetchRepairConfig(prefillModelId);
setRepairConfig(config);
if (config.categories && config.categories.length > 0) {
const categoryObj = prefillServiceTypeId
? config.categories.find((c: any) => c.service_type_id === prefillServiceTypeId)
: config.categories[0];
if (categoryObj) {
setSelectedCategory(categoryObj);
if (categoryObj.variants && categoryObj.variants.length > 0) {
const variantObj = prefillVariantSku
? categoryObj.variants.find((v: any) => v.name === prefillVariantSku)
: categoryObj.variants[0];
if (variantObj) {
setSelectedVariant(variantObj);
}
}
}
}
}
} catch (err) {
console.error("Error prefilling data", err);
} finally {
isPrefillingRef.current = false;
}
};
initFlow();
}
}, []);
// Load Brands when Device Type changes
useEffect(() => {
if (!deviceType || isPrefillingRef.current) return;
if (!deviceType) return;
loadBrands(deviceType);
}, [deviceType]);
@ -328,14 +263,12 @@ export default function ServiceBookingPage() {
try {
const data = await serviceBookingService.fetchBrands(type);
setBrands(data);
if (!isPrefillingRef.current) {
setSelectedBrand(null);
setSelectedSeries(null);
setSelectedModel(null);
setRepairConfig(null);
setSelectedCategory(null);
setSelectedVariant(null);
}
setSelectedBrand(null);
setSelectedSeries(null);
setSelectedModel(null);
setRepairConfig(null);
setSelectedCategory(null);
setSelectedVariant(null);
} catch (err: any) {
toast.error(err.message || 'Failed to load brands.');
} finally {
@ -543,7 +476,6 @@ export default function ServiceBookingPage() {
},
service_id: serviceId || 'OTHER_SERVICE',
custom_service_name: customServiceName || undefined,
quoted_price: selectedVariant.price,
customer_name: custName.trim() || undefined,
customer_email: custEmail.trim() || undefined,
device_type: deviceType,

View file

@ -28,9 +28,6 @@ import {
Smartphone,
Wrench,
ArrowRight,
Calendar,
Download,
ExternalLink,
} from 'lucide-react';
import { AnnouncementBar } from '@/layout/AnnouncementBar';
import { Header } from '@/layout/Header';
@ -99,81 +96,10 @@ function BookingSuccessContent() {
const needsVerify = searchParams.get('verify') === '1';
const [jobDetails, setJobDetails] = useState<any | null>(null);
const [calendarInvite, setCalendarInvite] = useState<any | null>(null);
const [layoutCMS, setLayoutCMS] = useState<any[]>([]);
const [verifyState, setVerifyState] = useState<'idle' | 'verifying' | 'done'>(
needsVerify ? 'verifying' : 'idle'
);
const [isRetrying, setIsRetrying] = useState(false);
const handleRetryPayment = async () => {
if (!jobId && !jobNoParam) return;
setIsRetrying(true);
try {
const loadRazorpayScript = (): Promise<boolean> => {
return new Promise((resolve) => {
if (document.querySelector('script[src="https://checkout.razorpay.com/v1/checkout.js"]')) {
resolve(true);
return;
}
const script = document.createElement('script');
script.src = 'https://checkout.razorpay.com/v1/checkout.js';
script.onload = () => resolve(true);
script.onerror = () => resolve(false);
document.body.appendChild(script);
});
};
const rzpLoaded = await loadRazorpayScript();
if (!rzpLoaded) {
throw new Error('Razorpay SDK failed to load. Please check your network connection.');
}
// If we don't have jobDetails loaded yet, use the query param ID
const targetId = jobDetails?.job_id || jobId || jobNoParam;
const pmtOrder = await serviceBookingService.initiateServicePayment(targetId, {
payment_type: 'ADVANCE',
amount: Math.max(1, Math.round(qAmount > 0 ? qAmount : 100)), // fallback to query amount or minimum
provider: 'RAZORPAY',
});
const rzpKey = pmtOrder.rzp_key_id || process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID || 'rzp_test_TTUzPFYF0hRV89';
const options = {
key: rzpKey,
amount: pmtOrder.amount,
currency: pmtOrder.currency || 'INR',
name: 'iFixKart Commerce',
description: `Advance Booking Deposit (${jobNoParam})`,
order_id: pmtOrder.rzp_order_id,
redirect: false,
handler: (response: any) => {
const qs = new URLSearchParams(searchParams.toString());
qs.set('payment_id', String(pmtOrder.payment_id || ''));
qs.set('amount', String(pmtOrder.amount));
qs.set('method', 'Razorpay');
qs.set('rzp_payment_id', String(response.razorpay_payment_id || ''));
qs.set('rzp_order_id', String(response.razorpay_order_id || ''));
qs.set('rzp_signature', String(response.razorpay_signature || ''));
qs.set('verify', '1');
router.replace(`/services/success?${qs.toString()}`);
},
modal: {
escape: true,
handleback: true,
confirm_close: true,
},
};
const rzp = new (window as any).Razorpay(options);
rzp.open();
} catch (err: any) {
toast.error(err.message || 'Failed to initiate payment retry.');
} finally {
setIsRetrying(false);
}
};
useEffect(() => {
void bootstrapAuth();
@ -280,16 +206,6 @@ function BookingSuccessContent() {
}
};
useEffect(() => {
const target = jobId || (jobNoParam && jobNoParam !== 'SRV-BOOKING' ? jobNoParam : '');
if (target) {
serviceBookingService
.fetchCalendarInvite(target)
.then((data) => setCalendarInvite(data))
.catch(() => setCalendarInvite(null));
}
}, [jobId, jobNoParam]);
const job = unwrapJob(jobDetails);
const payment = firstPayment(job);
const isPaid =
@ -448,65 +364,9 @@ function BookingSuccessContent() {
? 'is saved. Complete the advance payment to lock your technician slot.'
: 'is confirmed. Your advance payment is complete and our team is preparing your repair schedule.'}
</p>
{isPending && (
<div className="mt-4">
<button
type="button"
disabled={isRetrying}
onClick={handleRetryPayment}
className="px-6 py-2.5 bg-primary hover:bg-primary-hover text-white font-bold text-[13px] rounded-lg flex items-center gap-2"
>
{isRetrying ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<CreditCard className="w-4 h-4" />
)}
{isRetrying ? 'Loading...' : 'Complete Payment Now'}
</button>
</div>
)}
</div>
</div>
{calendarInvite && (
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-5 rounded-lg flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-start gap-3.5">
<div className="w-10 h-10 rounded-full bg-blue-600 text-white flex items-center justify-center shrink-0 mt-0.5">
<Calendar className="w-5 h-5" />
</div>
<div>
<div className="text-[11px] font-bold uppercase tracking-wider text-blue-700">Walk-In Calendar Invite</div>
<h4 className="text-[15px] font-bold text-gray-900 mt-0.5">
Slot: {new Date(calendarInvite.scheduled_start).toLocaleString('en-IN', { dateStyle: 'medium', timeStyle: 'short' })}
</h4>
<p className="text-[12px] text-gray-600 mt-1 max-w-xl">
Add this repair appointment to your personal calendar to receive automatic pre-service notifications and a reminder before your slot.
</p>
</div>
</div>
<div className="flex flex-wrap sm:flex-nowrap items-center gap-2 shrink-0">
<a
href={calendarInvite.google_calendar_url}
target="_blank"
rel="noopener noreferrer"
className="px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-[12px] font-bold rounded flex items-center gap-1.5 shadow-sm transition"
>
<Calendar className="w-3.5 h-3.5" />
Add to Google Calendar
<ExternalLink className="w-3 h-3 ml-0.5 opacity-80" />
</a>
<a
href={`http://localhost:8000${calendarInvite.ics_download_url}`}
download
className="px-4 py-2.5 bg-white hover:bg-gray-50 border border-gray-300 text-gray-800 text-[12px] font-semibold rounded flex items-center gap-1.5 shadow-sm transition"
>
<Download className="w-3.5 h-3.5" />
Download .ics Invite
</a>
</div>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div className="border border-[#e5e5e5] p-5 space-y-4">
<div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-[#222] border-b border-[#e5e5e5] pb-2">

View file

@ -25,8 +25,6 @@ import {
Image as ImageIcon,
Maximize2,
KeyRound,
Download,
ExternalLink,
} from 'lucide-react';
import { BlurHashImage } from '@/components/ui/BlurHashImage';
import { AnnouncementBar } from '@/layout/AnnouncementBar';
@ -63,7 +61,6 @@ export default function ServiceJobTrackingPage({
const { isAuthenticated, accessToken, authReady, bootstrapAuth } = useAuthStore();
const [job, setJob] = useState<any>(null);
const [calendarInvite, setCalendarInvite] = useState<any | null>(null);
const [loading, setLoading] = useState(true);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [actionLoading, setActionLoading] = useState(false);
@ -102,13 +99,6 @@ export default function ServiceJobTrackingPage({
job_id: item?.job_id || job_id,
job_no: item?.job_no,
});
if (item?.fulfillment_type === 'WALK_IN' || item?.appointment) {
serviceBookingService
.fetchCalendarInvite(item?.job_id || job_id)
.then((cal) => setCalendarInvite(cal))
.catch(() => setCalendarInvite(null));
}
} catch (err: any) {
setErrorMsg(err.message || 'Failed to retrieve tracking details.');
} finally {
@ -543,15 +533,10 @@ export default function ServiceJobTrackingPage({
})()}
{job.appointment && (
<div className="bg-white border border-[#e5e5e5] p-5 space-y-4 text-[13px]">
<div className="flex items-center justify-between border-b border-[#e5e5e5] pb-2">
<h4 className="font-semibold text-[#222] uppercase tracking-wider text-[11px]">
Booking Schedule
</h4>
<span className="text-[11px] font-bold text-blue-600 bg-blue-50 px-2 py-0.5 rounded">
Walk-In
</span>
</div>
<div className="bg-white border border-[#e5e5e5] p-5 space-y-3 text-[13px]">
<h4 className="font-semibold text-[#222] uppercase tracking-wider text-[11px] border-b border-[#e5e5e5] pb-2">
Booking Schedule
</h4>
<div className="flex items-start gap-3">
<Calendar className="w-5 h-5 text-primary shrink-0 mt-0.5" />
<div>
@ -565,46 +550,16 @@ export default function ServiceJobTrackingPage({
})}
</div>
<div className="text-gray-500 font-mono text-[12px] mt-0.5">
Slot:{' '}
Start:{' '}
{new Date(
job.appointment.scheduled_start
).toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
})}{' '}
–{' '}
{new Date(
job.appointment.scheduled_end
).toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
})}
</div>
</div>
</div>
{calendarInvite && (
<div className="pt-2 border-t border-[#f0f0f0] space-y-2">
<a
href={calendarInvite.google_calendar_url}
target="_blank"
rel="noopener noreferrer"
className="w-full py-2 px-3 bg-blue-600 hover:bg-blue-700 text-white font-bold text-[12px] rounded flex items-center justify-center gap-1.5 transition shadow-sm"
>
<Calendar className="w-3.5 h-3.5" />
Add to Google Calendar
<ExternalLink className="w-3 h-3 ml-0.5 opacity-80" />
</a>
<a
href={`http://localhost:8000${calendarInvite.ics_download_url}`}
download
className="w-full py-2 px-3 bg-gray-50 hover:bg-gray-100 border border-gray-200 text-gray-700 font-semibold text-[12px] rounded flex items-center justify-center gap-1.5 transition"
>
<Download className="w-3.5 h-3.5" />
Download .ics Calendar File
</a>
</div>
)}
</div>
)}

View file

@ -1,71 +0,0 @@
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

@ -15,10 +15,12 @@ import { StickyHeaderSpacer } from '@/components/StickyHeaderSpacer';
import { FloatingButtons } from '@/components/FloatingButtons';
import { useCartStore } from '@/store/cartStore';
import { ProductResponse } from '@/services/api/catalogService';
import { formatCatalogPriceLabel, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCatalogPriceLabel, getImageUrl } from '@/lib/utils';
function getProductImage(product: ProductResponse): string {
return resolveProductImage(product);
const fromProduct = product.images?.[0]?.image_url;
const fromVariant = product.variants?.[0]?.images?.[0]?.image_url;
return getImageUrl(fromProduct || fromVariant || '');
}
function getPriceLabel(product: ProductResponse): string {

View file

@ -1,59 +1,20 @@
"use client";
import React, { useState, useEffect, useCallback } from 'react';
import { usePathname } from 'next/navigation';
import React, { useState, useEffect } from 'react';
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();
};
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]);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
const scrollToTop = () => {
window.scrollTo({
@ -63,14 +24,8 @@ export const FloatingButtons: React.FC = () => {
};
return (
<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. */}
<div className="fixed bottom-6 right-6 z-50 flex flex-col gap-3">
{/* Scroll to Top */}
<AnimatePresence>
{showScrollTop && (
<motion.button

View file

@ -1,7 +1,7 @@
"use client";
import React, { useEffect, useState, useMemo } from 'react';
import { X, Folder, FolderOpen, ChevronDown, ArrowRight, LayoutGrid } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { X, Folder, LayoutGrid } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import { catalogService, CategoryResponse } from '@/services/api/catalogService';
@ -13,7 +13,6 @@ interface MobileDrawerProps {
export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) => {
const [categories, setCategories] = useState<CategoryResponse[]>([]);
const [expandedCats, setExpandedCats] = useState<Record<string, boolean>>({});
useEffect(() => {
if (isOpen) {
@ -23,26 +22,6 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
}
}, [isOpen]);
const toggleCategory = (catId: string) => {
setExpandedCats((prev) => ({
...prev,
[catId]: !prev[catId],
}));
};
const parentCategories = useMemo(() => {
const parents = categories.filter((c) => !c.parent_category_id);
return parents.map((parent) => {
const nestedSubs = parent.sub_categories || [];
const flatSubs = categories.filter((c) => c.parent_category_id === parent.category_id);
const subCategories = nestedSubs.length > 0 ? nestedSubs : flatSubs;
return {
...parent,
subCategories,
};
});
}, [categories]);
React.useEffect(() => {
if (!isOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
@ -52,22 +31,11 @@ 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: 'Top Deals', href: '/shop?tag=deals' },
{ name: 'Services', href: '/services' },
{ name: 'Services', href: '/service' },
{ name: 'Top Deals', href: '/shop' },
];
return (
@ -80,7 +48,7 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
animate={{ opacity: 0.5 }}
exit={{ opacity: 0 }}
onClick={onClose}
className="fixed inset-0 bg-black z-[115] xl:hidden"
className="fixed inset-0 bg-black z-50 xl:hidden"
/>
{/* Drawer Panel */}
@ -89,7 +57,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-[290px] max-w-[85vw] bg-white z-[120] xl:hidden flex flex-col justify-between shadow-xl overflow-y-auto overscroll-contain"
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"
>
<div>
{/* Header */}
@ -99,10 +67,9 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
</span>
<button
onClick={onClose}
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"
className="p-1.5 text-gray-400 hover:text-gray-650 hover:bg-gray-50 rounded-lg transition-colors"
>
<X size={22} />
<X size={20} />
</button>
</div>
@ -125,107 +92,29 @@ export const MobileDrawer: React.FC<MobileDrawerProps> = ({ isOpen, onClose }) =
</div>
{/* Categories */}
{parentCategories.length > 0 && (
{categories.length > 0 && (
<div className="p-4 text-left">
<h4 className="text-[11px] font-bold text-gray-400 uppercase tracking-widest mb-3">Categories</h4>
<ul className="space-y-1">
{parentCategories.map((cat) => {
const hasSubs = cat.subCategories && cat.subCategories.length > 0;
const isExpanded = !!expandedCats[cat.category_id];
return (
<li key={cat.category_id} className="rounded-lg overflow-hidden">
{hasSubs ? (
<div>
<button
type="button"
onClick={() => toggleCategory(cat.category_id)}
className={`w-full flex items-center justify-between py-2.5 px-2 rounded-lg text-sm font-semibold transition-colors cursor-pointer ${
isExpanded
? 'bg-primary/5 text-primary'
: 'text-gray-700 hover:text-primary hover:bg-gray-50'
}`}
>
<div className="flex items-center gap-2.5 min-w-0">
{isExpanded ? (
<FolderOpen size={16} className="text-primary shrink-0" />
) : (
<Folder size={16} className="text-primary/70 shrink-0" />
)}
<span className="truncate">{cat.name}</span>
</div>
<div className="flex items-center gap-1.5 shrink-0 ml-2">
<span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-gray-100 text-gray-500">
{cat.subCategories.length}
</span>
<ChevronDown
size={16}
className={`text-gray-400 transition-transform duration-200 ${
isExpanded ? 'rotate-180 text-primary' : ''
}`}
/>
</div>
</button>
{/* Subcategories Accordion */}
<AnimatePresence initial={false}>
{isExpanded && (
<motion.ul
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2, ease: 'easeInOut' }}
className="overflow-hidden pl-5 pr-2 py-1 space-y-1 bg-gray-50/70 rounded-b-lg border-l-2 border-primary/30 ml-4 my-1"
>
{/* View All Parent Category */}
<li>
<Link
href={`/shop?category=${encodeURIComponent(cat.slug)}`}
onClick={onClose}
className="flex items-center gap-2 py-1.5 text-xs font-bold text-primary hover:underline transition-colors"
>
<span>All {cat.name}</span>
<ArrowRight size={12} />
</Link>
</li>
{/* Subcategories */}
{cat.subCategories.map((sub) => (
<li key={sub.category_id}>
<Link
href={`/shop?category=${encodeURIComponent(sub.slug)}`}
onClick={onClose}
className="flex items-center gap-2 py-1.5 text-xs font-medium text-gray-600 hover:text-primary transition-colors"
>
<span className="w-1.5 h-1.5 rounded-full bg-gray-300 shrink-0" />
<span className="truncate">{sub.name}</span>
</Link>
</li>
))}
</motion.ul>
)}
</AnimatePresence>
</div>
) : (
<Link
href={`/shop?category=${encodeURIComponent(cat.slug)}`}
onClick={onClose}
className="flex items-center gap-2.5 py-2.5 px-2 rounded-lg text-sm font-semibold text-gray-700 hover:text-primary hover:bg-gray-50 transition-colors"
>
<Folder size={16} className="text-primary/70 shrink-0" />
<span className="truncate">{cat.name}</span>
</Link>
)}
</li>
);
})}
<ul className="space-y-3">
{categories.map((cat) => (
<li key={cat.category_id}>
<Link
href={`/shop?category=${encodeURIComponent(cat.slug)}`}
onClick={onClose}
className="flex items-center gap-3 text-sm font-semibold text-gray-650 hover:text-primary transition-colors"
>
<Folder size={15} className="text-primary/70" />
<span>{cat.name}</span>
</Link>
</li>
))}
</ul>
</div>
)}
</div>
{/* 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))]">
{/* Footer */}
<div className="p-4 border-t border-gray-100 text-xs text-gray-400 text-center font-medium bg-gray-50">
© {new Date().getFullYear()} iFixKart. All Rights Reserved.
</div>
</motion.div>

View file

@ -302,10 +302,10 @@ export const ProductCard: React.FC<ProductCardProps> = ({
<div
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className="bg-white p-3 sm:p-4 md:p-5 flex flex-col relative font-sans group/card h-full min-h-[330px] sm:min-h-[380px]"
className="bg-white p-4 md:p-5 flex flex-col relative font-sans group/card h-full min-h-[380px]"
>
{/* Badges — top right */}
<div className="absolute top-2.5 right-2.5 sm:top-3 sm:right-3 z-10 flex flex-col items-end gap-1">
<div className="absolute top-3 right-3 z-10 flex flex-col items-end gap-1">
{isOutOfStock ? (
<span className="bg-[#222] text-white text-[10px] font-bold px-1.5 py-0.5 leading-none uppercase tracking-wide">
Out of Stock
@ -318,12 +318,12 @@ export const ProductCard: React.FC<ProductCardProps> = ({
) : null}
</div>
{/* Hover actions — top left (always visible on touch/mobile, hover on desktop) */}
{/* Hover actions — top left */}
<div
className={`absolute left-2.5 top-2.5 sm:left-3 sm:top-3 z-20 flex flex-col gap-1.5 sm:gap-2 transition-all duration-200 ${
className={`absolute left-3 top-3 z-20 flex flex-col gap-2 transition-all duration-200 ${
isHovered
? 'opacity-100 translate-y-0'
: 'opacity-100 sm:opacity-0 sm:-translate-y-1 pointer-events-auto sm:pointer-events-none'
: 'opacity-0 -translate-y-1 pointer-events-none'
}`}
>
<button
@ -342,7 +342,7 @@ export const ProductCard: React.FC<ProductCardProps> = ({
<button
type="button"
onClick={handleCompareClick}
className={`hidden sm:flex ${iconBtn} ${isCompared ? '!bg-primary !text-white' : ''}`}
className={`${iconBtn} ${isCompared ? '!bg-primary !text-white' : ''}`}
title="Compare"
aria-label="Compare product"
>
@ -351,7 +351,7 @@ export const ProductCard: React.FC<ProductCardProps> = ({
<button
type="button"
onClick={handleQuickViewClick}
className={`hidden sm:flex ${iconBtn}`}
className={iconBtn}
title="Quick View"
aria-label="Quick view"
>
@ -360,7 +360,7 @@ export const ProductCard: React.FC<ProductCardProps> = ({
</div>
<Link href={href} className="flex flex-col items-center flex-1 select-none">
<div className="relative w-full h-[125px] sm:h-[150px] flex items-center justify-center mb-1">
<div className="relative w-full h-[150px] flex items-center justify-center mb-1">
{mainImageUrl ? (
<>
<BlurHashImage
@ -442,9 +442,6 @@ export const ProductCard: React.FC<ProductCardProps> = ({
<span className="text-[14px] font-bold text-[#111]">
{formatCurrency(product.price)}
</span>
<span className="text-[10px] text-gray-500 font-medium">
+18% GST
</span>
</>
)}
</div>

View file

@ -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,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"
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"
>
<button
type="button"

View file

@ -37,27 +37,6 @@ 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,
@ -157,7 +136,15 @@ 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">
<CategoryItemIcon src={item.image} alt={item.name} />
{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" />
)}
</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}

View file

@ -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-[85dvh] text-left"
className="bg-white w-full max-w-[740px] rounded-2xl shadow-2xl overflow-hidden relative flex flex-col max-h-[85vh] text-left"
>
{/* Header */}
<div className="bg-[#1E1E1E] text-white px-7 py-4 flex items-center justify-between">

View file

@ -1,46 +0,0 @@
'use client';
import React, { useEffect } from 'react';
import Script from 'next/script';
import { usePathname, useSearchParams } from 'next/navigation';
import { GA_MEASUREMENT_ID, trackPageView } from '@/lib/analytics';
export function GoogleAnalytics() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (pathname) {
const fullUrl = searchParams?.toString()
? `${pathname}?${searchParams.toString()}`
: pathname;
trackPageView(fullUrl);
}
}, [pathname, searchParams]);
if (!GA_MEASUREMENT_ID) return null;
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
/>
<Script
id="ga4-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_MEASUREMENT_ID}', {
page_path: window.location.pathname,
send_page_view: true
});
`,
}}
/>
</>
);
}

View file

@ -57,7 +57,6 @@ 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('');
@ -65,36 +64,21 @@ 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';
// Fetch HMAC-signed CSRF state token from backend
fetchCsrfToken();
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)
);
}
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
@ -115,7 +99,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
}
}, [isOpen]);
const handleAuthCodeSubmit = async (code: string, returnedState?: string) => {
const handleAuthCodeSubmit = async (code: string) => {
setLoading(true);
setError(null);
try {
@ -124,8 +108,6 @@ 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: {
@ -135,7 +117,7 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
credentials: 'include',
body: JSON.stringify({
code,
state: stateToSend,
state: csrfToken,
guest_session_id: guestSessionId,
redirect_uri: 'postmessage',
}),
@ -165,7 +147,6 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
onClose();
} catch (err: any) {
setError(err.message || 'Google authentication failed. Please try again.');
fetchCsrfToken();
} finally {
setLoading(false);
}
@ -224,26 +205,12 @@ 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, codeResponse.state);
if (codeResponse.code) handleAuthCodeSubmit(codeResponse.code);
},
onError: () => {
setError('Google Login popup was closed or authentication failed.');
fetchCsrfToken();
},
flow: 'auth-code',
state: csrfToken,
@ -338,12 +305,12 @@ function GoogleAuthInner({ isOpen, onClose, onSuccess }: GoogleAuthModalProps) {
<button
type="button"
onClick={handleGoogleClick}
disabled={loading || fetchingCsrf}
onClick={() => googleLogin()}
disabled={loading}
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...' : fetchingCsrf ? 'Securing session...' : 'Continue with Google'}
{loading ? 'Connecting Google...' : 'Continue with Google'}
</button>
</>
) : (

View file

@ -17,7 +17,7 @@ import { BrandSelector } from './BrandSelector';
import { SeriesSelector } from './SeriesSelector';
import { ModelSelector } from './ModelSelector';
import { StandardCatalog } from './StandardCatalog';
import { formatCurrency, getCatalogPriceInfo, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCurrency, getCatalogPriceInfo, getImageUrl } from '@/lib/utils';
import { ShoppingCart, Heart, ArrowLeftRight, Search, RotateCcw } from 'lucide-react';
import { useCartStore } from '@/store/cartStore';
import { mapProductCardToProductResponse } from '@/utils/productMapper';
@ -361,25 +361,23 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) {
{products.map((p) => {
const firstVariant = p.variants?.[0];
const { price, oldPrice: comparePrice } = getCatalogPriceInfo(p);
const primaryImage = resolveProductImage(p);
const primaryImage = getImageUrl(p.images?.[0]?.image_url);
const isWishlisted = wishlist.some((item) => item.product_id === p.product_id);
const isCompared = compareList.some((item) => item.product_id === p.product_id);
return (
<div
key={(p as any).variant_sku || p.product_id}
key={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>
<BlurHashImage
src={primaryImage}
alt={p.name}
fill
className="object-contain p-2 group-hover:scale-105 transition-transform duration-300"
/>
{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}
@ -413,7 +411,7 @@ export function ParentFeatureCatalog({ category }: ParentFeatureCatalogProps) {
<div className="flex-1 flex flex-col justify-between">
<div>
<Link href={p.variant_url || `/products/${p.slug}`}>
<Link href={`/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>

View file

@ -10,7 +10,7 @@ import {
CategoryResponse,
BrandResponse,
} from '@/services/api/catalogService';
import { formatCurrency, getCatalogPriceInfo, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCurrency, getCatalogPriceInfo, getImageUrl } from '@/lib/utils';
import {
applyCatalogFilters,
CATALOG_API_LIMIT,
@ -32,9 +32,6 @@ import {
ShoppingCart,
Star,
ChevronDown,
ChevronRight,
SlidersHorizontal,
X,
} from 'lucide-react';
import { useCartStore } from '@/store/cartStore';
import { AnnouncementBar } from '@/layout/AnnouncementBar';
@ -63,7 +60,7 @@ const HIGHLIGHTS: CatalogHighlight[] = [
'Hot Items',
];
type CollapseKey = 'categories' | 'brands' | 'highlight' | 'price';
type CollapseKey = 'categories' | 'brands' | 'highlight' | 'price' | 'rating';
function mapApiProduct(p: any): ProductResponse {
return mapProductCardToProductResponse(p);
@ -84,13 +81,12 @@ 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 = resolveProductImage(product);
const image = getImageUrl(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);
@ -102,7 +98,7 @@ function CatalogProductCard({
e.stopPropagation();
if (!variant) return;
if (hasOptions) {
window.location.href = productUrl;
window.location.href = `/products/${product.slug}`;
return;
}
void addToCart(product, variant, 1);
@ -111,7 +107,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={productUrl} className="relative w-36 h-36 shrink-0 bg-white">
<Link href={`/products/${product.slug}`} 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}%
@ -125,7 +121,7 @@ function CatalogProductCard({
</Link>
<div className="flex-1 min-w-0 flex flex-col justify-center">
<Link
href={productUrl}
href={`/products/${product.slug}`}
className="text-[14px] font-semibold text-[#222] hover:text-primary line-clamp-2 mb-1.5"
>
{product.name}
@ -219,7 +215,7 @@ function CatalogProductCard({
</div>
<Link
href={productUrl}
href={`/products/${product.slug}`}
className="relative flex-1 flex items-center justify-center min-h-[160px] mb-3"
>
{image ? (
@ -237,7 +233,7 @@ function CatalogProductCard({
<div className="text-left mt-auto">
<Link
href={productUrl}
href={`/products/${product.slug}`}
className="block text-[13px] font-semibold text-[#222] hover:text-primary line-clamp-2 leading-snug min-h-[36px] mb-1.5"
>
{product.name}
@ -301,29 +297,26 @@ export function StandardCatalog({
brandParam,
searchQuery,
}: StandardCatalogProps) {
const router = useRouter();
const [productPool, setProductPool] = useState<ProductResponse[]>([]);
const [categories, setCategories] = useState<CategoryResponse[]>([]);
const [brands, setBrands] = useState<BrandResponse[]>([]);
const [selectedCategory, setSelectedCategory] = useState<string>(
categoryParam || initialCategory?.category_id || 'all'
);
const [selectedBrand, setSelectedBrand] = useState<string>(brandParam || 'all');
const [selectedCategory, setSelectedCategory] = useState('all');
const [selectedBrand, setSelectedBrand] = useState('all');
const [highlight, setHighlight] = useState<CatalogHighlight>('All Products');
const [priceRangeId, setPriceRangeId] = useState('all');
const [selectedRating, setSelectedRating] = useState<number | null>(null);
const [sortBy, setSortBy] = useState('default');
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
const [page, setPage] = useState(1);
const [isLoading, setIsLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [isMobileFilterOpen, setIsMobileFilterOpen] = useState(false);
const [expandedCategoryIds, setExpandedCategoryIds] = useState<Record<string, boolean>>({});
const fetchIdRef = useRef(0);
const [collapsed, setCollapsed] = useState<Record<CollapseKey, boolean>>({
categories: false,
brands: false,
highlight: false,
price: false,
rating: false,
});
const [allProductsTotal, setAllProductsTotal] = useState<number>(0);
const [categoryCounts, setCategoryCounts] = useState<Record<string, number>>({});
@ -336,45 +329,10 @@ export function StandardCatalog({
}).catch(() => {});
}, []);
const toggleCollapse = (key: CollapseKey) =>
setCollapsed((prev) => ({ ...prev, [key]: !prev[key] }));
// Synchronize URL search params seamlessly
const syncUrlParams = (catId: string, brandId: string) => {
if (typeof window === 'undefined') return;
const currentParams = new URLSearchParams(window.location.search);
if (catId && catId !== 'all') {
const cat = categories.find(
(c) => c.category_id === catId || c.slug.toLowerCase() === catId.toLowerCase()
);
currentParams.set('category', cat?.slug || catId);
} else {
currentParams.delete('category');
}
if (brandId && brandId !== 'all') {
const b = brands.find(
(br) => br.brand_id === brandId || br.slug.toLowerCase() === brandId.toLowerCase()
);
currentParams.set('brand', b?.slug || brandId);
} else {
currentParams.delete('brand');
}
const qs = currentParams.toString();
router.replace(`/shop${qs ? `?${qs}` : ''}`, { scroll: false });
};
const handleCategorySelect = (catId: string) => {
const nextCat = selectedCategory === catId ? 'all' : catId;
setSelectedCategory(nextCat);
syncUrlParams(nextCat, selectedBrand);
};
const handleBrandSelect = (brandId: string) => {
const nextBrand = selectedBrand === brandId ? 'all' : brandId;
setSelectedBrand(nextBrand);
syncUrlParams(selectedCategory, nextBrand);
};
useEffect(() => {
catalogService.getCategories().then((catData) => {
setCategories(catData);
@ -396,42 +354,12 @@ export function StandardCatalog({
setSelectedCategory(found?.category_id || categoryParam);
} else if (initialCategory) {
setSelectedCategory(initialCategory.category_id);
} else {
setSelectedCategory('all');
}
});
}, [categoryParam, initialCategory]);
// Group root categories and their child subcategories
const rootCategories = useMemo(() => {
return categories.filter((c) => !c.parent_category_id);
}, [categories]);
const subCategoriesMap = useMemo(() => {
const map: Record<string, CategoryResponse[]> = {};
for (const cat of categories) {
if (cat.parent_category_id) {
if (!map[cat.parent_category_id]) map[cat.parent_category_id] = [];
map[cat.parent_category_id].push(cat);
}
}
return map;
}, [categories]);
// Auto-expand active category parent in accordion
useEffect(() => {
if (selectedCategory && selectedCategory !== 'all') {
const found = categories.find(
(c) =>
c.category_id === selectedCategory ||
c.slug.toLowerCase() === selectedCategory.toLowerCase()
);
if (found?.parent_category_id) {
setExpandedCategoryIds((prev) => ({ ...prev, [found.parent_category_id!]: true }));
} else if (found?.category_id) {
setExpandedCategoryIds((prev) => ({ ...prev, [found.category_id]: true }));
}
}
}, [selectedCategory, categories]);
useEffect(() => {
const activeCatId = selectedCategory === 'all' ? undefined : selectedCategory;
catalogService.getBrands(activeCatId).then((brandData) => {
@ -457,6 +385,7 @@ export function StandardCatalog({
searchQuery,
highlight,
priceRangeId,
selectedRating,
sortBy,
]);
@ -471,11 +400,7 @@ export function StandardCatalog({
};
if (selectedCategory !== 'all') paramsBase.category = selectedCategory;
if (selectedBrand !== 'all') paramsBase.brand = selectedBrand;
if (searchQuery) {
paramsBase.search = searchQuery;
// Sunsky-style: keyword searches expand each active variant into its own card
paramsBase.expand_variants = 'true';
}
if (searchQuery) paramsBase.search = searchQuery;
const accumulated: ProductResponse[] = [];
const seen = new Set<string>();
@ -496,10 +421,8 @@ export function StandardCatalog({
let added = 0;
for (const product of mapped) {
// 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);
if (seen.has(product.product_id)) continue;
seen.add(product.product_id);
accumulated.push(product);
added += 1;
}
@ -527,11 +450,22 @@ export function StandardCatalog({
const filteredProducts = useMemo(() => {
return applyCatalogFilters(productPool, {
priceRangeId,
selectedRating: null,
selectedRating,
highlight,
sortBy,
});
}, [productPool, priceRangeId, highlight, sortBy]);
}, [productPool, priceRangeId, selectedRating, highlight, sortBy]);
const ratingFilterPool = useMemo(
() =>
applyCatalogFilters(productPool, {
priceRangeId,
selectedRating: null,
highlight,
sortBy: 'default',
}),
[productPool, priceRangeId, highlight]
);
const displayed = useMemo(
() => filteredProducts.slice(0, page * CATALOG_PAGE_SIZE),
@ -548,225 +482,18 @@ export function StandardCatalog({
setSelectedBrand('all');
setHighlight('All Products');
setPriceRangeId('all');
setSelectedRating(null);
setSortBy('default');
setPage(1);
if (typeof window !== 'undefined') {
const currentParams = new URLSearchParams(window.location.search);
currentParams.delete('category');
currentParams.delete('brand');
currentParams.delete('search');
const qs = currentParams.toString();
router.replace(`/shop${qs ? `?${qs}` : ''}`, { scroll: false });
}
};
const handleLoadMore = () => {
setLoadingMore(true);
setPage((p) => p + 1);
// next paint after slice grows
requestAnimationFrame(() => setLoadingMore(false));
};
const activeFiltersCount = useMemo(() => {
let count = 0;
if (selectedCategory !== 'all') count++;
if (selectedBrand !== 'all') count++;
if (highlight !== 'All Products') count++;
if (priceRangeId !== 'all') count++;
return count;
}, [selectedCategory, selectedBrand, highlight, priceRangeId]);
// Reusable Filter Cards Component (used in both desktop sidebar & mobile drawer)
const renderFiltersContent = () => (
<div className="space-y-4">
{/* 1. Categories Accordion */}
<FilterCard
title="Shop By Categories"
open={!collapsed.categories}
onToggle={() => toggleCollapse('categories')}
>
<div className="pt-3 space-y-2 max-h-80 overflow-y-auto pr-1">
<label className="flex items-center justify-between text-[13px] cursor-pointer group py-1">
<span className="flex items-center gap-2.5">
<input
type="checkbox"
checked={selectedCategory === 'all'}
onChange={() => handleCategorySelect('all')}
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer shrink-0"
/>
<span className={selectedCategory === 'all' ? 'text-primary font-semibold' : 'text-gray-700'}>
All Categories
</span>
</span>
<span className="text-gray-400 text-xs shrink-0">({allProductsTotal || 0})</span>
</label>
{rootCategories.map((parent) => {
const isParentActive =
selectedCategory === parent.category_id ||
selectedCategory.toLowerCase() === parent.slug.toLowerCase();
const parentCount =
categoryCounts[parent.category_id] ??
categoryCounts[parent.slug] ??
parent.product_count ??
0;
const subs = subCategoriesMap[parent.category_id] || parent.sub_categories || [];
const hasSubs = subs.length > 0;
const isExpanded = !!expandedCategoryIds[parent.category_id];
return (
<div key={parent.category_id} className="space-y-1">
<div className="flex items-center justify-between text-[13px] group">
<label className="flex items-center gap-2.5 min-w-0 cursor-pointer flex-1 py-1">
<input
type="checkbox"
checked={isParentActive}
onChange={() => handleCategorySelect(parent.category_id)}
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer shrink-0"
/>
<span className={`truncate ${isParentActive ? 'text-primary font-semibold' : 'text-gray-700 group-hover:text-primary'}`}>
{parent.name}
</span>
</label>
<div className="flex items-center gap-1.5 shrink-0 ml-1">
<span className="text-gray-400 text-xs">({parentCount})</span>
{hasSubs && (
<button
type="button"
onClick={(e) => {
e.preventDefault();
setExpandedCategoryIds((prev) => ({
...prev,
[parent.category_id]: !prev[parent.category_id],
}));
}}
className="p-1 text-gray-400 hover:text-gray-700 rounded hover:bg-gray-100 transition-colors"
aria-label={`Toggle ${parent.name} subcategories`}
>
<ChevronDown
size={14}
className={`transition-transform duration-200 ${isExpanded ? 'rotate-180' : ''}`}
/>
</button>
)}
</div>
</div>
{hasSubs && isExpanded && (
<div className="pl-6 pr-1 py-1 space-y-1.5 border-l-2 border-gray-100 ml-1.5">
{subs.map((sub) => {
const isSubActive =
selectedCategory === sub.category_id ||
selectedCategory.toLowerCase() === sub.slug.toLowerCase();
const subCount =
categoryCounts[sub.category_id] ??
categoryCounts[sub.slug] ??
sub.product_count ??
0;
return (
<label
key={sub.category_id}
className="flex items-center justify-between text-[12.5px] cursor-pointer group py-0.5"
>
<span className="flex items-center gap-2 min-w-0">
<input
type="checkbox"
checked={isSubActive}
onChange={() => handleCategorySelect(sub.category_id)}
className="w-3 h-3 rounded border-gray-300 text-primary accent-primary cursor-pointer shrink-0"
/>
<span className={`truncate ${isSubActive ? 'text-primary font-semibold' : 'text-gray-600 group-hover:text-primary'}`}>
{sub.name}
</span>
</span>
<span className="text-gray-400 text-[11px] shrink-0">({subCount})</span>
</label>
);
})}
</div>
)}
</div>
);
})}
</div>
</FilterCard>
{/* 2. Brands */}
<FilterCard title="Brands" open={!collapsed.brands} onToggle={() => toggleCollapse('brands')}>
<div className="pt-3 space-y-2.5 max-h-56 overflow-y-auto pr-1">
<label className="flex items-center gap-2.5 text-[13px] cursor-pointer">
<input
type="checkbox"
checked={selectedBrand === 'all'}
onChange={() => handleBrandSelect('all')}
className="w-3.5 h-3.5 rounded border-gray-300 accent-primary cursor-pointer"
/>
<span className={selectedBrand === 'all' ? 'text-primary font-semibold' : 'text-gray-600'}>
All Brands
</span>
</label>
{brands.map((brand) => {
const checked = selectedBrand === brand.brand_id;
return (
<label key={brand.brand_id} className="flex items-center gap-2.5 text-[13px] cursor-pointer">
<input
type="checkbox"
checked={checked}
onChange={() => handleBrandSelect(brand.brand_id)}
className="w-3.5 h-3.5 rounded border-gray-300 accent-primary cursor-pointer"
/>
<span className={checked ? 'text-primary font-semibold' : 'text-gray-600'}>
{brand.name}
</span>
</label>
);
})}
</div>
</FilterCard>
{/* 3. Highlight */}
<FilterCard
title="Highlight"
open={!collapsed.highlight}
onToggle={() => toggleCollapse('highlight')}
>
<div className="pt-3 space-y-2">
{HIGHLIGHTS.map((item) => (
<button
key={item}
type="button"
onClick={() => setHighlight(item)}
className={`block w-full text-left text-[13px] py-0.5 cursor-pointer ${
highlight === item ? 'text-primary font-semibold' : 'text-gray-600 hover:text-primary'
}`}
>
{item}
</button>
))}
</div>
</FilterCard>
{/* 4. Price Filter */}
<FilterCard title="Price Filter" open={!collapsed.price} onToggle={() => toggleCollapse('price')}>
<div className="pt-3 space-y-2">
{CATALOG_PRICE_RANGES.map((range) => (
<button
key={range.id}
type="button"
onClick={() => setPriceRangeId(range.id)}
className={`block w-full text-left text-[13px] py-0.5 cursor-pointer ${
priceRangeId === range.id
? 'text-primary font-semibold'
: 'text-gray-600 hover:text-primary'
}`}
>
{range.label}
</button>
))}
</div>
</FilterCard>
</div>
);
return (
<div className="min-h-screen bg-white text-[#1E293B] flex flex-col font-sans">
<AnnouncementBar />
@ -776,110 +503,177 @@ export function StandardCatalog({
<main className="flex-grow pb-16">
<div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6 max-w-[1400px]">
{/* Mobile Filter & Sort Bar (Visible on mobile/tablet < lg) */}
<div className="lg:hidden mb-4 flex items-center justify-between gap-3 bg-gray-50 p-3 rounded-lg border border-gray-200">
<button
type="button"
onClick={() => setIsMobileFilterOpen(true)}
className="flex items-center gap-2 px-3.5 py-2 bg-white border border-gray-300 rounded-md shadow-xs text-[13px] font-semibold text-gray-800 hover:border-primary active:bg-gray-50 transition-colors cursor-pointer"
>
<SlidersHorizontal size={14} className="text-primary" />
<span>Filters</span>
{activeFiltersCount > 0 && (
<span className="w-5 h-5 rounded-full bg-primary text-white text-[11px] font-bold flex items-center justify-center">
{activeFiltersCount}
</span>
)}
</button>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 font-medium hidden sm:inline">Sort:</span>
<div className="relative">
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
className="appearance-none bg-white border border-gray-300 rounded-md pl-2.5 pr-7 py-2 text-[12px] font-medium text-gray-700 cursor-pointer focus:outline-none focus:border-primary"
>
<option value="default">Default</option>
<option value="newest">Newest</option>
<option value="price-low">Price: Low to High</option>
<option value="price-high">Price: High to Low</option>
<option value="a-z">A–Z</option>
</select>
<ChevronDown
size={12}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"
/>
</div>
</div>
</div>
{/* Active Filter Chips */}
{activeFiltersCount > 0 && (
<div className="mb-4 flex flex-wrap items-center gap-2 text-xs">
<span className="text-gray-500 font-medium">Active:</span>
{selectedCategory !== 'all' && (
<button
type="button"
onClick={() => handleCategorySelect('all')}
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
>
<span>
{categories.find(
(c) => c.category_id === selectedCategory || c.slug.toLowerCase() === selectedCategory.toLowerCase()
)?.name || 'Category'}
</span>
<X size={12} />
</button>
)}
{selectedBrand !== 'all' && (
<button
type="button"
onClick={() => handleBrandSelect('all')}
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
>
<span>
{brands.find(
(b) => b.brand_id === selectedBrand || b.slug.toLowerCase() === selectedBrand.toLowerCase()
)?.name || 'Brand'}
</span>
<X size={12} />
</button>
)}
{priceRangeId !== 'all' && (
<button
type="button"
onClick={() => setPriceRangeId('all')}
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
>
<span>{CATALOG_PRICE_RANGES.find((r) => r.id === priceRangeId)?.label}</span>
<X size={12} />
</button>
)}
{highlight !== 'All Products' && (
<button
type="button"
onClick={() => setHighlight('All Products')}
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-primary/10 text-primary font-medium rounded-full hover:bg-primary/20 transition-colors cursor-pointer"
>
<span>{highlight}</span>
<X size={12} />
</button>
)}
<button
type="button"
onClick={resetFilters}
className="text-xs text-gray-500 hover:text-red-600 underline ml-1 cursor-pointer"
>
Reset All
</button>
</div>
)}
<div className="flex flex-col lg:flex-row gap-7 items-start">
{/* Desktop Sidebar: hidden on mobile (< lg), shown on lg+ */}
<aside className="hidden lg:block w-[260px] shrink-0 space-y-4">
{renderFiltersContent()}
<aside className="w-full lg:w-[260px] shrink-0 space-y-4">
<FilterCard
title="Shop By Categories"
open={!collapsed.categories}
onToggle={() => toggleCollapse('categories')}
>
<div className="pt-3 space-y-2.5">
<label className="flex items-center justify-between text-[13px] cursor-pointer group">
<span className="flex items-center gap-2.5">
<input
type="checkbox"
checked={selectedCategory === 'all'}
onChange={() => setSelectedCategory('all')}
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer"
/>
<span className={selectedCategory === 'all' ? 'text-primary font-semibold' : 'text-gray-600'}>
Our Store
</span>
</span>
<span className="text-gray-400">({allProductsTotal})</span>
</label>
{categories.map((cat) => {
const checked =
selectedCategory === cat.category_id ||
selectedCategory.toLowerCase() === cat.slug.toLowerCase();
const catCount =
categoryCounts[cat.category_id] ??
categoryCounts[cat.slug] ??
(cat as any).product_count;
return (
<label
key={cat.category_id}
className="flex items-center justify-between text-[13px] cursor-pointer"
>
<span className="flex items-center gap-2.5 min-w-0">
<input
type="checkbox"
checked={checked}
onChange={() => setSelectedCategory(checked ? 'all' : cat.category_id)}
className="w-3.5 h-3.5 rounded border-gray-300 text-primary accent-primary cursor-pointer"
/>
<span className={`truncate ${checked ? 'text-primary font-semibold' : 'text-gray-600'}`}>
{cat.name}
</span>
</span>
{catCount != null && (
<span className="text-gray-400 shrink-0">
({catCount})
</span>
)}
</label>
);
})}
</div>
</FilterCard>
<FilterCard title="Brands" open={!collapsed.brands} onToggle={() => toggleCollapse('brands')}>
<div className="pt-3 space-y-2.5 max-h-56 overflow-y-auto">
<label className="flex items-center gap-2.5 text-[13px] cursor-pointer">
<input
type="checkbox"
checked={selectedBrand === 'all'}
onChange={() => setSelectedBrand('all')}
className="w-3.5 h-3.5 rounded border-gray-300 accent-primary cursor-pointer"
/>
<span className={selectedBrand === 'all' ? 'text-primary font-semibold' : 'text-gray-600'}>
All Brands
</span>
</label>
{brands.map((brand) => {
const checked = selectedBrand === brand.brand_id;
return (
<label key={brand.brand_id} className="flex items-center gap-2.5 text-[13px] cursor-pointer">
<input
type="checkbox"
checked={checked}
onChange={() => setSelectedBrand(checked ? 'all' : brand.brand_id)}
className="w-3.5 h-3.5 rounded border-gray-300 accent-primary cursor-pointer"
/>
<span className={checked ? 'text-primary font-semibold' : 'text-gray-600'}>
{brand.name}
</span>
</label>
);
})}
</div>
</FilterCard>
<FilterCard
title="Highlight"
open={!collapsed.highlight}
onToggle={() => toggleCollapse('highlight')}
>
<div className="pt-3 space-y-2">
{HIGHLIGHTS.map((item) => (
<button
key={item}
type="button"
onClick={() => setHighlight(item)}
className={`block w-full text-left text-[13px] py-0.5 cursor-pointer ${
highlight === item ? 'text-primary font-semibold' : 'text-gray-600 hover:text-primary'
}`}
>
{item}
</button>
))}
</div>
</FilterCard>
<FilterCard title="Price Filter" open={!collapsed.price} onToggle={() => toggleCollapse('price')}>
<div className="pt-3 space-y-2">
{CATALOG_PRICE_RANGES.map((range) => (
<button
key={range.id}
type="button"
onClick={() => setPriceRangeId(range.id)}
className={`block w-full text-left text-[13px] py-0.5 cursor-pointer ${
priceRangeId === range.id
? 'text-primary font-semibold'
: 'text-gray-600 hover:text-primary'
}`}
>
{range.label}
</button>
))}
</div>
</FilterCard>
<FilterCard
title="Average rating"
open={!collapsed.rating}
onToggle={() => toggleCollapse('rating')}
>
<div className="pt-3 space-y-1">
{[5, 4, 3, 2, 1].map((stars) => {
const active = selectedRating === stars;
const matchCount = ratingFilterPool.filter((p) =>
productMatchesRating(p, stars)
).length;
return (
<button
key={stars}
type="button"
aria-pressed={active}
onClick={() =>
setSelectedRating(selectedRating === stars ? null : stars)
}
className={`flex items-center justify-between w-full rounded-md px-2 py-1.5 -mx-2 text-[13px] cursor-pointer ${
active
? 'bg-[#f3f6fb] text-primary ring-1 ring-[#d7e3f4]'
: 'text-gray-600 hover:bg-gray-50'
}`}
>
<span className="flex items-center gap-0.5 text-amber-400">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
size={12}
className={i < stars ? 'fill-amber-400' : 'text-gray-200'}
/>
))}
</span>
<span className={active ? 'text-primary' : 'text-gray-400'}>
({stars}+) {isLoading ? '' : matchCount}
</span>
</button>
);
})}
</div>
</FilterCard>
</aside>
<div className="flex-1 min-w-0 w-full">
@ -959,13 +753,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 as any).variant_sku || p.variant_url || p.product_id} product={p} viewMode="grid" />
<CatalogProductCard key={p.product_id} product={p} viewMode="grid" />
))}
</div>
) : (
<div className="border border-[#e8e8e8] rounded-sm overflow-hidden">
{displayed.map((p) => (
<CatalogProductCard key={(p as any).variant_sku || p.variant_url || p.product_id} product={p} viewMode="list" />
<CatalogProductCard key={p.product_id} product={p} viewMode="list" />
))}
</div>
)}
@ -987,64 +781,6 @@ export function StandardCatalog({
</div>
</main>
{/* Slide-over Mobile Filter Drawer */}
{isMobileFilterOpen && (
<div className="fixed inset-0 z-[100] lg:hidden flex justify-end">
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 backdrop-blur-xs transition-opacity"
onClick={() => setIsMobileFilterOpen(false)}
/>
{/* Drawer Sheet */}
<div className="relative z-10 w-full max-w-[320px] bg-white h-full flex flex-col shadow-2xl animate-in slide-in-from-right duration-300">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<div className="flex items-center gap-2">
<SlidersHorizontal size={16} className="text-primary" />
<h3 className="text-base font-bold text-gray-900">Filters</h3>
{activeFiltersCount > 0 && (
<span className="w-5 h-5 rounded-full bg-primary text-white text-[11px] font-bold flex items-center justify-center">
{activeFiltersCount}
</span>
)}
</div>
<button
type="button"
onClick={() => setIsMobileFilterOpen(false)}
className="p-1.5 text-gray-400 hover:text-gray-700 rounded-full hover:bg-gray-100 cursor-pointer"
aria-label="Close filters"
>
<X size={18} />
</button>
</div>
{/* Scrollable Body */}
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{renderFiltersContent()}
</div>
{/* Sticky Footer */}
<div className="p-4 border-t border-gray-100 bg-white flex items-center gap-3">
<button
type="button"
onClick={resetFilters}
className="flex-1 py-2.5 px-3 border border-gray-300 text-gray-700 text-xs font-semibold rounded-lg hover:bg-gray-50 cursor-pointer"
>
Reset All
</button>
<button
type="button"
onClick={() => setIsMobileFilterOpen(false)}
className="flex-1 py-2.5 px-3 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 shadow-sm cursor-pointer"
>
Apply ({totalProducts})
</button>
</div>
</div>
</div>
)}
<Footer />
<FloatingButtons />
</div>

View file

@ -18,10 +18,7 @@ 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)]"
style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}
>
<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="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">

View file

@ -14,12 +14,7 @@ import {
type StorefrontSettings,
MOCK_FOOTER_INFO,
} from '@/services/api/storefrontService';
import {
buildPrivacyDoc,
buildTermsDoc,
type LegalDoc,
type LegalSection,
} from '@/lib/legalContent';
import { buildPrivacyDoc, buildTermsDoc } from '@/lib/legalContent';
export type LegalTab = 'terms' | 'privacy';
@ -31,7 +26,6 @@ export function LegalPage({ initialTab }: { initialTab: LegalTab }) {
const [tab, setTab] = useState<LegalTab>(initialTab);
const [footer, setFooter] = useState<FooterInfo>(MOCK_FOOTER_INFO);
const [settings, setSettings] = useState<StorefrontSettings>({ store_name: 'iFixKart' });
const [layoutSections, setLayoutSections] = useState<any[]>([]);
useEffect(() => {
setTab(initialTab);
@ -42,12 +36,10 @@ export function LegalPage({ initialTab }: { initialTab: LegalTab }) {
Promise.all([
storefrontService.getFooterInfo(),
storefrontService.getSettings(),
storefrontService.getPageLayout('terms'),
]).then(([info, store, layout]) => {
]).then(([info, store]) => {
if (cancelled) return;
if (info) setFooter(info);
if (store) setSettings(store);
if (layout && layout.length > 0) setLayoutSections(layout);
});
return () => {
cancelled = true;
@ -59,27 +51,10 @@ export function LegalPage({ initialTab }: { initialTab: LegalTab }) {
const email = footer.email || '';
const address = footer.address || '';
const termsSec = layoutSections.find((s) => s.region === 'terms_clauses' || s.type === 'terms_clauses');
const privacySec = layoutSections.find((s) => s.region === 'privacy_clauses' || s.type === 'privacy_clauses');
const doc = useMemo<LegalDoc>(() => {
const defaultDoc = tab === 'privacy' ? buildPrivacyDoc(storeName) : buildTermsDoc(storeName);
const activeSec = tab === 'privacy' ? privacySec : termsSec;
const meta = activeSec?.metadata || activeSec?.metadata_json || {};
if (Array.isArray(meta.sections) && meta.sections.length > 0) {
return {
heading: activeSec?.title || defaultDoc.heading,
intro: activeSec?.subtitle || defaultDoc.intro,
sections: meta.sections.map((s: any, idx: number): LegalSection => ({
id: s.id || `custom-${idx}`,
title: s.title || `Section ${idx + 1}`,
paragraphs: Array.isArray(s.paragraphs) ? s.paragraphs : [s.content || s.text || ''],
})),
};
}
return defaultDoc;
}, [tab, storeName, termsSec, privacySec]);
const doc = useMemo(
() => (tab === 'privacy' ? buildPrivacyDoc(storeName) : buildTermsDoc(storeName)),
[tab, storeName]
);
return (
<div className="min-h-screen bg-[#F8F9FB] text-[#1E293B] flex flex-col font-sans">

View file

@ -19,23 +19,13 @@ import {
HelpCircle,
GitCompare,
ChevronUp,
ChevronDown,
Wrench,
Sparkles,
Zap,
MapPin,
Clock,
Star,
ChevronDown
} from 'lucide-react';
import { requireLoginForCheckout } from '@/lib/requireLoginForCheckout';
import { trackViewItem, trackAddToCart, trackBeginCheckout } from '@/lib/analytics';
interface ProductInteractiveGridProps {
product: ProductResponse;
initialReviewsCount: number;
relatedProducts?: ProductResponse[];
initialVariantSku?: string;
rating?: number;
}
const FALLBACK_TECH_IMAGES: string[] = ['/images/placeholder-product.webp'];
@ -87,62 +77,13 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
product,
initialReviewsCount,
relatedProducts = [],
initialVariantSku,
rating: propRating,
}) => {
const searchParams = useSearchParams();
const router = useRouter();
const [currentRating, setCurrentRating] = useState<number>(() => {
if (typeof propRating === 'number' && !isNaN(propRating)) return propRating;
if (product.rating !== undefined && product.rating !== null) return Number(product.rating);
return 5.0;
});
const [currentReviewsCount, setCurrentReviewsCount] = useState<number>(initialReviewsCount || 0);
useEffect(() => {
if (typeof propRating === 'number' && !isNaN(propRating)) {
setCurrentRating(propRating);
} else if (product.rating !== undefined && product.rating !== null) {
setCurrentRating(Number(product.rating));
}
}, [propRating, product.rating]);
useEffect(() => {
setCurrentReviewsCount(initialReviewsCount || 0);
}, [initialReviewsCount]);
useEffect(() => {
const handleUpdate = (e: Event) => {
const customEvent = e as CustomEvent;
if (customEvent.detail && customEvent.detail.productId === product.product_id) {
if (typeof customEvent.detail.averageRating === 'number') {
setCurrentRating(customEvent.detail.averageRating);
}
if (typeof customEvent.detail.totalReviews === 'number') {
setCurrentReviewsCount(customEvent.detail.totalReviews);
}
}
};
window.addEventListener('ifixkart:reviews-summary-updated', handleUpdate);
return () => window.removeEventListener('ifixkart:reviews-summary-updated', handleUpdate);
}, [product.product_id]);
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 [selectedVariantIndex, setSelectedVariantIndex] = useState<number>(getInitialIndex);
const [selectedImage, setSelectedImage] = useState<string>(() => resolveInitialImage(product, getInitialIndex()));
const [selectedImage, setSelectedImage] = useState<string>(() => resolveInitialImage(product, 0));
const [selectedVariantIndex, setSelectedVariantIndex] = useState(0);
const [quantity, setQuantity] = useState(1);
const [added, setAdded] = useState(false);
const [selections, setSelections] = useState<Record<string, string>>({});
@ -165,30 +106,6 @@ 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(() => {
@ -211,30 +128,13 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
lookupIndex.current = { variantAttrsMap, validValuesByDimension };
// 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');
// Select variant based on URL params or default to first index
const urlVariantId = searchParams.get('variant');
const urlSku = searchParams.get('sku');
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)
);
let activeIdx = product.variants.findIndex((v: any) => v.variant_id === urlVariantId || 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));
@ -247,7 +147,7 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
});
}
setSelections(initial);
}, [product, searchParams, initialVariantSku]);
}, [product, searchParams]);
useEffect(() => {
const named = (product as ProductResponse & { brand_name?: string }).brand_name;
@ -285,7 +185,17 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
const selectedVariant =
product.variants && product.variants.length > 0
? product.variants[selectedVariantIndex] || product.variants[0]
? product.variants[selectedVariantIndex] ||
product.variants.find((v: any) => {
if (!lookupIndex.current) return false;
const attrMap = lookupIndex.current.variantAttrsMap.get(v.variant_id);
if (!attrMap || attrMap.size === 0) return false;
return (
Object.entries(selections).length > 0 &&
Object.entries(selections).every(([k, vVal]) => attrMap.get(k) === vVal)
);
}) ||
product.variants[0]
: null;
useEffect(() => {
@ -337,22 +247,6 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
}
}, [galleryImages, selectedImage, failedImages, selectedVariantIndex, selectedVariant?.variant_id]);
const handleBookService = () => {
if (!selectedVariant) return;
const qs = new URLSearchParams();
if (product.device_type) qs.set('device_type', product.device_type);
if (product.brand_id) qs.set('brand_id', product.brand_id);
if (product.device_series_id) qs.set('series_id', product.device_series_id);
if (product.device_model_id) qs.set('model_id', product.device_model_id);
if (product.mapped_service_category_id) qs.set('service_type_id', product.mapped_service_category_id);
qs.set('variant_sku', selectedVariant.sku);
router.push(`/services?${qs.toString()}`);
};
// Delivery SLA & Pincode Checker
const [deliveryPincode, setDeliveryPincode] = useState('560001');
const [pincodeChecked, setPincodeChecked] = useState(true);
const handleAddToCart = () => {
if (selectedVariant) {
const available = selectedVariant.available_stock;
@ -360,15 +254,6 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
return;
}
addToCart(product, selectedVariant, quantity);
trackAddToCart({
id: product.product_id,
name: product.name,
price: selectedPrice,
category: (product as any).category?.name || 'Spare Parts',
brand: (product as any).brand?.name || 'iFixKart',
sku: selectedVariant.sku,
quantity,
});
Object.entries(addonQty).forEach(([productId, qty]) => {
if (qty <= 0) return;
const addon = relatedProducts.find((p) => p.product_id === productId);
@ -381,36 +266,6 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
}
};
const handleBuyNow = () => {
if (!selectedVariant || outOfStock) return;
const available = selectedVariant.available_stock;
if (typeof available === 'number' && (available <= 0 || quantity > available)) {
return;
}
addToCart(product, selectedVariant, quantity);
trackBeginCheckout(
[
{
variant_id: selectedVariant.variant_id,
product_id: product.product_id,
name: product.name,
price: selectedPrice,
quantity,
},
],
selectedPrice * quantity
);
Object.entries(addonQty).forEach(([productId, qty]) => {
if (qty <= 0) return;
const addon = relatedProducts.find((p) => p.product_id === productId);
const variant = addon?.variants?.[0];
if (addon && variant) void addToCart(addon, variant, qty);
});
window.dispatchEvent(new Event('wishlistUpdated'));
if (!requireLoginForCheckout('/checkout')) return;
router.push('/checkout');
};
const { price: minPrice, priceMax: maxPrice } = getCatalogPriceInfo(product);
const selectedPrice = parseMoney(selectedVariant?.price);
const selectedCompare = parseMoney(selectedVariant?.compare_price);
@ -425,20 +280,6 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
? Math.round(((selectedCompare - selectedPrice) / selectedCompare) * 100)
: 0;
// GA4 Telemetry view_item
useEffect(() => {
if (product && selectedVariant && selectedPrice > 0) {
trackViewItem({
id: product.product_id,
name: product.name,
price: selectedPrice,
category: (product as any).category?.name || 'Spare Parts',
brand: (product as any).brand?.name || 'iFixKart',
sku: selectedVariant.sku,
});
}
}, [product?.product_id, selectedVariant?.variant_id, selectedPrice]);
const cleanDesc = (product.description || '')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
@ -466,7 +307,7 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
return (
<>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-10 items-start">
{/* Left Column: Image Gallery */}
<div className="lg:col-span-6 flex flex-col md:flex-row gap-3">
<div className="flex md:flex-col items-center gap-1.5 order-2 md:order-1 flex-shrink-0 justify-center">
@ -488,8 +329,9 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
<button
key={idx}
onClick={() => setSelectedImage(img)}
className={`w-[62px] h-[62px] rounded-sm border p-1 transition-all overflow-hidden flex items-center justify-center bg-white cursor-pointer shrink-0 ${selectedImage === img ? 'border-primary' : 'border-gray-200 hover:border-gray-300'
}`}
className={`w-[62px] h-[62px] rounded-sm border p-1 transition-all overflow-hidden flex items-center justify-center bg-white cursor-pointer shrink-0 ${
selectedImage === img ? 'border-primary' : 'border-gray-200 hover:border-gray-300'
}`}
aria-label={`Select thumbnail ${idx + 1}`}
>
<Image
@ -583,37 +425,6 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
{product.name}
</h1>
{/* Product Rating & Reviews Anchor Shortcut */}
<div className="flex items-center gap-2.5 pt-0.5">
<div className="flex items-center text-amber-400">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
size={15}
className={i < Math.round(currentRating) ? 'fill-amber-400 text-amber-400' : 'text-gray-300'}
/>
))}
</div>
<span className="text-[13px] font-bold text-gray-800">
{Number(currentRating).toFixed(1)}
</span>
<span className="text-gray-300 text-xs">•</span>
<button
type="button"
onClick={() => {
const reviewsBtn = document.getElementById('tab-reviews-btn');
if (reviewsBtn) reviewsBtn.click();
const tabsContainer = document.getElementById('product-tabs');
if (tabsContainer) {
tabsContainer.scrollIntoView({ behavior: 'smooth' });
}
}}
className="text-[13px] font-semibold text-primary hover:underline cursor-pointer flex items-center gap-1"
>
<span>{currentReviewsCount > 0 ? `${currentReviewsCount} Customer Review${currentReviewsCount > 1 ? 's' : ''}` : 'Customer Reviews (Write a review)'}</span>
</button>
</div>
<div className="flex flex-wrap items-baseline gap-3">
<span className="text-xl md:text-2xl font-extrabold text-gray-900 font-outfit">{priceLabel}</span>
{selectedCompare > selectedPrice && (
@ -621,50 +432,18 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
{formatCurrency(selectedCompare)}
</span>
)}
<span className="text-xs text-muted-foreground font-medium bg-gray-100 px-2 py-0.5 rounded text-gray-600">
+18% GST at checkout {selectedVariant?.mrp ? `(MRP: ${formatCurrency(selectedVariant.mrp)})` : ''}
</span>
</div>
{/* Store Credit Cashback Incentive Badge */}
{selectedPrice > 0 && (
<div className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-200/80 text-emerald-800 text-[12px] font-semibold">
<Sparkles size={14} className="text-emerald-600 shrink-0" />
<span>
Earn 5% Store Credit After 7-day of the purchase
</span>
</div>
)}
{/* Interactive Variant Attribute Selectors */}
{product.variants && product.variants.length > 0 && (
<div className="space-y-4 pt-2 pb-2 border-t border-b border-gray-100 my-4">
{(() => {
const IGNORED_ATTR_CODES = new Set([
'parent_media_key',
'media_key',
'is_active',
'parent_category',
'parent_name',
'parent_id',
'cost_price',
'costprice',
'sku',
'barcode',
'compare_price',
'is_parent_feature',
'status'
]);
const dimensions = new Map<string, { code: string; label: string; values: Set<string> }>();
(product.variants || []).forEach((variant: any) => {
(variant.attributes || []).forEach((attr: any) => {
const code = String(attr.attribute_code || '').trim();
const val = String(attr.attribute_value || '').trim();
if (!code || !val) return;
const normCode = code.toLowerCase();
if (IGNORED_ATTR_CODES.has(normCode)) return;
if (!dimensions.has(code)) {
const rawName = String(attr.attribute_name || '').trim();
let label = rawName && !looksLikeBrandId(rawName)
@ -686,27 +465,15 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
dimensions.get(code)!.values.add(val);
});
});
const dims = Array.from(dimensions.values()).map((d) => ({
code: d.code,
label: d.label,
values: Array.from(d.values),
}));
const dims = Array.from(dimensions.values())
.filter((d) => {
if (d.values.size === 0) return false;
const vals = Array.from(d.values);
if (vals.length === 1 && (vals[0].toUpperCase() === 'N/A' || vals[0] === '' || vals[0].toUpperCase() === 'TRUE' || vals[0].toUpperCase() === 'FALSE')) {
return false;
}
return true;
})
.map((d) => ({
code: d.code,
label: d.label,
values: Array.from(d.values),
}));
const hasMultiValuedDim = dims.some((d) => d.values.length > 1);
if (hasMultiValuedDim || (dims.length > 0 && product.variants.length <= 1)) {
if (dims.length > 0) {
return dims.map((dim) => {
const activeAttr = (selectedVariant?.attributes || []).find((a: any) => a.attribute_code === dim.code);
const currentVal = activeAttr?.attribute_value || selections[dim.code] || '';
const currentVal = selections[dim.code] || '';
return (
<div key={dim.code} className="space-y-1.5">
<label className="block text-[12px] font-bold uppercase tracking-wider text-gray-700">
@ -720,39 +487,22 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
key={val}
type="button"
onClick={() => {
let match = product.variants.find((v: any) => {
const next = { ...selections, [dim.code]: val };
setSelections(next);
const match = product.variants.find((v: any) => {
const attrs = (v.attributes || []).reduce((acc: any, a: any) => {
acc[a.attribute_code] = a.attribute_value;
return acc;
}, {});
const candidate = { ...selections, [dim.code]: val };
return Object.entries(candidate).every(([k, vVal]) => !attrs[k] || attrs[k] === vVal);
return Object.entries(next).every(([k, vVal]) => attrs[k] === vVal);
});
if (!match) {
match = product.variants.find((v: any) =>
(v.attributes || []).some(
(a: any) => (a.attribute_code === dim.code || a.attribute_id === dim.code) && a.attribute_value === val
)
);
}
if (match) {
const idx = product.variants.findIndex((v: any) => v.variant_id === match.variant_id);
if (idx !== -1) {
setSelectedVariantIndex(idx);
}
const updatedSelections: Record<string, string> = {};
(match.attributes || []).forEach((a: any) => {
if (a.attribute_code) updatedSelections[a.attribute_code] = a.attribute_value;
});
setSelections(updatedSelections);
if (idx !== -1) setSelectedVariantIndex(idx);
const varImg = getPrimaryImageUrl(match.images);
if (varImg) {
setSelectedImage(getImageUrl(varImg));
}
syncVariantUrl(match);
}
}}
className={`px-3 py-1.5 rounded text-[12px] font-semibold transition border cursor-pointer ${
@ -775,7 +525,7 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
return (
<div className="space-y-1.5">
<label className="block text-[12px] font-bold uppercase tracking-wider text-gray-700">
Select Variant: <span className="font-semibold text-primary">{(selectedVariant as any)?.name || (selectedVariant as any)?.label || selectedVariant?.sku}</span>
Select Variant: <span className="font-semibold text-primary">{(selectedVariant as any)?.label || selectedVariant?.sku}</span>
</label>
<div className="flex flex-wrap gap-2">
{product.variants.map((v: any, idx: number) => {
@ -790,14 +540,14 @@ 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
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-gray-200 bg-white text-gray-700 hover:border-gray-300'
}`}
}`}
>
{v.name || v.label || v.sku || `Variant ${idx + 1}`}
{v.label || v.sku || `Variant ${idx + 1}`}
</button>
);
})}
@ -811,34 +561,20 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
</div>
)}
<div className="flex flex-col sm:flex-row gap-3">
<button
disabled={!selectedVariant || outOfStock}
onClick={handleAddToCart}
className={`flex-1 font-semibold text-sm py-3 px-6 rounded-md transition-colors flex items-center justify-center gap-2 cursor-pointer ${selectedVariant && !outOfStock
? 'bg-primary hover:bg-primary-hover text-white'
: 'bg-gray-100 text-gray-400 border border-gray-200 cursor-not-allowed'
}`}
>
{added ? <Check className="w-4 h-4" /> : <ShoppingCart size={16} />}
<span>
{!selectedVariant ? 'Unavailable' : outOfStock ? 'Out of Stock' : added ? 'Added to Cart!' : 'Add To Cart'}
</span>
</button>
<button
disabled={!selectedVariant || outOfStock}
onClick={handleBuyNow}
className={`flex-1 font-semibold text-sm py-3 px-6 rounded-md transition-colors flex items-center justify-center gap-2 cursor-pointer shadow-sm ${
selectedVariant && !outOfStock
? 'bg-emerald-600 hover:bg-emerald-700 text-white'
: 'bg-gray-100 text-gray-400 border border-gray-200 cursor-not-allowed'
}`}
>
<Zap size={16} />
<span>Buy Now</span>
</button>
</div>
<button
disabled={!selectedVariant || outOfStock}
onClick={handleAddToCart}
className={`w-full font-semibold text-sm py-3 px-6 rounded-md transition-colors flex items-center justify-center gap-2 cursor-pointer ${
selectedVariant && !outOfStock
? 'bg-primary hover:bg-primary-hover text-white'
: 'bg-gray-100 text-gray-400 border border-gray-200 cursor-not-allowed'
}`}
>
{added ? <Check className="w-4 h-4" /> : <ShoppingCart size={16} />}
<span>
{!selectedVariant ? 'Unavailable' : outOfStock ? 'Out of Stock' : added ? 'Added to Cart!' : 'Add To Cart'}
</span>
</button>
<div className="flex flex-wrap items-center gap-x-5 gap-y-2 text-[12px] font-medium text-gray-600">
<button
@ -853,8 +589,8 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
onClick={() => toggleWishlist(product)}
className={`flex items-center gap-1.5 cursor-pointer ${isInWishlist ? 'text-primary' : 'hover:text-primary'}`}
>
<Heart size={14} className={isInWishlist ? 'fill-primary text-primary' : ''} />
{isInWishlist ? 'Saved' : 'Wishlist'}
<Heart size={14} className={isInWishlist ? 'fill-[#e4382f] text-[#e4382f]' : ''} />
Wishlist
</button>
<button
type="button"
@ -871,84 +607,6 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
Share
</button>
</div>
{/* Pincode Delivery SLA & Courier Verification Widget */}
<div className="mt-5 p-4 rounded-xl border border-gray-200/90 bg-gray-50/70 space-y-3">
<div className="flex items-center justify-between">
<span className="text-[12px] font-bold uppercase tracking-wider text-gray-700 flex items-center gap-1.5">
<Truck size={15} className="text-primary" />
<span>Delivery & Courier Availability</span>
</span>
<span className="text-[11px] font-semibold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200/60">
Pan-India Express
</span>
</div>
<div className="flex items-center gap-2">
<div className="relative flex-1">
<MapPin size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<input
type="text"
maxLength={6}
value={deliveryPincode}
onChange={(e) => {
setDeliveryPincode(e.target.value.replace(/\D/g, ''));
setPincodeChecked(false);
}}
placeholder="Enter 6-digit delivery pincode"
className="w-full pl-8 pr-3 py-1.5 text-xs rounded-lg border border-gray-300 bg-white focus:outline-none focus:ring-1 focus:ring-primary font-mono text-gray-900"
/>
</div>
<button
type="button"
onClick={() => setPincodeChecked(true)}
className="px-3.5 py-1.5 text-xs font-semibold rounded-lg bg-gray-900 text-white hover:bg-gray-800 transition cursor-pointer"
>
Check
</button>
</div>
{pincodeChecked && (
<div className="space-y-1.5 pt-1 text-xs text-gray-600 animate-in fade-in duration-200">
<div className="flex items-center gap-2 text-emerald-700 font-semibold">
<Check size={14} className="text-emerald-600" />
<span>Express Delivery Available to {deliveryPincode}</span>
</div>
<div className="flex items-center gap-2 text-gray-500 text-[11px]">
<Clock size={13} className="text-primary" />
<span>Estimated delivery within 2-3 business days via Express Air Courier</span>
</div>
<div className="flex items-center gap-2 text-gray-500 text-[11px]">
<ShieldCheck size={13} className="text-emerald-600" />
<span>Prepaid Order Protection (Instant Online Verification & Fast Dispatch)</span>
</div>
</div>
)}
</div>
{product.is_service_booking && (
<div className="mt-4 p-4 border border-emerald-200 bg-emerald-50 rounded-xl flex flex-col gap-3">
<div className="flex items-start gap-3">
<Wrench className="w-5 h-5 text-emerald-600 mt-0.5 shrink-0" />
<div>
<h4 className="font-semibold text-emerald-900 text-sm">Need Professional Installation?</h4>
<p className="text-xs text-emerald-700 mt-1">
Book a service for your device.An expert engineer will install it for you.
</p>
</div>
</div>
<button
disabled={!selectedVariant}
onClick={handleBookService}
className={`w-full font-semibold text-sm py-2.5 px-6 rounded-md transition-colors flex items-center justify-center gap-2 cursor-pointer ${selectedVariant
? 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm'
: 'bg-emerald-200 text-emerald-500 cursor-not-allowed'
}`}
>
Book Service Now
</button>
</div>
)}
</div>
</div>
@ -983,26 +641,15 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
{selectedVariant ? formatCurrency(selectedPrice) : 'N/A'}
</span>
<button
disabled={!selectedVariant || outOfStock}
disabled={!selectedVariant}
onClick={handleAddToCart}
className={`font-extrabold text-xs uppercase tracking-wider py-2.5 px-5 rounded-xl transition-all shadow-sm cursor-pointer whitespace-nowrap ${
selectedVariant && !outOfStock
selectedVariant
? 'bg-[#0073EC] hover:bg-[#1565C0] text-white'
: 'bg-gray-100 text-gray-450 border border-gray-200 cursor-not-allowed'
}`}
>
{!selectedVariant ? 'Unavailable' : outOfStock ? 'Out of Stock' : 'Add to Cart'}
</button>
<button
disabled={!selectedVariant || outOfStock}
onClick={handleBuyNow}
className={`font-extrabold text-xs uppercase tracking-wider py-2.5 px-5 rounded-xl transition-all shadow-sm cursor-pointer whitespace-nowrap ${
selectedVariant && !outOfStock
? 'bg-emerald-600 hover:bg-emerald-700 text-white'
: 'bg-gray-100 text-gray-450 border border-gray-200 cursor-not-allowed'
}`}
>
Buy Now
{!selectedVariant ? 'Unavailable' : 'Add to Cart'}
</button>
</div>
</div>

View file

@ -1,219 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { ChevronDown, MessageSquare, Loader2 } from 'lucide-react';
import { reviewService, ProductReviewItem, ProductReviewSummaryResponse } from '@/services/api/reviewService';
import { ReviewSummaryBreakdown } from './ReviewSummaryBreakdown';
import { ReviewCard } from './ReviewCard';
import { ReviewSubmissionModal } from './ReviewSubmissionModal';
interface ProductReviewsSectionProps {
productId: string;
productName: string;
onReviewsCountChange?: (count: number) => void;
}
export function ProductReviewsSection({
productId,
productName,
onReviewsCountChange,
}: ProductReviewsSectionProps) {
const [data, setData] = useState<ProductReviewSummaryResponse | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [sort, setSort] = useState('newest');
const [page, setPage] = useState(1);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isLoadingMore, setIsLoadingMore] = useState(false);
useEffect(() => {
setIsLoading(true);
reviewService
.getProductReviews(productId, 1, 10, sort)
.then((res) => {
setData(res);
if (onReviewsCountChange) onReviewsCountChange(res.total_reviews);
if (typeof window !== 'undefined') {
window.dispatchEvent(
new CustomEvent('ifixkart:reviews-summary-updated', {
detail: {
productId,
averageRating: res.average_rating,
totalReviews: res.total_reviews,
},
})
);
}
})
.finally(() => {
setIsLoading(false);
});
}, [productId, sort]);
const handleLoadMore = () => {
if (!data) return;
setIsLoadingMore(true);
const nextPage = page + 1;
reviewService
.getProductReviews(productId, nextPage, 10, sort)
.then((res) => {
setData((prev) => {
if (!prev) return res;
return {
...res,
reviews: [...prev.reviews, ...res.reviews],
};
});
setPage(nextPage);
})
.finally(() => {
setIsLoadingMore(false);
});
};
const handleReviewSubmitted = (newReview: ProductReviewItem) => {
// If review is pending admin approval, do not append to public storefront list
if (newReview.is_approved === false) {
return;
}
setData((prev) => {
const existingReviews = prev ? prev.reviews : [];
const updatedReviews = [newReview, ...existingReviews];
const newTotal = (prev?.total_reviews || 0) + 1;
const starKey = String(newReview.rating);
const newDist = { ...(prev?.star_distribution || {}) };
newDist[starKey] = (newDist[starKey] || 0) + 1;
const calculatedAvg = prev ? ((prev.average_rating * prev.total_reviews) + newReview.rating) / newTotal : newReview.rating;
if (onReviewsCountChange) onReviewsCountChange(newTotal);
if (typeof window !== 'undefined') {
window.dispatchEvent(
new CustomEvent('ifixkart:reviews-summary-updated', {
detail: {
productId,
averageRating: Number(calculatedAvg.toFixed(1)),
totalReviews: newTotal,
},
})
);
}
return {
average_rating: calculatedAvg,
total_reviews: newTotal,
star_distribution: newDist,
verified_count: (prev?.verified_count || 0) + (newReview.verified_buyer ? 1 : 0),
page: 1,
limit: 10,
reviews: updatedReviews,
};
});
};
if (isLoading) {
return (
<div className="py-12 flex flex-col items-center justify-center gap-3">
<Loader2 size={24} className="text-primary animate-spin" />
<p className="text-xs font-semibold text-gray-500">Loading customer reviews...</p>
</div>
);
}
const reviews = data?.reviews || [];
const totalReviews = data?.total_reviews || 0;
const averageRating = data?.average_rating || 0;
const verifiedCount = data?.verified_count || 0;
const starDistribution = data?.star_distribution || { '5': 0, '4': 0, '3': 0, '2': 0, '1': 0 };
const hasMore = reviews.length < totalReviews;
return (
<div className="py-4">
{/* 1. Summary Breakdown */}
<ReviewSummaryBreakdown
averageRating={averageRating}
totalReviews={totalReviews}
verifiedCount={verifiedCount}
starDistribution={starDistribution}
onWriteReviewClick={() => setIsModalOpen(true)}
/>
{/* 2. Reviews Header with Sorting */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-gray-200 mb-2">
<h3 className="text-sm font-bold text-gray-900">
Customer Feedback ({totalReviews})
</h3>
{reviews.length > 0 && (
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 font-medium">Sort by:</span>
<div className="relative">
<select
value={sort}
onChange={(e) => setSort(e.target.value)}
className="appearance-none bg-white border border-gray-300 rounded-md pl-3 pr-7 py-1.5 text-xs font-medium text-gray-700 cursor-pointer focus:outline-none focus:border-primary"
>
<option value="newest">Most Recent</option>
<option value="highest">Highest Rating</option>
<option value="lowest">Lowest Rating</option>
<option value="helpful">Most Helpful</option>
</select>
<ChevronDown
size={12}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"
/>
</div>
</div>
)}
</div>
{/* 3. Review Cards List */}
{reviews.length === 0 ? (
<div className="py-12 text-center space-y-3">
<MessageSquare size={36} className="mx-auto text-gray-300" />
<h4 className="text-sm font-bold text-gray-800">No reviews yet</h4>
<p className="text-xs text-gray-500 max-w-sm mx-auto">
Have you purchased this product? Be the first to share your thoughts with other customers.
</p>
<button
type="button"
onClick={() => setIsModalOpen(true)}
className="px-5 py-2.5 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 shadow-sm inline-flex items-center gap-2 cursor-pointer mt-2"
>
Write the First Review
</button>
</div>
) : (
<div className="divide-y divide-gray-100">
{reviews.map((r) => (
<ReviewCard key={r.review_id} review={r} />
))}
</div>
)}
{/* 4. Load More Button */}
{hasMore && (
<div className="pt-6 flex justify-center">
<button
type="button"
onClick={handleLoadMore}
disabled={isLoadingMore}
className="px-6 py-2.5 border border-gray-300 text-gray-700 text-xs font-semibold rounded-lg hover:bg-gray-50 transition-colors cursor-pointer disabled:opacity-60 inline-flex items-center gap-2"
>
{isLoadingMore && <Loader2 size={13} className="animate-spin" />}
<span>{isLoadingMore ? 'Loading...' : 'Load More Reviews'}</span>
</button>
</div>
)}
{/* 5. Submission Modal */}
<ReviewSubmissionModal
productId={productId}
productName={productName}
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
onReviewSubmitted={handleReviewSubmitted}
/>
</div>
);
}

View file

@ -1,94 +1,51 @@
"use client";
import React, { useState, useEffect } from 'react';
import { ProductReviewsSection } from './ProductReviewsSection';
import React, { useState } from 'react';
interface ProductTabsWrapperProps {
productId?: string;
productName?: string;
initialReviewsCount?: number;
descriptionHtml: React.ReactNode;
specsHtml: React.ReactNode;
showSpecifications?: boolean;
}
type TabId = 'description' | 'specs' | 'reviews';
type TabId = 'description' | 'specs';
const BOX = 'border border-gray-200 rounded-xl overflow-hidden';
const TAB_LINE = 'border-[#e0e0e0]';
const BOX = 'border border-[#e0e0e0]';
export const ProductTabsWrapper: React.FC<ProductTabsWrapperProps> = ({
productId,
productName,
initialReviewsCount = 0,
descriptionHtml,
specsHtml,
showSpecifications = true,
}) => {
const [activeTab, setActiveTab] = useState<TabId>('description');
const [reviewsCount, setReviewsCount] = useState<number>(initialReviewsCount);
useEffect(() => {
if (typeof window !== 'undefined' && window.location.hash === '#reviews') {
setActiveTab('reviews');
setTimeout(() => {
document.getElementById('product-tabs')?.scrollIntoView({ behavior: 'smooth' });
}, 150);
}
}, []);
const tabs: { id: TabId; label: string }[] = [
{ id: 'description', label: 'Description' },
...(showSpecifications ? [{ id: 'specs' as TabId, label: 'Specifications' }] : []),
];
return (
<div id="product-tabs" className="bg-white mb-10 text-left">
{/* Modern High-Visibility Tab Bar */}
<div className="flex items-center justify-center border-b border-gray-200 gap-2 sm:gap-6 overflow-x-auto pb-px">
<button
id="tab-description-btn"
type="button"
onClick={() => setActiveTab('description')}
className={`pb-3 px-3 text-[15px] sm:text-[16px] font-semibold cursor-pointer border-b-2 transition-all flex items-center gap-1.5 ${
activeTab === 'description'
? 'border-primary text-primary font-bold'
: 'border-transparent text-gray-500 hover:text-gray-900'
}`}
>
<span>Description</span>
</button>
{showSpecifications && (
<button
id="tab-specs-btn"
type="button"
onClick={() => setActiveTab('specs')}
className={`pb-3 px-3 text-[15px] sm:text-[16px] font-semibold cursor-pointer border-b-2 transition-all flex items-center gap-1.5 ${
activeTab === 'specs'
? 'border-primary text-primary font-bold'
: 'border-transparent text-gray-500 hover:text-gray-900'
}`}
>
<span>Specifications</span>
</button>
)}
<button
id="tab-reviews-btn"
type="button"
onClick={() => setActiveTab('reviews')}
className={`pb-3 px-3 text-[15px] sm:text-[16px] font-semibold cursor-pointer border-b-2 transition-all flex items-center gap-2 ${
activeTab === 'reviews'
? 'border-primary text-primary font-bold'
: 'border-transparent text-gray-500 hover:text-gray-900'
}`}
>
<span>Customer Reviews</span>
<span
className={`px-2 py-0.5 rounded-full text-xs font-bold transition-colors ${
activeTab === 'reviews'
? 'bg-primary text-white'
: 'bg-gray-100 text-gray-700'
}`}
>
{reviewsCount}
</span>
</button>
{/* Tab Headers */}
<div className={`flex justify-center items-end gap-8 md:gap-12 border-b ${TAB_LINE} overflow-x-auto no-scrollbar`}>
{tabs.map((tab) => {
const isActive = activeTab === tab.id;
return (
<button
key={tab.id}
type="button"
onClick={() => setActiveTab(tab.id)}
className={`-mb-px pb-[13px] text-[14px] leading-none whitespace-nowrap cursor-pointer border-b-2 transition-colors ${
isActive
? 'border-primary text-[#222]'
: 'border-transparent text-[#9a9a9a] hover:text-[#555]'
}`}
>
{tab.label}
</button>
);
})}
</div>
{/* Tab Panels */}
@ -110,19 +67,6 @@ export const ProductTabsWrapper: React.FC<ProductTabsWrapperProps> = ({
{specsHtml}
</div>
{/* ── Reviews ── */}
<div className={activeTab === 'reviews' ? 'block p-4 sm:p-6 md:p-8' : 'hidden'}>
{productId ? (
<ProductReviewsSection
productId={productId}
productName={productName || 'Product'}
onReviewsCountChange={setReviewsCount}
/>
) : (
<p className="text-xs text-gray-400 py-6 text-center">Reviews unavailable</p>
)}
</div>
</div>
</div>
);

View file

@ -1,213 +1,186 @@
'use client';
import { useState } from 'react';
import { Check, ShoppingCart, ShieldCheck, FileText } from 'lucide-react';
import BlurHashImage from '@/components/ui/BlurHashImage';
import { ProductResponse, ProductVariantResponse } from '@/services/api/catalogService';
import { useCartStore } from '@/store/cartStore';
import { formatCurrency, getImageUrl } from '@/lib/utils';
interface QuickComparisonTableProps {
product: ProductResponse;
}
function getVariantTitle(variant: ProductVariantResponse, fallbackIndex: number): string {
const validAttrs = (variant.attributes || []).filter((a) => {
const key = (a.attribute_name || a.attribute_code || '').toLowerCase().trim();
return a.attribute_value && !['media_key', 'parent_media_key'].includes(key);
});
if (validAttrs.length > 0) {
return validAttrs
.map((a) => {
const name = a.attribute_name ? `${a.attribute_name}: ` : '';
return `${name}${a.attribute_value}`;
})
.join(' | ');
}
return variant.sku || `Variant ${fallbackIndex + 1}`;
}
function getVariantImage(product: ProductResponse, variant: ProductVariantResponse): string {
const img = variant.images?.[0]?.image_url || product.images?.[0]?.image_url;
return getImageUrl(img);
}
export function QuickComparisonTable({ product }: QuickComparisonTableProps) {
const addToCart = useCartStore((state) => state.addToCart);
const [addedVariantId, setAddedVariantId] = useState<string | null>(null);
const variants = product?.variants || [];
// Strictly only show when the product has multiple variants (> 1)
if (variants.length <= 1) {
return null;
}
const handleAdd = async (variant: ProductVariantResponse) => {
await addToCart(product, variant, 1);
setAddedVariantId(variant.variant_id);
setTimeout(() => setAddedVariantId(null), 1800);
};
const labelCls =
'sticky left-0 z-10 w-[160px] min-w-[160px] px-5 py-4 text-[13px] font-semibold text-gray-700 text-left align-middle bg-[#f3f4f6] border-b border-gray-200';
const cellCls = 'px-5 py-4 min-w-[200px] align-middle text-center border-b border-gray-200';
return (
<section className="mb-12">
<div className="flex items-center gap-2 mb-4">
<h3 className="text-[20px] font-bold text-gray-800 tracking-tight">Variant Comparison</h3>
<span className="text-[12px] font-medium text-gray-500 bg-gray-100 px-2.5 py-0.5 rounded-full">
{variants.length} Options
</span>
</div>
<div className="overflow-x-auto rounded-lg border border-gray-200 shadow-sm bg-white">
<table className="w-full border-collapse min-w-[700px]">
{/* Variant Header Row */}
<thead>
<tr className="bg-white">
<th className={`${labelCls} bg-white text-gray-400 font-normal`}>Option</th>
{variants.map((v, idx) => {
const img = getVariantImage(product, v);
const title = getVariantTitle(v, idx);
return (
<th key={v.variant_id} className={`${cellCls} font-normal bg-white`}>
<div className="w-[100px] h-[100px] mx-auto bg-gray-50 border border-gray-200 rounded-lg p-2 flex items-center justify-center mb-3">
<BlurHashImage
src={img}
alt={title}
width={90}
height={90}
className="max-h-full max-w-full object-contain"
/>
</div>
<div className="text-[13px] font-semibold text-gray-800 leading-snug line-clamp-2 px-1 min-h-[36px]">
{title}
</div>
</th>
);
})}
</tr>
</thead>
<tbody>
{/* 1. Name / Specifications Row */}
<tr className="bg-[#fcfcfd]">
<td className={labelCls}>Name / Specification</td>
{variants.map((v, idx) => (
<td key={v.variant_id} className={`${cellCls} text-[13px] font-medium text-gray-800`}>
{getVariantTitle(v, idx)}
</td>
))}
</tr>
{/* 2. Price Row */}
<tr className="bg-white">
<td className={labelCls}>Price</td>
{variants.map((v) => {
const price = Number(v.price) || 0;
const comparePrice = v.compare_price ? Number(v.compare_price) : 0;
const hasDiscount = comparePrice > price;
const discountPercent = hasDiscount
? Math.round(((comparePrice - price) / comparePrice) * 100)
: 0;
return (
<td key={v.variant_id} className={cellCls}>
<div className="flex items-center justify-center gap-2 flex-wrap">
<span className="text-[16px] font-bold text-gray-900">
{formatCurrency(price)}
</span>
{hasDiscount && (
<>
<span className="text-[13px] text-gray-400 line-through">
{formatCurrency(comparePrice)}
</span>
<span className="text-[11px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-1.5 py-0.5 rounded">
{discountPercent}% OFF
</span>
</>
)}
</div>
</td>
);
})}
</tr>
{/* 3. Warranty Type Row */}
<tr className="bg-[#fcfcfd]">
<td className={labelCls}>
<div className="flex items-center gap-1.5">
<ShieldCheck size={15} className="text-primary flex-shrink-0" />
<span>Warranty Type</span>
</div>
</td>
{variants.map((v) => (
<td key={v.variant_id} className={`${cellCls} text-[13px] text-gray-700 font-medium`}>
{product.warranty_type || 'Standard Warranty'}
</td>
))}
</tr>
{/* 4. Summary Row */}
<tr className="bg-white">
<td className={labelCls}>
<div className="flex items-center gap-1.5">
<FileText size={15} className="text-primary flex-shrink-0" />
<span>Summary</span>
</div>
</td>
{variants.map((v) => (
<td key={v.variant_id} className={`${cellCls} text-[13px] text-gray-600 leading-relaxed max-w-[280px]`}>
{product.warranty_summary || '100% Quality Tested & Brand Verified'}
</td>
))}
</tr>
{/* Action Row */}
<tr className="bg-[#fcfcfd]">
<td className={labelCls}>Action</td>
{variants.map((v) => {
const justAdded = addedVariantId === v.variant_id;
const isOutOfStock = v.status === 'inactive' || (v.available_stock !== undefined && v.available_stock <= 0);
return (
<td key={v.variant_id} className={cellCls}>
<button
type="button"
disabled={isOutOfStock}
onClick={() => void handleAdd(v)}
className={`inline-flex items-center justify-center gap-2 min-w-[130px] text-[13px] font-semibold px-4 py-2.5 rounded-md transition-all cursor-pointer shadow-sm ${
isOutOfStock
? 'bg-gray-200 text-gray-400 cursor-not-allowed'
: justAdded
? 'bg-emerald-600 text-white'
: 'bg-primary hover:bg-primary-hover text-white hover:shadow'
}`}
>
{isOutOfStock ? (
'Out of Stock'
) : justAdded ? (
<>
<Check size={14} className="stroke-[2.5]" />
<span>Added</span>
</>
) : (
<>
<ShoppingCart size={14} />
<span>Add To Cart</span>
</>
)}
</button>
</td>
);
})}
</tr>
</tbody>
</table>
</div>
</section>
);
}
'use client';
import Link from 'next/link';
import Image from 'next/image';
import { useState } from 'react';
import { Check, ShoppingCart } from 'lucide-react';
import BlurHashImage from '@/components/ui/BlurHashImage';
import { ProductResponse } from '@/services/api/catalogService';
import { useCartStore } from '@/store/cartStore';
import { formatCatalogPriceLabel, formatCurrency, getImageUrl } from '@/lib/utils';
interface QuickComparisonTableProps {
products: ProductResponse[];
}
function priceLabel(product: ProductResponse): string {
const label = formatCatalogPriceLabel(product);
return label === formatCurrency(0) ? '—' : label;
}
function productImage(product: ProductResponse): string {
return getImageUrl(product.images?.[0]?.image_url || product.variants?.[0]?.images?.[0]?.image_url);
}
function extraAttributes(product: ProductResponse): { label: string; values: string[] }[] {
const buckets: Record<string, { label: string; values: Set<string> }> = {};
(product.variants || []).forEach((variant) => {
(variant.attributes || []).forEach((attr) => {
const raw = attr.attribute_name || attr.attribute_code || '';
const value = String(attr.attribute_value || '').trim();
if (!raw || !value) return;
const key = raw.trim().toLowerCase().replace(/[\s-]+/g, '_');
if (!buckets[key]) {
let label = raw.replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
if (['qul', 'qual'].includes(key)) label = 'Quality';
else if (['clr'].includes(key)) label = 'Color';
else if (['str'].includes(key)) label = 'Storage';
buckets[key] = {
label,
values: new Set(),
};
}
buckets[key].values.add(value);
});
});
return Object.values(buckets)
.map((item) => ({
label: item.label,
values: Array.from(item.values),
}))
.slice(0, 3);
}
function ctaKind(product: ProductResponse): 'view' | 'cart' {
return (product.variants?.length || 0) > 1 ? 'view' : 'cart';
}
export function QuickComparisonTable({ products }: QuickComparisonTableProps) {
const addToCart = useCartStore((state) => state.addToCart);
const [addedId, setAddedId] = useState<string | null>(null);
if (!products.length) return null;
const handleAdd = async (product: ProductResponse) => {
const variant = product.variants?.[0];
if (!variant) return;
await addToCart(product, variant, 1);
setAddedId(product.product_id);
setTimeout(() => setAddedId(null), 1800);
};
const labelCls =
'sticky left-0 z-10 w-[150px] min-w-[150px] px-4 py-4 text-[13px] font-medium text-gray-500 text-left align-middle bg-[#f3f4f6]';
const cellCls = 'px-5 py-4 min-w-[170px] align-middle text-center';
return (
<section className="mb-10">
<h3 className="text-[20px] font-semibold text-gray-800 mb-4 tracking-tight">Quick Comparison</h3>
<div className="overflow-x-auto rounded-md border border-gray-200">
<table className="w-full border-collapse min-w-[860px]">
<thead>
<tr className="bg-white">
<th className={labelCls} />
{products.map((prod) => {
const img = productImage(prod);
return (
<th key={prod.product_id} className={`${cellCls} font-normal bg-white`}>
<Link
href={`/products/${prod.slug}`}
className="block text-[13px] font-medium text-gray-700 leading-snug hover:text-primary line-clamp-2 min-h-[36px] mb-3"
>
{prod.name}
</Link>
<Link
href={`/products/${prod.slug}`}
className="w-[92px] h-[92px] mx-auto bg-white border border-gray-200 rounded-md p-2 flex items-center justify-center hover:border-primary/40 transition-colors"
>
<BlurHashImage
src={img}
alt={prod.name}
width={84}
height={84}
className="max-h-full max-w-full object-contain"
/>
</Link>
</th>
);
})}
</tr>
</thead>
<tbody>
<tr className="bg-[#f8f8f8]">
<td className={labelCls}>Price</td>
{products.map((prod) => (
<td key={prod.product_id} className={`${cellCls} text-[14px] font-bold text-gray-900`}>
{priceLabel(prod)}
</td>
))}
</tr>
<tr className="bg-white">
<td className={labelCls}>Add to cart</td>
{products.map((prod) => {
const kind = ctaKind(prod);
const justAdded = addedId === prod.product_id;
return (
<td key={prod.product_id} className={cellCls}>
{kind === 'view' ? (
<Link
href={`/products/${prod.slug}`}
className="inline-flex items-center justify-center min-w-[120px] bg-primary hover:bg-primary-hover text-white text-[13px] font-semibold px-4 py-2.5 rounded-md transition-colors"
>
View Products
</Link>
) : (
<button
type="button"
onClick={() => void handleAdd(prod)}
className="inline-flex items-center justify-center gap-1.5 min-w-[120px] bg-primary hover:bg-primary-hover text-white text-[13px] font-semibold px-4 py-2.5 rounded-md transition-colors cursor-pointer"
>
{justAdded ? <Check size={14} /> : <ShoppingCart size={14} />}
{justAdded ? 'Added' : 'Add To Cart'}
</button>
)}
</td>
);
})}
</tr>
<tr className="bg-[#f8f8f8]">
<td className={`${labelCls} align-top`}>Additional information</td>
{products.map((prod) => {
const attrs = extraAttributes(prod);
return (
<td key={prod.product_id} className={`${cellCls} align-top text-[12px] leading-relaxed`}>
{attrs.length === 0 ? (
<span className="text-gray-300">—</span>
) : (
<div className="space-y-1.5 text-left inline-block">
{attrs.map((attr) => (
<div key={attr.label}>
<span className="text-gray-700 font-medium">{attr.label}: </span>
{attr.values.map((value, i) => (
<span key={value}>
<Link href={`/products/${prod.slug}`} className="text-primary hover:underline">
{value}
</Link>
{i < attr.values.length - 1 ? <span className="text-gray-400">, </span> : null}
</span>
))}
</div>
))}
</div>
)}
</td>
);
})}
</tr>
</tbody>
</table>
</div>
</section>
);
}

View file

@ -1,124 +0,0 @@
'use client';
import React, { useState } from 'react';
import Image from 'next/image';
import { Star, CheckCircle, MessageSquareQuote, X } from 'lucide-react';
import { ProductReviewItem } from '@/services/api/reviewService';
import { getImageUrl } from '@/lib/utils';
export function ReviewCard({ review }: { review: ProductReviewItem }) {
const [selectedImage, setSelectedImage] = useState<string | null>(null);
return (
<div className="py-6 border-b border-gray-100 last:border-b-0 space-y-3">
{/* Header: Author & Verified Badge & Date */}
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-full bg-primary/10 text-primary font-bold text-sm flex items-center justify-center">
{review.author_name ? review.author_name.charAt(0).toUpperCase() : 'U'}
</div>
<div>
<div className="flex items-center gap-2">
<span className="text-[14px] font-semibold text-gray-900">
{review.author_name}
</span>
{review.verified_buyer && (
<span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
<CheckCircle size={11} className="text-emerald-600 fill-emerald-100" />
Verified Purchase
</span>
)}
</div>
{review.review_date && (
<span className="text-[12px] text-gray-400">
Reviewed on {review.review_date}
</span>
)}
</div>
</div>
{/* Stars */}
<div className="flex items-center gap-0.5 text-amber-400">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
size={14}
className={i < review.rating ? 'fill-amber-400 text-amber-400' : 'text-gray-200'}
/>
))}
</div>
</div>
{/* Review Title */}
{review.title && (
<h4 className="text-[14px] font-bold text-gray-900 leading-snug">
{review.title}
</h4>
)}
{/* Review Body */}
<p className="text-[13px] text-gray-700 leading-relaxed whitespace-pre-line">
{review.comment}
</p>
{/* Uploaded Customer Photos */}
{review.images && review.images.length > 0 && (
<div className="flex items-center gap-2.5 pt-1">
{review.images.map((imgUrl, idx) => {
const fullUrl = getImageUrl(imgUrl);
return (
<button
key={idx}
type="button"
onClick={() => setSelectedImage(fullUrl)}
className="relative w-16 h-16 rounded-md overflow-hidden border border-gray-200 hover:border-primary transition-all hover:scale-105 cursor-pointer"
>
<Image
src={fullUrl}
alt={`Customer photo ${idx + 1}`}
fill
className="object-cover"
/>
</button>
);
})}
</div>
)}
{/* Admin Reply */}
{review.admin_reply && (
<div className="mt-3 p-3.5 bg-gray-50 border-l-3 border-primary rounded-r-md text-xs space-y-1">
<div className="flex items-center gap-1.5 font-bold text-gray-900">
<MessageSquareQuote size={14} className="text-primary" />
<span>iFixKart Response</span>
</div>
<p className="text-gray-600 leading-relaxed">{review.admin_reply}</p>
</div>
)}
{/* Lightbox Modal */}
{selectedImage && (
<div
className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"
onClick={() => setSelectedImage(null)}
>
<div className="relative max-w-2xl max-h-[85vh] w-full bg-black rounded-lg overflow-hidden flex items-center justify-center">
<button
type="button"
onClick={() => setSelectedImage(null)}
className="absolute top-3 right-3 z-10 p-2 text-white/80 hover:text-white bg-black/50 rounded-full"
>
<X size={20} />
</button>
<img
src={selectedImage}
alt="Customer photo enlarged"
className="max-h-[80vh] w-auto object-contain rounded-md"
/>
</div>
</div>
)}
</div>
);
}

View file

@ -1,441 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Star, X, Upload, CheckCircle2, AlertCircle, Loader2 } from 'lucide-react';
import { useAuthStore } from '@/store/authStore';
import { reviewService, ProductReviewItem } from '@/services/api/reviewService';
import GoogleAuthModal from '@/components/auth/GoogleAuthModal';
interface ReviewSubmissionModalProps {
productId: string;
productName: string;
isOpen: boolean;
onClose: () => void;
onReviewSubmitted: (newReview: ProductReviewItem) => void;
}
const RATING_DESCRIPTIONS: Record<number, string> = {
1: 'Terrible - Very disappointed',
2: 'Poor - Not as expected',
3: 'Average - It was okay',
4: 'Good - Satisfied with quality',
5: 'Excellent - Highly recommended!',
};
function GoogleIcon({ className = 'w-4 h-4' }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" aria-hidden>
<path
fill="#4285F4"
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
/>
<path
fill="#34A853"
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
/>
<path
fill="#FBBC05"
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"
/>
<path
fill="#EA4335"
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"
/>
</svg>
);
}
export function ReviewSubmissionModal({
productId,
productName,
isOpen,
onClose,
onReviewSubmitted,
}: ReviewSubmissionModalProps) {
const customer = useAuthStore((s) => s.customer);
const bootstrapAuth = useAuthStore((s) => s.bootstrapAuth);
const [rating, setRating] = useState<number>(5);
const [hoverRating, setHoverRating] = useState<number | null>(null);
const [title, setTitle] = useState('');
const [comment, setComment] = useState('');
const [authorName, setAuthorName] = useState('');
const [authorEmail, setAuthorEmail] = useState('');
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const [filePreviews, setFilePreviews] = useState<string[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [isSuccess, setIsSuccess] = useState(false);
const [showGoogleAuthModal, setShowGoogleAuthModal] = useState(false);
const [isGoogleAutofilled, setIsGoogleAutofilled] = useState(false);
// Restore session when modal opens
useEffect(() => {
if (isOpen) {
void bootstrapAuth();
}
}, [isOpen, bootstrapAuth]);
// Autofill name & email from logged in customer
useEffect(() => {
if (customer) {
const resolvedName =
(customer as any).name ||
(customer as any).full_name ||
[customer.first_name, customer.last_name].filter(Boolean).join(' ') ||
customer.first_name ||
'';
if (resolvedName) {
setAuthorName((prev) => (prev ? prev : resolvedName));
}
if (customer.email) {
setAuthorEmail((prev) => (prev ? prev : customer.email));
}
setIsGoogleAutofilled(true);
}
}, [customer, isOpen]);
if (!isOpen) return null;
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
if (!files.length) return;
const remainingSlots = 3 - selectedFiles.length;
const toAdd = files.slice(0, remainingSlots);
setSelectedFiles((prev) => [...prev, ...toAdd]);
const newPreviews = toAdd.map((f) => URL.createObjectURL(f));
setFilePreviews((prev) => [...prev, ...newPreviews]);
};
const removeFile = (index: number) => {
setSelectedFiles((prev) => prev.filter((_, i) => i !== index));
setFilePreviews((prev) => {
URL.revokeObjectURL(prev[index]);
return prev.filter((_, i) => i !== index);
});
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setErrorMsg(null);
if (!title.trim()) {
setErrorMsg('Please enter a headline for your review.');
return;
}
if (!comment.trim() || comment.trim().length < 5) {
setErrorMsg('Please enter a detailed review comment (at least 5 characters).');
return;
}
if (!authorName.trim()) {
setErrorMsg('Please enter your name.');
return;
}
setIsSubmitting(true);
try {
// 1. Upload images if any
const imageUrls: string[] = [];
for (const file of selectedFiles) {
try {
const url = await reviewService.uploadReviewImage(file, productId);
if (url) imageUrls.push(url);
} catch (uploadErr) {
console.warn('Image upload error, continuing without this photo:', uploadErr);
}
}
// 2. Submit the review
const newReview = await reviewService.submitReview(productId, {
rating,
title: title.trim(),
comment: comment.trim(),
author_name: authorName.trim(),
author_email: authorEmail.trim() || undefined,
image_urls: imageUrls,
});
setIsSuccess(true);
setTimeout(() => {
onReviewSubmitted(newReview);
onClose();
setIsSuccess(false);
}, 1500);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to submit review. Please try again.');
} finally {
setIsSubmitting(false);
}
};
const activeRating = hoverRating ?? rating;
return (
<div className="fixed inset-0 z-[120] flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs">
<div className="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl overflow-hidden border border-gray-100 animate-in fade-in zoom-in-95 duration-200">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 bg-[#fafbfc]">
<div>
<h3 className="text-base font-bold text-gray-900">Write a Review</h3>
<p className="text-xs text-gray-500 truncate max-w-xs">{productName}</p>
</div>
<button
type="button"
onClick={onClose}
className="p-1.5 text-gray-400 hover:text-gray-700 rounded-full hover:bg-gray-100 cursor-pointer"
>
<X size={18} />
</button>
</div>
{/* Success Banner */}
{isSuccess ? (
<div className="p-8 text-center space-y-3">
<CheckCircle2 size={48} className="mx-auto text-emerald-500 animate-bounce" />
<h4 className="text-lg font-bold text-gray-900">Thank You!</h4>
<p className="text-sm text-gray-600">
Your review has been submitted and is currently pending moderation. It will be published once approved by our team.
</p>
</div>
) : (
/* Form */
<form onSubmit={handleSubmit} className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
{errorMsg && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-xs text-red-700 flex items-center gap-2">
<AlertCircle size={15} className="shrink-0 text-red-500" />
<span>{errorMsg}</span>
</div>
)}
{/* Overall Rating */}
<div className="space-y-1.5 text-center sm:text-left">
<label className="block text-xs font-bold text-gray-700 uppercase tracking-wider">
Overall Rating *
</label>
<div className="flex items-center gap-1.5 justify-center sm:justify-start">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
type="button"
onClick={() => setRating(star)}
onMouseEnter={() => setHoverRating(star)}
onMouseLeave={() => setHoverRating(null)}
className="p-1 text-gray-300 hover:scale-110 transition-transform cursor-pointer"
>
<Star
size={24}
className={
star <= activeRating
? 'fill-amber-400 text-amber-400'
: 'text-gray-200'
}
/>
</button>
))}
<span className="text-xs font-semibold text-amber-700 ml-2">
{RATING_DESCRIPTIONS[activeRating] || ''}
</span>
</div>
</div>
{/* Review Title */}
<div>
<label className="block text-xs font-semibold text-gray-700 mb-1">
Headline / Summary *
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="e.g. Excellent display, perfectly fits my Samsung A80"
className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:border-primary"
required
/>
</div>
{/* Review Comment */}
<div>
<label className="block text-xs font-semibold text-gray-700 mb-1">
Detailed Review *
</label>
<textarea
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
placeholder="Share your experience: build quality, packaging, installation ease, and performance..."
className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:border-primary"
required
/>
</div>
{/* Google Autofill Banner / Action */}
{customer?.email ? (
<div className="flex items-center justify-between p-2.5 rounded-xl bg-blue-50/80 border border-blue-200/80 text-xs">
<div className="flex items-center gap-2 min-w-0">
<div className="w-6 h-6 rounded-full bg-white shadow-xs border border-blue-200 flex items-center justify-center shrink-0">
<GoogleIcon className="w-3.5 h-3.5" />
</div>
<span className="truncate text-blue-950">
Auto-filled from Google: <strong className="font-semibold text-blue-900">{customer.email}</strong>
</span>
</div>
<span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200 shrink-0">
<CheckCircle2 size={11} />
Verified Sync
</span>
</div>
) : (
<div className="flex items-center justify-between p-2.5 sm:p-3 rounded-xl bg-gradient-to-r from-gray-50 to-blue-50/40 border border-gray-200 hover:border-blue-300 transition-colors">
<div className="flex items-center gap-2.5 min-w-0">
<div className="w-7 h-7 rounded-full bg-white shadow-xs border border-gray-200 flex items-center justify-center shrink-0">
<GoogleIcon className="w-4 h-4" />
</div>
<div className="text-left">
<p className="text-xs font-semibold text-gray-800">Auto-fill with Google</p>
<p className="text-[11px] text-gray-500 hidden sm:block">1-click fetch name & verified buyer check</p>
</div>
</div>
<button
type="button"
onClick={() => setShowGoogleAuthModal(true)}
className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-white hover:bg-gray-50 text-gray-700 hover:text-gray-900 border border-gray-300 rounded-lg text-xs font-bold shadow-2xs transition-all cursor-pointer hover:border-gray-400 shrink-0"
>
<GoogleIcon className="w-3.5 h-3.5" />
<span>Continue with Google</span>
</button>
</div>
)}
{/* Name and Email */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<div className="flex items-center justify-between mb-1">
<label className="block text-xs font-semibold text-gray-700">
Your Name *
</label>
{isGoogleAutofilled && authorName && (
<span className="text-[10px] text-blue-600 font-medium inline-flex items-center gap-1">
<GoogleIcon className="w-2.5 h-2.5" /> Auto-filled
</span>
)}
</div>
<input
type="text"
value={authorName}
onChange={(e) => setAuthorName(e.target.value)}
placeholder="e.g. Adithiyan"
className="w-full px-3.5 py-2 border border-gray-300 rounded-lg text-sm text-gray-800 focus:outline-none focus:border-primary"
required
/>
</div>
<div>
<div className="flex items-center justify-between mb-1">
<label className="block text-xs font-semibold text-gray-700 truncate">
Email (Used for Verified Buyer check)
</label>
{isGoogleAutofilled && authorEmail && (
<span className="text-[10px] text-emerald-600 font-medium inline-flex items-center gap-1">
<CheckCircle2 size={10} /> Verified
</span>
)}
</div>
<input
type="email"
value={authorEmail}
onChange={(e) => setAuthorEmail(e.target.value)}
placeholder="name@example.com"
className="w-full px-3.5 py-2 border border-gray-300 rounded-lg text-sm text-gray-800 focus:outline-none focus:border-primary"
/>
</div>
</div>
{/* Photos Upload */}
<div>
<label className="block text-xs font-semibold text-gray-700 mb-1">
Attach Photos (Optional, up to 3)
</label>
<div className="flex flex-wrap items-center gap-2.5 pt-1">
{filePreviews.map((previewUrl, idx) => (
<div
key={idx}
className="relative w-16 h-16 rounded-lg overflow-hidden border border-gray-200 shadow-2xs"
>
<img src={previewUrl} alt="Preview" className="w-full h-full object-cover" />
<button
type="button"
onClick={() => removeFile(idx)}
className="absolute top-1 right-1 p-0.5 bg-black/60 text-white rounded-full hover:bg-black"
>
<X size={12} />
</button>
</div>
))}
{selectedFiles.length < 3 && (
<label className="w-16 h-16 border-2 border-dashed border-gray-300 hover:border-primary rounded-lg flex flex-col items-center justify-center text-gray-400 hover:text-primary cursor-pointer transition-colors">
<Upload size={16} />
<span className="text-[10px] font-semibold mt-0.5">Upload</span>
<input
type="file"
accept="image/jpeg,image/png,image/webp"
onChange={handleFileChange}
className="hidden"
/>
</label>
)}
</div>
</div>
{/* Footer Buttons */}
<div className="pt-3 border-t border-gray-100 flex items-center justify-end gap-3">
<button
type="button"
onClick={onClose}
disabled={isSubmitting}
className="px-4 py-2 border border-gray-300 rounded-lg text-xs font-semibold text-gray-700 hover:bg-gray-50 cursor-pointer"
>
Cancel
</button>
<button
type="submit"
disabled={isSubmitting}
className="px-6 py-2.5 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 shadow-sm inline-flex items-center gap-2 cursor-pointer disabled:opacity-60"
>
{isSubmitting ? (
<>
<Loader2 size={14} className="animate-spin" />
<span>Submitting…</span>
</>
) : (
<span>Submit Review</span>
)}
</button>
</div>
</form>
)}
</div>
{/* Google Auth Modal for 1-Click Auto-fill */}
<GoogleAuthModal
isOpen={showGoogleAuthModal}
onClose={() => setShowGoogleAuthModal(false)}
onSuccess={(data) => {
const resolvedName =
[data.first_name, data.last_name].filter(Boolean).join(' ') ||
data.first_name ||
data.name ||
data.email?.split('@')[0] ||
'';
if (resolvedName) setAuthorName(resolvedName);
if (data.email) setAuthorEmail(data.email);
setIsGoogleAutofilled(true);
setShowGoogleAuthModal(false);
}}
/>
</div>
);
}

View file

@ -1,105 +0,0 @@
'use client';
import React from 'react';
import { Star, ShieldCheck, PenLine } from 'lucide-react';
interface ReviewSummaryBreakdownProps {
averageRating: number;
totalReviews: number;
verifiedCount: number;
starDistribution: Record<string, number>;
onWriteReviewClick: () => void;
}
export function ReviewSummaryBreakdown({
averageRating,
totalReviews,
verifiedCount,
starDistribution,
onWriteReviewClick,
}: ReviewSummaryBreakdownProps) {
const starsList = [5, 4, 3, 2, 1];
return (
<div className="bg-[#fafbfc] border border-gray-200/80 rounded-xl p-6 mb-8">
<div className="grid grid-cols-1 md:grid-cols-12 gap-8 items-center">
{/* Left: Big Score & Stars */}
<div className="md:col-span-4 flex flex-col items-center md:items-start text-center md:text-left space-y-2 border-b md:border-b-0 md:border-r border-gray-200 pb-6 md:pb-0 md:pr-6">
<div className="flex items-baseline gap-2">
<span className="text-4xl font-extrabold text-gray-900">
{averageRating > 0 ? averageRating.toFixed(1) : '0.0'}
</span>
<span className="text-gray-400 text-sm font-medium">/ 5.0</span>
</div>
<div className="flex items-center gap-1 text-amber-400">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
size={18}
className={
i < Math.round(averageRating)
? 'fill-amber-400 text-amber-400'
: 'text-gray-200'
}
/>
))}
</div>
<p className="text-xs text-gray-500 font-medium">
Based on {totalReviews} {totalReviews === 1 ? 'review' : 'customer reviews'}
</p>
{verifiedCount > 0 && (
<div className="inline-flex items-center gap-1.5 text-xs text-emerald-700 font-semibold bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200/60 mt-1">
<ShieldCheck size={13} className="text-emerald-600" />
<span>{verifiedCount} Verified Purchases</span>
</div>
)}
<div className="pt-2 w-full">
<button
type="button"
onClick={onWriteReviewClick}
className="w-full py-2.5 px-4 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 transition-all shadow-xs inline-flex items-center justify-center gap-2 cursor-pointer"
>
<PenLine size={14} />
Write a Review
</button>
</div>
</div>
{/* Right: Star Distribution Progress Bars */}
<div className="md:col-span-8 space-y-2.5">
{starsList.map((stars) => {
const count = starDistribution[String(stars)] || 0;
const percent =
totalReviews > 0 ? Math.round((count / totalReviews) * 100) : 0;
return (
<div key={stars} className="flex items-center gap-3 text-xs">
<span className="w-12 font-semibold text-gray-700 flex items-center gap-1 shrink-0">
<span>{stars}</span>
<Star size={11} className="fill-amber-400 text-amber-400" />
</span>
<div className="flex-1 h-2.5 bg-gray-200 rounded-full overflow-hidden">
<div
className="h-full bg-amber-400 rounded-full transition-all duration-500"
style={{ width: `${percent}%` }}
/>
</div>
<div className="w-20 text-right text-gray-500 shrink-0 font-medium">
<span>{percent}%</span>
<span className="text-gray-400 text-[11px] ml-1.5">({count})</span>
</div>
</div>
);
})}
</div>
</div>
</div>
);
}

View file

@ -5,7 +5,7 @@ import Image from 'next/image';
import { useEffect, useState } from 'react';
import BlurHashImage from '@/components/ui/BlurHashImage';
import { ProductResponse } from '@/services/api/catalogService';
import { formatCurrency, getCatalogPriceInfo, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCurrency, getCatalogPriceInfo, getImageUrl } from '@/lib/utils';
interface YouMayAlsoLikeProps {
products: ProductResponse[];
@ -101,7 +101,7 @@ export function YouMayAlsoLike({ products }: YouMayAlsoLikeProps) {
style={{ gridTemplateColumns: `repeat(${Math.min(products.length, 5)}, minmax(168px, 1fr))` }}
>
{products.slice(0, 5).map((prod, index) => {
const img = resolveProductImage(prod);
const img = getImageUrl(prod.images?.[0]?.image_url || prod.variants?.[0]?.images?.[0]?.image_url);
const off = discountPct(prod);
const pricing = priceLabel(prod);
const onSale = off > 0;

View file

@ -4,21 +4,20 @@
*/
'use client';
import { useEffect, useState } from 'react';
import { useEffect } from 'react';
import Link from 'next/link';
import { X, Trash2, Plus, Minus, ShoppingBag, ArrowRight, Truck } from 'lucide-react';
import { useCartStore } from '@/store/cartStore';
import { formatCurrency, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCurrency, getImageUrl } from '@/lib/utils';
import { requireLoginForCheckout } from '@/lib/requireLoginForCheckout';
import { deliveryService, DeliverySettings } from '@/services/api/deliveryService';
function resolveItemImage(item: {
product: any;
selectedVariant: any;
product: { images?: { image_url?: string }[]; name?: string };
selectedVariant: { images?: { image_url?: string }[] };
}): string {
const fromVariant = item.selectedVariant?.thumbnail_url || item.selectedVariant?.images?.[0]?.image_url;
if (fromVariant) return getImageUrl(fromVariant);
return resolveProductImage(item.product);
const fromVariant = item.selectedVariant?.images?.[0]?.image_url;
const fromProduct = item.product?.images?.[0]?.image_url;
return getImageUrl(fromVariant || fromProduct || '');
}
export function CartDrawer() {
@ -28,11 +27,9 @@ export function CartDrawer() {
const removeFromCart = useCartStore((state) => state.removeFromCart);
const updateQuantity = useCartStore((state) => state.updateQuantity);
const getCartTotal = useCartStore((state) => state.getCartTotal);
const [deliverySettings, setDeliverySettings] = useState<DeliverySettings | null>(null);
useEffect(() => {
if (!isOpen) return;
deliveryService.getDeliverySettings().then(setDeliverySettings).catch(() => {});
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
const onKey = (e: KeyboardEvent) => {
@ -49,7 +46,7 @@ export function CartDrawer() {
const total = getCartTotal();
const itemCount = cart.reduce((sum, i) => sum + (i.quantity || 1), 0);
const freeShippingThreshold = deliverySettings?.free_delivery_min_order_amount || 999;
const freeShippingThreshold = 999;
const progressPercent = Math.min(100, (total / freeShippingThreshold) * 100);
const amountNeeded = Math.max(0, freeShippingThreshold - total);
@ -83,8 +80,8 @@ export function CartDrawer() {
</button>
</div>
{/* Dynamic Free shipping bar (only when enabled by admin) */}
{deliverySettings?.free_delivery_enabled && cart.length > 0 && (
{/* Free shipping bar */}
{cart.length > 0 && (
<div className="shrink-0 px-4 py-3 bg-[#f0f7ff] border-b border-[#d6e8fb]">
<div className="flex items-start gap-2 text-[12px] font-semibold text-[#1a1a1a] mb-2">
<Truck className="w-4 h-4 text-primary shrink-0 mt-0.5" />

View file

@ -12,29 +12,12 @@ 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 { formatCurrency, getImageUrl } from '@/lib/utils';
import { 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('');
@ -299,35 +282,33 @@ export function LiveSearch() {
{!loading && hasResults && (
<div className="p-2 divide-y divide-gray-100 text-xs">
{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 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">
{imgUrl ? (
<SearchItemImage
src={getImageUrl(imgUrl)}
alt={product.name}
/>
) : (
<div className="w-full h-full bg-gray-100" />
)}
{results.products.slice(0, 5).map((product) => (
<Link
key={product.product_id}
href={`/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)}
alt={product.name}
fill
className="object-cover"
/>
) : (
<div className="w-full h-full bg-gray-100" />
)}
</div>
<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)}
</div>
<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">
{formatCurrency(price)}
</div>
</div>
</Link>
);
})}
</div>
</Link>
))}
</div>
)}
</div>

View file

@ -14,7 +14,7 @@ import { useRouter } from 'next/navigation';
import { Star, Eye, Heart, ArrowLeftRight, ShoppingBag, Check } from 'lucide-react';
import { ProductResponse } from '@/services/api/catalogService';
import { useCartStore } from '@/store/cartStore';
import { formatCurrency, getImageUrl, resolveProductImage } from '@/lib/utils';
import { formatCurrency, getImageUrl } from '@/lib/utils';
import BlurHashImage from '@/components/ui/BlurHashImage';
import { addToCompareAndNavigate } from '@/lib/compare';
@ -31,10 +31,9 @@ export function ProductCard({ product }: ProductCardProps) {
const setQuickViewProduct = useCartStore((state) => state.setQuickViewProduct);
const router = useRouter();
const primaryVariant = product.variants?.[0];
const primaryImage = resolveProductImage(product);
const secondaryImage = getImageUrl(product.images?.[1]?.image_url) || primaryImage;
const productUrl = (product as any).variant_url || `/products/${product.slug}`;
const primaryVariant = product.variants[0];
const primaryImage = getImageUrl(product.images[0]?.image_url);
const secondaryImage = getImageUrl(product.images[1]?.image_url) || primaryImage;
const price = Number(primaryVariant?.price || 0);
const comparePrice = primaryVariant?.compare_price != null ? Number(primaryVariant.compare_price) : null;
@ -108,7 +107,7 @@ export function ProductCard({ product }: ProductCardProps) {
</div>
{/* Image Gallery Flip Container */}
<Link href={productUrl} className="block relative w-full pt-[85%] bg-gray-50 overflow-hidden">
<Link href={`/products/${product.slug}`} className="block relative w-full pt-[85%] bg-gray-50 overflow-hidden">
<BlurHashImage
src={primaryImage}
blurHash={(product as any).blur_hash || null}
@ -139,7 +138,7 @@ export function ProductCard({ product }: ProductCardProps) {
{/* Title */}
<Link
href={productUrl}
href={`/products/${product.slug}`}
className="text-xs font-bold text-[#1b2559] hover:text-[#e4382f] transition-colors line-clamp-2 leading-snug mb-2"
>
{product.name}
@ -152,9 +151,6 @@ export function ProductCard({ product }: ProductCardProps) {
<span className="text-sm font-extrabold text-[#e4382f]">
{formatCurrency(price)}
</span>
<span className="text-[10px] text-gray-400 font-medium">
+18% GST
</span>
{comparePrice && (
<span className="text-xs text-gray-400 line-through">
{formatCurrency(comparePrice)}

View file

@ -34,9 +34,9 @@ export function TopBar() {
</Link>
</div>
{/* Right Delivery Text */}
{/* Right Free Shipping Text */}
<div className="hidden md:flex items-center gap-1.5 text-[11px] font-semibold text-gray-700">
<span>Express Pan-India Delivery | 100% Genuine Spare Parts</span>
<span>Free Shipping on orders over ₹999!</span>
</div>
</div>
</div>

View file

@ -20,13 +20,6 @@ function SocialIcon({ name }: { name?: string }) {
</svg>
);
}
if (key.includes('whatsapp')) {
return (
<svg className={`${className} hover:text-[#25D366]`} viewBox="0 0 24 24" aria-hidden>
<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
</svg>
);
}
if (key.includes('twitter') || key === 'x') {
return (
<svg className="w-4.5 h-4.5 fill-current" viewBox="0 0 24 24" aria-hidden>
@ -200,13 +193,7 @@ export const Footer: React.FC = () => {
].filter((c) => c.links.length > 0)
);
const defaultSocials = [
{ platform: 'Instagram', url: 'https://instagram.com', icon: 'instagram' },
{ platform: 'Facebook', url: 'https://facebook.com', icon: 'facebook' },
{ platform: 'WhatsApp', url: 'https://wa.me/919080323589', icon: 'whatsapp' },
];
const rawSocials = (info.social_links || []).filter((s) => s?.url);
const socials = rawSocials.length > 0 ? rawSocials : defaultSocials;
const socials = (info.social_links || []).filter((s) => s?.url);
const payments = (info.payment_methods || []).filter((p) => p?.name || p?.icon_url);
return (

View file

@ -25,7 +25,7 @@ export const Header: React.FC = () => {
return (
<header
data-storefront-header
className={`mobile-sticky-header bg-white z-[110] border-b border-gray-100 transition-shadow duration-200 ${
className={`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-[28px] min-[400px]:text-[38px] font-black leading-none">
<span className="text-[#0073EC] text-[38px] font-black leading-none">
iFix
</span>
<span className="text-gray-900 text-[28px] min-[400px]:text-[38px] font-black leading-none">
<span className="text-gray-900 text-[38px] font-black leading-none">
Kart
</span>
</Link>

View file

@ -45,7 +45,7 @@ export const HeaderActions: React.FC = () => {
<button
onClick={triggerMobileDrawer}
className="xl:hidden p-2 text-gray-650 hover:text-primary transition-colors hover:bg-gray-50 rounded-lg cursor-pointer"
className="lg: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 hidden sm:block"
className="relative p-2 text-gray-650 hover:text-primary transition-colors hover:bg-gray-50 rounded-lg group focus:outline-none"
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 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"
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"
>
<div className="flex gap-2 items-center relative z-55">
<LiveSearch />

View file

@ -1,109 +0,0 @@
/**
* Google Analytics 4 (GA4) E-Commerce & Telemetry Tracker
* Property ID: 521198579 / iFixKart Storefront
*/
declare global {
interface Window {
dataLayer: any[];
gtag: (...args: any[]) => void;
}
}
export const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID || 'G-IFIXKART2026';
export function trackPageView(url: string) {
if (typeof window === 'undefined' || typeof window.gtag !== 'function') return;
try {
window.gtag('config', GA_MEASUREMENT_ID, {
page_path: url,
});
} catch (err) {
console.debug('[GA4] Pageview tracking suppressed', err);
}
}
export function trackEvent(action: string, params: Record<string, any> = {}) {
if (typeof window === 'undefined' || typeof window.gtag !== 'function') return;
try {
window.gtag('event', action, params);
} catch (err) {
console.debug('[GA4] Event tracking suppressed', err);
}
}
export function trackViewItem(product: {
id: string | number;
name: string;
price: number;
category?: string;
brand?: string;
sku?: string;
}) {
trackEvent('view_item', {
currency: 'INR',
value: product.price,
items: [
{
item_id: String(product.sku || product.id),
item_name: product.name,
price: product.price,
item_category: product.category || 'Spare Parts',
item_brand: product.brand || 'iFixKart',
quantity: 1,
},
],
});
}
export function trackAddToCart(product: {
id: string | number;
name: string;
price: number;
category?: string;
brand?: string;
sku?: string;
quantity?: number;
}) {
trackEvent('add_to_cart', {
currency: 'INR',
value: product.price * (product.quantity || 1),
items: [
{
item_id: String(product.sku || product.id),
item_name: product.name,
price: product.price,
item_category: product.category || 'Spare Parts',
item_brand: product.brand || 'iFixKart',
quantity: product.quantity || 1,
},
],
});
}
export function trackBeginCheckout(items: any[], totalValue: number) {
trackEvent('begin_checkout', {
currency: 'INR',
value: totalValue,
items: items.map((item) => ({
item_id: String(item.variant_id || item.product_id || item.id),
item_name: item.name || item.title,
price: item.price,
quantity: item.quantity || 1,
})),
});
}
export function trackPurchase(orderId: string, totalValue: number, items: any[]) {
trackEvent('purchase', {
transaction_id: orderId,
currency: 'INR',
value: totalValue,
items: items.map((item) => ({
item_id: String(item.variant_id || item.product_id || item.id),
item_name: item.name || item.title,
price: item.price,
quantity: item.quantity || 1,
})),
});
}

View file

@ -38,7 +38,7 @@ export const DEFAULT_FAQ_PAGE: FaqPageData = {
{
question: 'What payment modes are available for refurbished mobiles?',
answer:
'You can pay with Visa and Mastercard debit or credit cards, UPI, net banking, RuPay, and Razorpay-supported wallets. All orders require secure online prepaid payment.',
'You can pay with Visa and Mastercard debit or credit cards, UPI, net banking, RuPay, and Razorpay-supported wallets. Cash on delivery may not be available on every listing.',
},
{
question: 'Will I get a warranty card with the product?',

View file

@ -56,7 +56,7 @@ export const DEFAULT_PROMO_CARDS: any[] = [];
export const DEFAULT_PROMO_BANNERS: any[] = [];
export const DEFAULT_TRUST_FEATURES = [
{ title: 'Fast Express Shipping', desc: 'Pan-India Insured Delivery', icon: 'Truck' },
{ title: 'Free Shipping', desc: 'On orders over ₹1,000', icon: 'Truck' },
{ title: 'Flexible & Easy Return', desc: 'Return within 14 days', icon: 'RefreshCcw' },
{ title: '24/7 Support Services', desc: 'Any Time Customer Support', icon: 'Headphones' },
@ -173,7 +173,7 @@ export const DEFAULT_SECTION_TITLES: Record<string, { title: string; subtitle: s
},
trust_badges: {
title: 'Certified Quality Guarantee',
subtitle: 'Express Delivery, 1-Year Warranty & 24/7 Technical Support',
subtitle: 'Free Shipping, 1-Year Warranty & 24/7 Technical Support',
},
announcement_bar: {
title: 'Top Navigation Links',

View file

@ -52,7 +52,7 @@ export function buildPaymentsDoc(storeName: string): PaymentsDoc {
title: 'Accepted methods',
paragraphs: [
`At checkout you can pay with Visa and Mastercard debit or credit cards, RuPay, UPI, net banking, and Razorpay-supported wallets. The exact list on a product or repair booking is what we accept for that order.`,
'All orders are processed via secure online payment gateways (Cards, UPI, Netbanking, Wallets). Cash on delivery (COD) is not accepted.',
'Cash on delivery is not available on every listing. If COD is offered, it is shown before you confirm the order.',
'Split payments across cards, UPI, and wallets are not supported. Complete the order with a single method.',
],
},

View file

@ -93,18 +93,8 @@ export function getImageUrl(path?: string | null | unknown): string {
if (typeof path === 'string') {
resolvedPath = path;
} else if (path && typeof path === 'object') {
const obj = path as Record<string, any>;
resolvedPath = String(
obj.thumbnail_url ??
obj.image_url ??
obj.image ??
(Array.isArray(obj.images) && obj.images.length > 0
? (typeof obj.images[0] === 'string' ? obj.images[0] : (obj.images[0]?.image_url ?? ''))
: '') ??
obj.url ??
obj.src ??
''
);
const obj = path as Record<string, unknown>;
resolvedPath = String(obj.image_url ?? obj.url ?? obj.src ?? '');
} else {
return '/images/placeholder-product.webp';
}
@ -122,11 +112,6 @@ export function getImageUrl(path?: string | null | unknown): string {
trimmed.startsWith('data:') ||
trimmed.startsWith('blob:')
) {
// Strip loopback addresses like http://127.0.0.1:8010 or http://localhost:8000
if (trimmed.includes('127.0.0.1') || trimmed.includes('localhost')) {
const pathOnly = trimmed.replace(/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?/, '');
return pathOnly.startsWith('/uploads/') ? pathOnly : `/uploads${pathOnly.startsWith('/') ? pathOnly : `/${pathOnly}`}`;
}
return trimmed;
}
@ -151,34 +136,12 @@ export function getImageUrl(path?: string | null | unknown): string {
cleanPath = `/${withoutLeadingSlash}`;
} else if (withoutLeadingSlash.startsWith('product/')) {
cleanPath = `/uploads/${withoutLeadingSlash}`;
} else {
cleanPath = `/uploads/${withoutLeadingSlash}`;
}
}
// Always return relative /uploads/... so that:
// 1. In production (https://ifixkart.trionixsolution.com), Nginx serves /uploads/ directly from disk with SSL & caching.
// 2. In local dev, Next.js rewrites proxy /uploads/ transparently to https://ifixkartbe.trionixsolution.com/uploads/.
// 3. No loopback IP (127.0.0.1) or mixed-content (HTTP on HTTPS) errors can ever occur in the client browser.
return cleanPath;
const backendUrl =
process.env.NEXT_PUBLIC_API_URL || 'https://ifixkartbe.trionixsolution.com';
return `${backendUrl.replace(/\/$/, '')}${cleanPath}`;
}
/**
* Universal bulletproof image resolver for any product or variant representation.
* Prioritizes thumbnail_url, product.image, variant images, product images, and imageHover.
*/
export function resolveProductImage(product?: any): string {
if (!product) return '/images/placeholder-product.webp';
const raw =
product.thumbnail_url ||
product.image ||
product.images?.[0]?.image_url ||
(typeof product.images?.[0] === 'string' ? product.images[0] : null) ||
product.variants?.[0]?.thumbnail_url ||
product.variants?.[0]?.images?.[0]?.image_url ||
(typeof product.variants?.[0]?.images?.[0] === 'string' ? product.variants[0].images[0] : null) ||
product.imageHover;
return getImageUrl(raw);
}

View file

@ -9,7 +9,6 @@ const nextConfig: NextConfig = {
},
async rewrites() {
const backendUrl = process.env.NEXT_PUBLIC_API_URL || '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*',
@ -17,7 +16,7 @@ const nextConfig: NextConfig = {
},
{
source: '/uploads/:path*',
destination: `${mediaUrl}/uploads/:path*`,
destination: `${backendUrl}/uploads/:path*`,
},
];
},

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 992 B

View file

@ -141,7 +141,7 @@ export const ArticlesSection: React.FC<ArticlesSectionProps> = ({ config }) => {
1024: { slidesPerView: 3, spaceBetween: 22 },
1280: { slidesPerView: 4, spaceBetween: 24 },
}}
className="overflow-hidden"
className="!overflow-visible"
>
{articles.map((article) => (
<SwiperSlide key={article.id} className="h-auto">

View file

@ -24,19 +24,11 @@ interface BrandsSectionProps {
}
function toBrandItem(b: any, idx: number): BrandItem {
const rawLogo = b.logo_url || b.logo || b.image;
const isPlaceholder =
!rawLogo ||
rawLogo === 'null' ||
rawLogo === 'undefined' ||
String(rawLogo).includes('placeholder') ||
String(rawLogo).trim() === '';
return {
id: String(b.brand_id || b.id || b.slug || idx),
name: b.name || 'Brand',
slug: b.slug || String(b.brand_id || b.id || idx),
logo: isPlaceholder ? undefined : (getImageUrl(rawLogo) || undefined),
logo: getImageUrl(b.logo_url || b.logo || b.image) || undefined,
fontClass: FALLBACK_FONT,
};
}
@ -108,35 +100,32 @@ export const BrandsSection: React.FC<BrandsSectionProps> = ({
</div>
{loading ? (
<div className="flex md:grid md:grid-cols-5 gap-3 overflow-x-auto no-scrollbar py-1 snap-x">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3 md:gap-4">
{Array.from({ length: 10 }).map((_, i) => (
<div
key={i}
className="snap-start shrink-0 min-w-[130px] sm:min-w-[150px] md:min-w-0 md:w-auto h-[54px] md:h-[80px] rounded-xl bg-gray-100 animate-pulse"
/>
<BrandTileSkeleton key={i} />
))}
</div>
) : (
<div className="flex md:grid md:grid-cols-5 gap-3 overflow-x-auto no-scrollbar py-1 snap-x">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3 md:gap-4">
{brands.map((brand) => (
<Link
key={brand.id}
href={`/shop?brand=${encodeURIComponent(brand.slug)}`}
className="group snap-start shrink-0 min-w-[130px] sm:min-w-[150px] md:min-w-0 md:w-auto flex items-center justify-center h-[54px] md:h-[80px] px-4 rounded-xl bg-white md:bg-[#F3F3F3] border border-gray-200 md:border-transparent hover:border-primary/40 hover:bg-[#ebebeb] shadow-2xs md:shadow-none hover:shadow-sm transition-all"
className="group flex items-center justify-center h-[72px] md:h-[80px] px-4 rounded-lg bg-[#F3F3F3] hover:bg-[#ebebeb] transition-colors"
>
{brand.logo ? (
<img
src={brand.logo}
alt={brand.name}
className="max-h-[36px] md:max-h-[40px] max-w-[70%] object-contain opacity-75 group-hover:opacity-100 transition-opacity"
className="max-h-[36px] md:max-h-[40px] max-w-[70%] object-contain opacity-70 group-hover:opacity-100 transition-opacity"
style={{
filter: 'grayscale(1) contrast(0.85) brightness(0.55)',
}}
/>
) : (
<span
className={`select-none text-[#333] group-hover:text-primary transition-colors text-center ${
brand.fontClass || 'font-bold text-[14px] md:text-[15px]'
className={`select-none text-[#555] group-hover:text-[#222] transition-colors ${
brand.fontClass || 'font-bold text-[15px]'
}`}
>
{brand.name}

View file

@ -80,15 +80,11 @@ export const CategoriesSection: React.FC<CategoriesSectionProps> = ({
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [canSlide, setCanSlide] = useState(false);
const [productThumbs, setProductThumbs] = useState<Record<string, string>>({});
const [activeParentCat, setActiveParentCat] = useState<any | null>(null);
const [productThumbs, setProductThumbs] = useState<Record<string, string>>(
{}
);
const swiperRef = useRef<SwiperType | null>(null);
const rootCategories = React.useMemo(() => {
const roots = categories.filter((c) => !c.parent_category_id);
return roots.length > 0 ? roots : categories;
}, [categories]);
useEffect(() => {
const sortCats = (cats: any[]) =>
[...cats].sort((a, b) => {
@ -280,18 +276,19 @@ export const CategoriesSection: React.FC<CategoriesSectionProps> = ({
nextEl: '.cat-swiper-next',
}}
watchOverflow
spaceBetween={14}
slidesPerView={2.3}
spaceBetween={18}
slidesPerView={2}
breakpoints={{
480: { slidesPerView: 3, spaceBetween: 16 },
480: { slidesPerView: 3, spaceBetween: 18 },
768: { slidesPerView: 4, spaceBetween: 20 },
1024: { slidesPerView: 5, spaceBetween: 22 },
1280: { slidesPerView: 6, spaceBetween: 24 },
}}
>
{rootCategories.map((cat) => {
const rawCatImg = cat.image_url || cat.image || cat.icon_url;
const primarySrc = rawCatImg ? getImageUrl(rawCatImg) : '';
{categories.map((cat) => {
const primarySrc = getImageUrl(
cat.image_url || cat.image || cat.icon_url
);
const fallbackSrc =
productThumbs[cat.category_id] ||
productThumbs[cat.id] ||
@ -300,114 +297,33 @@ export const CategoriesSection: React.FC<CategoriesSectionProps> = ({
cat.product_count !== undefined && cat.product_count !== null
? Number(cat.product_count)
: null;
const hasSubs = cat.sub_categories && cat.sub_categories.length > 0;
return (
<SwiperSlide key={cat.category_id || cat.id || cat.slug}>
<div
onClick={(e) => {
if (hasSubs) {
e.preventDefault();
setActiveParentCat(cat);
}
}}
className="cursor-pointer"
<Link
href={cat.link || `/shop?category=${cat.slug}`}
className="flex flex-col items-center text-center group"
>
<Link
href={hasSubs ? '#' : (cat.link || `/shop?category=${cat.slug}`)}
onClick={(e) => {
if (hasSubs) {
e.preventDefault();
setActiveParentCat(cat);
}
}}
className="flex flex-col items-center text-center group"
>
<div className="w-full aspect-square bg-[#F5F5F5] rounded-xl flex items-center justify-center p-5 md:p-6 overflow-hidden transition-colors duration-200 group-hover:bg-[#ececec] relative">
<CategoryThumb
name={cat.name}
primarySrc={primarySrc}
fallbackSrc={fallbackSrc}
/>
{hasSubs && (
<span className="absolute bottom-2 right-2 bg-white/90 text-primary text-[10px] font-bold px-1.5 py-0.5 rounded shadow-xs">
{cat.sub_categories.length} sub
</span>
)}
</div>
<h3 className="text-[14px] font-bold text-[#333] mt-3 leading-snug group-hover:text-primary transition-colors">
{cat.name}
</h3>
<span className="text-[12px] text-[#888] mt-0.5">
{count !== null ? `${count} Products` : 'Shop now'}
</span>
</Link>
</div>
<div className="w-full aspect-square bg-[#F5F5F5] rounded-xl flex items-center justify-center p-5 md:p-6 overflow-hidden transition-colors duration-200 group-hover:bg-[#ececec]">
<CategoryThumb
name={cat.name}
primarySrc={primarySrc}
fallbackSrc={fallbackSrc}
/>
</div>
<h3 className="text-[14px] font-bold text-[#333] mt-3 leading-snug group-hover:text-primary transition-colors">
{cat.name}
</h3>
<span className="text-[12px] text-[#888] mt-0.5">
{count !== null ? `${count} Products` : 'Shop now'}
</span>
</Link>
</SwiperSlide>
);
})}
</Swiper>
</div>
)}
{/* Sub-Category Drilldown Modal */}
{activeParentCat && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs animate-in fade-in duration-200">
<div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl relative border border-gray-100 max-h-[85vh] flex flex-col">
<div className="flex items-center justify-between pb-4 border-b border-gray-100">
<div>
<h3 className="text-base font-bold text-gray-900">{activeParentCat.name}</h3>
<p className="text-xs text-gray-500 mt-0.5">
Select a sub-category to view products ({activeParentCat.product_count || 0} total items)
</p>
</div>
<button
type="button"
onClick={() => setActiveParentCat(null)}
className="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-500 hover:text-gray-800 transition-colors cursor-pointer text-sm font-bold"
>
✕
</button>
</div>
<div className="py-4 space-y-2 overflow-y-auto flex-1">
{(activeParentCat.sub_categories || []).map((sub: any) => (
<Link
key={sub.category_id || sub.slug}
href={`/products?category=${sub.slug}`}
onClick={() => setActiveParentCat(null)}
className="flex items-center justify-between p-3 rounded-xl border border-gray-100 hover:border-primary/40 hover:bg-primary/5 transition-all group"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-white transition-colors">
<Layers className="w-4 h-4" />
</div>
<div>
<p className="text-[13px] font-semibold text-gray-800 group-hover:text-primary transition-colors">
{sub.name}
</p>
<p className="text-[11px] text-gray-400">
{sub.product_count !== undefined ? `${sub.product_count} Products` : 'Browse'}
</p>
</div>
</div>
<ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-primary group-hover:translate-x-0.5 transition-all" />
</Link>
))}
</div>
<div className="pt-3 border-t border-gray-100 flex items-center justify-between gap-3">
<Link
href={`/shop?category=${activeParentCat.slug}`}
onClick={() => setActiveParentCat(null)}
className="w-full text-center py-2.5 px-4 bg-primary text-white text-xs font-bold rounded-xl hover:brightness-95 transition-all shadow-sm"
>
View All {activeParentCat.name} ({activeParentCat.product_count || 0})
</Link>
</div>
</div>
</div>
)}
</div>
</section>
);

View file

@ -19,8 +19,8 @@ const REFERENCE_FEATURES: FeatureItem[] = [
{
id: 'shipping',
icon: 'shipping',
title: 'Fast Express Delivery',
desc: 'Pan-India Insured Shipping',
title: 'Free Shipping',
desc: 'On order over $100',
},
{
id: 'return',

View file

@ -161,20 +161,20 @@ export const HeroSection: React.FC<HeroSectionProps> = ({
<div className="absolute -right-16 -top-20 w-72 h-72 rounded-full bg-primary/25 blur-3xl pointer-events-none z-[1]" />
<div className="absolute right-1/4 bottom-0 w-56 h-56 rounded-full bg-cyan-400/10 blur-3xl pointer-events-none z-[1]" />
<div className="relative z-10 h-full flex flex-col md:flex-row items-center justify-between gap-6 px-5 sm:px-12 lg:px-14 py-8 sm:py-10">
<div className="relative z-10 h-full flex flex-col md:flex-row items-center justify-between gap-6 px-8 sm:px-12 lg:px-14 py-10">
<div className="text-left flex-1 max-w-xl text-white">
{slide.badge ? (
<span className="techshop-layer techshop-layer-1 inline-block bg-primary text-[11px] font-extrabold uppercase tracking-wider px-3.5 py-1.5 rounded-md mb-3 sm:mb-4 shadow-sm">
<span className="techshop-layer techshop-layer-1 inline-block bg-primary text-[11px] font-extrabold uppercase tracking-wider px-3.5 py-1.5 rounded-md mb-4 shadow-sm">
{slide.badge}
</span>
) : null}
<h2 className="techshop-layer techshop-layer-2 text-2xl sm:text-4xl lg:text-[42px] font-extrabold tracking-tight leading-[1.12] sm:leading-[1.08] whitespace-pre-line mb-3 sm:mb-4 font-outfit drop-shadow-md">
<h2 className="techshop-layer techshop-layer-2 text-3xl sm:text-4xl lg:text-[42px] font-extrabold tracking-tight leading-[1.08] whitespace-pre-line mb-4 font-outfit drop-shadow-md">
{slide.title}
</h2>
{slide.subtitle ? (
<p className="techshop-layer techshop-layer-3 text-xs sm:text-sm md:text-base text-blue-100/95 font-medium mb-5 sm:mb-7 max-w-lg">
<p className="techshop-layer techshop-layer-3 text-sm md:text-base text-blue-100/95 font-medium mb-7 max-w-lg">
{slide.subtitle}
</p>
) : null}
@ -183,7 +183,7 @@ export const HeroSection: React.FC<HeroSectionProps> = ({
<div className="techshop-layer techshop-layer-4">
<Link
href={slide.buttonUrl || '/shop'}
className="inline-flex bg-primary hover:bg-primary-hover text-white text-xs md:text-sm font-semibold px-6 sm:px-8 py-3 sm:py-3.5 rounded-lg items-center shadow-lg transition-colors"
className="inline-flex bg-primary hover:bg-primary-hover text-white text-xs md:text-sm font-semibold px-8 py-3.5 rounded-lg items-center shadow-lg transition-colors"
>
{slide.buttonText}
</Link>

View file

@ -538,10 +538,12 @@ export const HotDealsSection: React.FC<HotDealsSectionProps> = ({
{/* ════════ Monthly Featured Item ════════ */}
<div
className="flex-1 min-w-0 flex flex-col lg:min-h-[364px]"
className="flex-1 min-w-0 flex flex-col"
style={{ minHeight: BLOCK_H }}
>
<div
className="flex items-center justify-between gap-3 shrink-0 border-b border-[#e5e5e5] h-[40px]"
className="flex items-center justify-between gap-3 shrink-0 border-b border-[#e5e5e5]"
style={{ height: FEAT_HEADER }}
>
<h3 className="text-[15px] font-bold text-[#222] leading-none whitespace-nowrap">
{featuredTitle}
@ -563,7 +565,12 @@ export const HotDealsSection: React.FC<HotDealsSectionProps> = ({
</div>
<div
className="grid grid-cols-2 lg:grid-cols-3 flex-1 gap-2.5 sm:gap-3.5 mt-3 sm:mt-3.5 sm:auto-rows-[148px]"
className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 flex-1"
style={{
gap: FEAT_GAP,
marginTop: FEAT_TOP_GAP,
gridAutoRows: `${FEAT_CARD_H}px`,
}}
>
{featuredProducts.map((product) => (
<FeaturedCard key={product.id} product={product} />
@ -594,10 +601,11 @@ const FeaturedCard: React.FC<{ product: Product }> = ({ product }) => {
return (
<Link
href={`/products/${product.slug || product.id}`}
className="flex flex-col sm:flex-row items-center gap-2 sm:gap-3 p-2.5 sm:p-3 bg-white border border-[#e8e8e8] rounded-xl hover:border-[#a8cce8] hover:shadow-xs transition-all group text-left overflow-hidden h-full"
className="flex items-center gap-3 px-3 bg-white border border-[#e8e8e8] rounded-[4px] hover:border-[#a8cce8] transition-colors group text-left overflow-hidden h-full"
>
<div
className="shrink-0 flex items-center justify-center overflow-hidden w-full h-[115px] sm:w-[96px] sm:h-[96px] bg-[#fafafa] sm:bg-transparent rounded-lg p-1.5 sm:p-0"
className="shrink-0 flex items-center justify-center overflow-hidden"
style={{ width: 96, height: 96 }}
>
{imageUrl ? (
<div className="relative w-full h-full">
@ -606,18 +614,18 @@ const FeaturedCard: React.FC<{ product: Product }> = ({ product }) => {
blurHash={(product as any).blur_hash || null}
alt={product.name}
fill
sizes="(max-width: 640px) 180px, 96px"
sizes="96px"
className="max-h-full max-w-full object-contain group-hover:scale-105 transition-transform duration-300"
/>
</div>
) : (
<div className="w-full h-full bg-gray-100 rounded" />
<div className="w-full h-full bg-gray-100" />
)}
</div>
<div className="w-full flex-1 min-w-0 flex flex-col justify-between sm:justify-center gap-1 py-0.5 sm:py-1 text-left">
<div className="flex-1 min-w-0 flex flex-col justify-center gap-1 py-1">
<h5
className="text-[12px] sm:text-[13px] font-bold text-[#222] line-clamp-2 sm:line-clamp-1 leading-snug group-hover:text-primary transition-colors"
className="text-[13px] font-bold text-[#222] line-clamp-1 leading-tight group-hover:text-primary transition-colors"
title={product.name}
>
{product.name}
@ -627,16 +635,16 @@ const FeaturedCard: React.FC<{ product: Product }> = ({ product }) => {
<div className="flex items-center gap-1.5 flex-wrap">
{product.oldPrice != null && product.oldPrice > product.price ? (
<span className="text-[10px] sm:text-[11px] text-gray-400 line-through">
<span className="text-[11px] text-gray-400 line-through">
{formatCurrency(Number(product.oldPrice))}
</span>
) : null}
<span className="text-[12px] sm:text-[13px] font-bold text-[#e53935]">
<span className="text-[13px] font-bold text-[#e53935]">
{formatCurrency(Number(product.price))}
</span>
</div>
<div className="text-[10px] text-gray-400 leading-[1.35] hidden sm:block">
<div className="text-[10px] text-gray-400 leading-[1.45]">
{line1 ? <p className="truncate">{line1}</p> : null}
{line2 ? <p className="truncate">{line2}</p> : null}
</div>

View file

@ -216,7 +216,7 @@ export const UltimateTechSection: React.FC<UltimateTechSectionProps> = ({
idx < 2 ? 'border-b md:border-b-0' : '',
].join(' ')}
>
<ProductCard product={product} products={techGadgets} variant="techshop" />
<ProductCard product={product} products={techGadgets} />
</div>
))}
</div>

View file

@ -42,7 +42,7 @@ export const catalogServerService = {
compatible_devices: any[];
specifications: any[];
}>(`/api/v1/catalog/products/detail/${slug}`, {
cache: 'no-store',
next: { revalidate: 60, tags: [`product-${slug}`] }
});
},

View file

@ -21,7 +21,6 @@ export interface CategoryResponse {
is_parent_feature?: boolean;
is_active: boolean;
product_count?: number;
sub_categories?: CategoryResponse[];
created_at: string;
}
@ -87,12 +86,10 @@ export interface ProductVariantResponse {
/** API may return decimal strings like "199.00" */
price: number | string;
compare_price: number | string | null;
mrp?: number | string | null;
cost_price: number | string;
low_stock_threshold: number;
status: string;
available_stock?: number;
thumbnail_url?: string | null;
attributes?: VariantAttributeResponse[];
images?: VariantImageResponse[];
}
@ -118,14 +115,8 @@ export interface ProductResponse {
description: string | null;
status: string;
created_at: string;
price?: number | string;
compare_price?: number | string | null;
mrp?: number | string | null;
thumbnail_url?: string | null;
images: ProductImageResponse[];
variants: ProductVariantResponse[];
warranty_type?: string | null;
warranty_summary?: string | null;
rating?: number;
review_count?: number;
badge?: 'HOT' | 'NEW' | 'SALE' | null;
@ -134,12 +125,6 @@ export interface ProductResponse {
color?: string | null;
colors?: string[];
brand_name?: string | null;
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 {
@ -189,10 +174,6 @@ 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 {
@ -235,9 +216,6 @@ 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));
@ -267,7 +245,7 @@ export const catalogService = {
category_id: p.category_id,
slug: p.slug,
name: p.name,
thumbnail_url: (p as any).thumbnail_url || p.images?.[0]?.image_url || null,
thumbnail_url: p.images[0]?.image_url || null,
price,
compare_price,
discount_percent,

View file

@ -47,21 +47,6 @@ export interface RazorpayInitiateResponse {
invoice_no?: string | null;
}
export interface AvailableCoupon {
coupon_id: string;
code: string;
title: string;
description?: string | null;
discount_type: 'PERCENTAGE' | 'FIXED' | 'FREE_SHIPPING';
discount_value: number;
max_discount_cap?: number | null;
min_order_amount: number;
first_order_only: boolean;
valid_to?: string | null;
is_eligible: boolean;
ineligibility_reason?: string | null;
}
export async function syncCartItems(items: SyncCartItem[]) {
return apiFetch<{ message: string; cart_id: string }>('/api/v1/cart/items', {
method: 'PUT',
@ -73,15 +58,13 @@ export async function createCheckoutOrder(payload: {
address_id: string;
payment_method?: string;
coupon_code?: string;
use_wallet_credits?: boolean;
}) {
return apiFetch<CheckoutCreateResponse>('/api/v1/checkout/create', {
method: 'POST',
body: JSON.stringify({
address_id: payload.address_id,
payment_method: payload.payment_method || 'RAZORPAY',
payment_method: payload.payment_method || 'COD',
coupon_code: payload.coupon_code,
use_wallet_credits: Boolean(payload.use_wallet_credits),
}),
});
}
@ -90,10 +73,6 @@ export async function fetchCustomerAddresses() {
return apiFetch<CustomerAddress[]>('/api/v1/customer/profile/addresses');
}
export async function fetchAvailableCoupons() {
return apiFetch<AvailableCoupon[]>('/api/v1/storefront/coupons');
}
export async function createCustomerAddress(address: Omit<CustomerAddress, 'address_id'> & { address_id?: string }) {
return apiFetch<CustomerAddress>('/api/v1/customer/profile/addresses', {
method: 'POST',

View file

@ -93,7 +93,6 @@ export async function apiFetch<T>(
try {
const response = await fetch(`${baseUrl}${endpoint}`, {
cache: rest.cache ?? 'no-store',
...rest,
headers,
credentials: 'include',
@ -104,7 +103,6 @@ export async function apiFetch<T>(
if (refreshed) {
headers['Authorization'] = `Bearer ${getAccessToken()}`;
const retryResponse = await fetch(`${baseUrl}${endpoint}`, {
cache: rest.cache ?? 'no-store',
...rest,
headers,
credentials: 'include',
@ -157,7 +155,6 @@ export interface RestoredSession {
customer_id: string;
email: string;
first_name: string;
last_name?: string;
}
/**
@ -180,7 +177,6 @@ export async function restoreCustomerSession(): Promise<RestoredSession | null>
customer_id: data.customer_id,
email: data.email,
first_name: data.first_name,
last_name: data.last_name,
};
} catch {
return null;

View file

@ -1,57 +0,0 @@
import { apiFetch } from './client';
export interface WalletTransaction {
transaction_id: string;
transaction_type: 'EARN' | 'REDEEM' | 'REFUND' | 'ADJUSTMENT' | string;
reference_type: string;
reference_id: string;
reference_no: string;
base_amount: number;
percentage_applied: number | null;
credit_amount: number;
status: 'PENDING' | 'MATURED' | 'COMPLETED' | 'VOIDED' | 'EXPIRED' | string;
matures_at: string | null;
matured_at: string | null;
voided_at: string | null;
void_reason: string | null;
description: string | null;
created_at: string | null;
}
export interface WalletSummary {
wallet_id: string;
customer_id: string;
active_balance: number;
pending_balance: number;
lifetime_earned: number;
lifetime_redeemed: number;
currency: string;
is_locked: boolean;
transactions: WalletTransaction[];
}
export interface CreditSettings {
credits_enabled: boolean;
credits_sales_percentage: number;
credits_sales_return_window_days: number;
credits_service_percentage: number;
credits_service_claim_window_days: number;
credits_minimum_order_value: number;
credits_expiry_days: number;
}
export const creditService = {
/**
* Retrieves the current customer's spendable balance, pending balance, and transaction history.
*/
async getMyWallet(): Promise<WalletSummary> {
return apiFetch<WalletSummary>('/api/v1/credits/my-wallet');
},
/**
* Retrieves current credit & return window parameters.
*/
async getCreditSettings(): Promise<CreditSettings> {
return apiFetch<CreditSettings>('/api/v1/credits/settings', { skipAuth: true });
},
};

View file

@ -1,25 +0,0 @@
import { apiFetch } from './client';
export interface DeliverySettings {
delivery_charge: number;
free_delivery_enabled: boolean;
free_delivery_min_order_amount: number;
}
export const deliveryService = {
/**
* Retrieves active delivery fee and dynamic free delivery configuration.
*/
async getDeliverySettings(): Promise<DeliverySettings> {
try {
return await apiFetch<DeliverySettings>('/api/v1/settings/delivery', { skipAuth: true });
} catch {
// Fallback defaults if offline or uninitialized
return {
delivery_charge: 99.0,
free_delivery_enabled: false,
free_delivery_min_order_amount: 999.0,
};
}
},
};

View file

@ -1,104 +0,0 @@
import { apiFetch, getBaseUrl } from './client';
export interface ProductReviewItem {
review_id: string;
product_id: string;
author_name: string;
rating: number;
title: string;
comment: string;
verified_buyer: boolean;
is_approved?: boolean;
helpful_count: number;
admin_reply?: string | null;
review_date?: string | null;
images: string[];
}
export interface ProductReviewSummaryResponse {
average_rating: number;
total_reviews: number;
star_distribution: Record<string, number>;
verified_count: number;
page: number;
limit: number;
reviews: ProductReviewItem[];
}
export interface ReviewCreatePayload {
rating: number;
title: string;
comment: string;
author_name: string;
author_email?: string;
image_urls?: string[];
}
export const reviewService = {
async getProductReviews(
productId: string,
page: number = 1,
limit: number = 10,
sort: string = 'newest'
): Promise<ProductReviewSummaryResponse> {
const params = new URLSearchParams({
page: String(page),
limit: String(limit),
sort,
});
try {
return await apiFetch<ProductReviewSummaryResponse>(
`/api/v1/storefront/reviews/${productId}?${params.toString()}`
);
} catch {
// Graceful fallback if no reviews yet
return {
average_rating: 0,
total_reviews: 0,
star_distribution: { '5': 0, '4': 0, '3': 0, '2': 0, '1': 0 },
verified_count: 0,
page: 1,
limit,
reviews: [],
};
}
},
async submitReview(
productId: string,
payload: ReviewCreatePayload
): Promise<ProductReviewItem> {
return await apiFetch<ProductReviewItem>(
`/api/v1/storefront/reviews/${productId}`,
{
method: 'POST',
body: JSON.stringify(payload),
}
);
},
async uploadReviewImage(file: File, productId: string): Promise<string> {
const baseUrl = getBaseUrl();
const formData = new FormData();
formData.append('file', file);
formData.append('entity_type', 'review');
formData.append('entity_id', productId);
const res = await fetch(
`${baseUrl}/api/v1/files/upload?entity_type=review&entity_id=${encodeURIComponent(productId)}`,
{
method: 'POST',
body: formData,
}
);
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: 'Upload failed' }));
throw new Error(err.detail || 'Failed to upload review image');
}
const data = await res.json();
return data.file_url || data.url || '';
},
};

View file

@ -65,7 +65,6 @@ export interface ServiceBookingPayload {
};
service_id?: string;
custom_service_name?: string;
quoted_price?: number;
customer_name?: string;
customer_email?: string;
customer_phone?: string;
@ -126,12 +125,12 @@ async function loadAdminCatalog(force = false): Promise<CatalogCache> {
repairServices,
repairVariants,
] = await Promise.all([
apiFetch<any[]>('/api/v1/catalog/brands/all', { skipAuth: true }),
apiFetch<any[]>('/api/v1/catalog/device-series/all', { skipAuth: true }),
apiFetch<any[]>('/api/v1/catalog/device-models/all', { skipAuth: true }),
apiFetch<any[]>('/api/v1/catalog/service-types/all', { skipAuth: true }),
apiFetch<any[]>('/api/v1/catalog/repair-services/all', { skipAuth: true }),
apiFetch<any[]>('/api/v1/catalog/repair-variants/all', { skipAuth: true }),
apiFetch<any[]>('/api/v1/catalog/brands/all'),
apiFetch<any[]>('/api/v1/catalog/device-series/all'),
apiFetch<any[]>('/api/v1/catalog/device-models/all'),
apiFetch<any[]>('/api/v1/catalog/service-types/all'),
apiFetch<any[]>('/api/v1/catalog/repair-services/all'),
apiFetch<any[]>('/api/v1/catalog/repair-variants/all'),
]);
catalogCache = {
@ -219,19 +218,12 @@ function buildRepairConfigFromCatalog(
export const serviceBookingService = {
async fetchLocations(): Promise<any[]> {
try {
const locations = await apiFetch<any[]>('/api/v1/system/locations', { skipAuth: true });
const locations = await apiFetch<any[]>('/api/v1/system-config/locations');
if (Array.isArray(locations) && locations.length > 0) {
return locations.filter((l) => l.is_active !== false);
return locations;
}
} catch {
try {
const locations = await apiFetch<any[]>('/api/v1/system-config/locations', { skipAuth: true });
if (Array.isArray(locations) && locations.length > 0) {
return locations.filter((l) => l.is_active !== false);
}
} catch {
/* fallback */
}
/* fallback */
}
return [
{ location_id: 'loc_chennai_hq', name: 'Chennai Store HQ', code: 'CHENNAI', address: 'Chennai Central' },
@ -239,20 +231,16 @@ export const serviceBookingService = {
},
fetchDeviceTypes(): Promise<string[]> {
return apiFetch<string[]>('/api/v1/catalog/device-types', { skipAuth: true });
return apiFetch<string[]>('/api/v1/catalog/device-types');
},
async fetchBrands(deviceType?: string): Promise<any[]> {
try {
const brands = await apiFetch<any[]>('/api/v1/catalog/brands/all', { skipAuth: true });
if (Array.isArray(brands) && brands.length > 0) {
// Kick off background cache of the rest of the catalog for smooth series/model selection
void loadAdminCatalog().catch(() => {});
const filtered = brands
.filter(isActive)
.filter((b) => brandMatchesDeviceType(b, deviceType));
if (filtered.length > 0) return filtered;
}
const cache = await loadAdminCatalog();
const filtered = cache.brands
.filter(isActive)
.filter((b) => brandMatchesDeviceType(b, deviceType));
if (filtered.length > 0) return filtered;
} catch {
/* demo fallback */
}
@ -414,7 +402,7 @@ export const serviceBookingService = {
serviceId
)}&target_date=${encodeURIComponent(targetDate)}`
);
if (Array.isArray(data)) return data;
if (Array.isArray(data) && data.length > 0) return data;
} catch {
/* fall through */
}
@ -507,21 +495,6 @@ export const serviceBookingService = {
});
},
fetchCalendarInvite(jobId: string): Promise<{
job_id: string;
job_no: string;
appointment_id: string;
scheduled_start: string;
scheduled_end: string;
device_name: string;
google_calendar_url: string;
store_name: string;
store_address: string;
ics_download_url: string;
}> {
return apiFetch(`/api/v1/service/jobs/${jobId}/calendar-invite`);
},
fetchServicePageLayout(): Promise<any[]> {
return apiFetch<any[]>('/api/v1/storefront/layout/services');
},

View file

@ -121,11 +121,7 @@ export const storefrontService = {
}
try {
const data = await apiFetch<LiveSearchResult>(API_ENDPOINTS.STOREFRONT_LIVE_SEARCH(query.trim(), category));
return {
...data,
products: (data.products || []).map((p: any) => mapProductCardToProductResponse(p)),
};
return await apiFetch<LiveSearchResult>(API_ENDPOINTS.STOREFRONT_LIVE_SEARCH(query.trim(), category));
} catch {
try {
const res = await catalogService.getProductsPaginated({
@ -209,29 +205,6 @@ export const storefrontService = {
}
},
async getPageLayout(page: string): Promise<any[]> {
try {
const data = await apiFetch<any[]>(`/api/v1/storefront/layout/${page}`);
return Array.isArray(data) ? data : [];
} catch {
return [];
}
},
async submitFeedback(payload: {
name: string;
email: string;
topic: string;
order_no?: string;
rating: number;
message: string;
}): Promise<{ message: string; feedback_id?: string }> {
return await apiFetch<{ message: string; feedback_id?: string }>('/api/v1/storefront/feedback', {
method: 'POST',
body: JSON.stringify(payload),
});
},
async getCatalogFilters(): Promise<CatalogFiltersData> {
try {
return await apiFetch<CatalogFiltersData>('/api/v1/storefront/catalog-filters');
@ -281,7 +254,7 @@ export const MOCK_REVIEWS: ProductReview[] = [
];
export const MOCK_TRUST_BADGES: TrustBadge[] = [
{ id: 'tb1', title: 'Express Delivery', subtitle: 'Fast & Insured Pan-India', icon: 'truck' },
{ id: 'tb1', title: 'Free Shipping', subtitle: 'On order over $100', icon: 'truck' },
{ id: 'tb2', title: 'Flexible & Easy Return', subtitle: 'Return within 14 days', icon: 'refresh' },
{ id: 'tb3', title: '24/7 Support Services', subtitle: 'Any Time Customer Support', icon: 'headset' },
{ id: 'tb4', title: 'Secure payment', subtitle: '100% Fast & Secure Payment', icon: 'shield' },

View file

@ -111,7 +111,6 @@ export const useAuthStore = create<AuthState>((set, get) => ({
customer_id: restored.customer_id,
email: restored.email,
first_name: restored.first_name,
last_name: restored.last_name,
};
set({
accessToken: restored.access_token,

View file

@ -11,17 +11,6 @@ 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,

View file

@ -33,9 +33,7 @@ export function mapProductCardToProductResponse(
{
variant_id: p.first_variant_id || p.product_id,
product_id: p.product_id,
// 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 || '',
sku: (p as any).sku || '',
barcode: null,
price,
compare_price: comparePrice && comparePrice > 0 ? comparePrice : null,
@ -63,9 +61,7 @@ export function mapProductCardToProductResponse(
device_model_id: (p as any).device_model_id || null,
name: p.name,
slug: 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,
full_path: (p as any).full_path || `/products/${p.slug}`,
description: (p as any).description ?? null,
status: (p as any).status || 'active',
created_at: (p as any).created_at || '',
@ -105,16 +101,11 @@ export function mapProductCardToProductResponse(
export function mapCatalogProductToProduct(
p: ProductResponse | ProductCardResponse | Record<string, any>
): Product {
const cardMapped = mapProductCardToProductResponse(p);
const normalized: ProductResponse =
Array.isArray((p as any).variants) && (p as any).variants.length > 0
? ({
...cardMapped,
...mapProductCardToProductResponse(p),
...p,
images:
Array.isArray((p as any).images) && (p as any).images.length > 0
? (p as any).images
: cardMapped.images,
variants: (p as any).variants.map((v: any) => ({
...v,
price: parseMoney(v.price),
@ -124,7 +115,7 @@ export function mapCatalogProductToProduct(
: null,
})),
} as ProductResponse)
: cardMapped;
: mapProductCardToProductResponse(p);
const { price, priceMax, oldPrice, discount } = getCatalogPriceInfo(normalized);