fixed some bugs

This commit is contained in:
@jcarymuhammedow
2026-02-05 19:36:12 +05:00
parent c68ac335c6
commit f32e7538e1
20 changed files with 1476 additions and 734 deletions

View File

@@ -136,7 +136,7 @@ export default function CartPage() {
shipping_method: "standart",
payment_type_id: paymentType.id,
region: selectedRegion,
note: note || undefined,
notes: note || undefined,
},
{
onSuccess: () => {

View File

@@ -44,72 +44,72 @@
}
:root {
--radius: 0.625rem;
--background: #eff3f6;
--foreground: oklch(0.141 0.005 285.823);
--card: oklch(1 0 0);
--card-foreground: oklch(0.141 0.005 285.823);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.141 0.005 285.823);
--primary: oklch(0.21 0.006 285.885);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.967 0.001 286.375);
--secondary-foreground: oklch(0.21 0.006 285.885);
--muted: oklch(0.967 0.001 286.375);
--muted-foreground: oklch(0.552 0.016 285.938);
--accent: oklch(0.967 0.001 286.375);
--accent-foreground: oklch(0.21 0.006 285.885);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.92 0.004 286.32);
--input: oklch(0.92 0.004 286.32);
--ring: oklch(0.705 0.015 286.067);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.141 0.005 285.823);
--sidebar-primary: oklch(0.21 0.006 285.885);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.967 0.001 286.375);
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
--sidebar-border: oklch(0.92 0.004 286.32);
--sidebar-ring: oklch(0.705 0.015 286.067);
--radius: 1rem;
--background: #fafafa;
--foreground: #0a0a0a;
--card: #ffffff;
--card-foreground: #0a0a0a;
--popover: #ffffff;
--popover-foreground: #0a0a0a;
--primary: #0a0a0a;
--primary-foreground: #ffffff;
--secondary: #f5f5f5;
--secondary-foreground: #0a0a0a;
--muted: #f5f5f5;
--muted-foreground: #737373;
--accent: #f5f5f5;
--accent-foreground: #0a0a0a;
--destructive: #ef4444;
--border: #e5e5e5;
--input: #e5e5e5;
--ring: #0a0a0a;
--chart-1: #6366f1;
--chart-2: #8b5cf6;
--chart-3: #ec4899;
--chart-4: #f59e0b;
--chart-5: #10b981;
--sidebar: #ffffff;
--sidebar-foreground: #0a0a0a;
--sidebar-primary: #0a0a0a;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f5f5f5;
--sidebar-accent-foreground: #0a0a0a;
--sidebar-border: #e5e5e5;
--sidebar-ring: #0a0a0a;
}
.dark {
--background: oklch(0.141 0.005 285.823);
--foreground: oklch(0.985 0 0);
--card: oklch(0.21 0.006 285.885);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.21 0.006 285.885);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.92 0.004 286.32);
--primary-foreground: oklch(0.21 0.006 285.885);
--secondary: oklch(0.274 0.006 286.033);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.274 0.006 286.033);
--muted-foreground: oklch(0.705 0.015 286.067);
--accent: oklch(0.274 0.006 286.033);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.552 0.016 285.938);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.21 0.006 285.885);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.274 0.006 286.033);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.552 0.016 285.938);
--background: #0a0a0a;
--foreground: #fafafa;
--card: #171717;
--card-foreground: #fafafa;
--popover: #171717;
--popover-foreground: #fafafa;
--primary: #fafafa;
--primary-foreground: #0a0a0a;
--secondary: #262626;
--secondary-foreground: #fafafa;
--muted: #262626;
--muted-foreground: #a3a3a3;
--accent: #262626;
--accent-foreground: #fafafa;
--destructive: #dc2626;
--border: #262626;
--input: #262626;
--ring: #fafafa;
--chart-1: #818cf8;
--chart-2: #a78bfa;
--chart-3: #f472b6;
--chart-4: #fbbf24;
--chart-5: #34d399;
--sidebar: #171717;
--sidebar-foreground: #fafafa;
--sidebar-primary: #fafafa;
--sidebar-primary-foreground: #0a0a0a;
--sidebar-accent: #262626;
--sidebar-accent-foreground: #fafafa;
--sidebar-border: #262626;
--sidebar-ring: #fafafa;
}
@layer base {
@@ -117,13 +117,52 @@
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
@apply bg-background text-foreground antialiased;
}
}
/* Toast Customization */
[data-sonner-toast] {
@apply rounded-2xl shadow-lg border-0;
}
[data-sonner-toast] [data-description] {
color: #000 !important;
opacity: 0.9;
color: #525252 !important;
opacity: 1;
}
[data-sonner-toast][data-type="success"] {
@apply bg-emerald-50 text-emerald-900;
}
[data-sonner-toast][data-type="error"] {
@apply bg-red-50 text-red-900;
}
/* Scrollbar Styling */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
@apply bg-transparent;
}
::-webkit-scrollbar-thumb {
@apply bg-gray-300 rounded-full;
}
::-webkit-scrollbar-thumb:hover {
@apply bg-gray-400;
}
.dark ::-webkit-scrollbar-thumb {
@apply bg-gray-700;
}
.dark ::-webkit-scrollbar-thumb:hover {
@apply bg-gray-600;
}
@layer utilities {
@@ -133,47 +172,109 @@
.bg-bg {
background-color: var(--bg);
}
/* Custom Gradient Utilities */
.gradient-primary {
background: linear-gradient(135deg, #0a0a0a 0%, #262626 100%);
}
.gradient-card {
background: linear-gradient(145deg, #fafafa 0%, #f5f5f5 100%);
}
/* Animation Utilities */
.animate-fade-in {
animation: fadeIn 0.3s ease-in-out;
}
.animate-scale-up {
animation: scaleUp 0.2s ease-in-out;
}
.animate-slide-up {
animation: slideUp 0.3s ease-out;
}
/* Shopping Cart Animations */
.stroke-primary {
stroke: #005bff;
stroke: #0a0a0a;
}
.stroke-track {
stroke: hsla(var(--hue), 10%, 10%, 0.1);
transition: stroke var(--trans-dur);
stroke: rgba(10, 10, 10, 0.1);
transition: stroke 0.3s ease;
}
@media (prefers-color-scheme: dark) {
.stroke-track {
stroke: hsla(var(--hue), 10%, 90%, 0.1);
stroke: rgba(250, 250, 250, 0.1);
}
}
.animate-msg {
animation: msg 0.3s 13.7s linear forwards;
}
.animate-msgLast {
animation: msg 0.3s 14s linear reverse forwards;
}
.animate-cartLines {
animation: cartLines 2s ease-in-out infinite;
}
.animate-cartTop {
animation: cartTop 2s ease-in-out infinite;
}
.animate-cartWheel1 {
animation: cartWheel1 2s ease-in-out infinite;
transform: rotate(-0.25turn);
transform-origin: 43px 111px;
}
.animate-cartWheel2 {
animation: cartWheel2 2s ease-in-out infinite;
transform: rotate(0.25turn);
transform-origin: 102px 111px;
}
.animate-cartWheelStroke {
animation: cartWheelStroke 2s ease-in-out infinite;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes scaleUp {
from {
transform: scale(0.95);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
@keyframes slideUp {
from {
transform: translateY(10px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
@keyframes msg {
from {
opacity: 1;
@@ -188,6 +289,7 @@
visibility: hidden;
}
}
@keyframes cartLines {
from,
to {
@@ -198,6 +300,7 @@
opacity: 1;
}
}
@keyframes cartTop {
from {
stroke-dashoffset: -338;
@@ -209,6 +312,7 @@
stroke-dashoffset: 338;
}
}
@keyframes cartWheel1 {
from {
transform: rotate(-0.25turn);
@@ -217,6 +321,7 @@
transform: rotate(2.75turn);
}
}
@keyframes cartWheel2 {
from {
transform: rotate(0.25turn);
@@ -225,6 +330,7 @@
transform: rotate(3.25turn);
}
}
@keyframes cartWheelStroke {
from,
to {
@@ -234,3 +340,21 @@
stroke-dashoffset: 40.84;
}
}
/* Focus Visible Improvements */
*:focus-visible {
@apply outline-2 outline-offset-2 outline-gray-900;
}
.dark *:focus-visible {
@apply outline-gray-100;
}
/* Selection Styling */
::selection {
@apply bg-gray-900 text-white;
}
.dark ::selection {
@apply bg-gray-100 text-gray-900;
}

View File

@@ -54,10 +54,14 @@ export default function Header({ locale = "ru" }: HeaderProps) {
return (
<>
<header className="sticky top-0 z-50 w-full border-b bg-white shadow-sm">
<div className="mx-auto px-4">
<div className="flex h-16 items-center justify-between gap-3">
<Link href="/" className="shrink-0">
<header className="sticky top-0 z-50 w-full border-b border-gray-200 bg-white/95 backdrop-blur-md shadow-sm ">
<div className="mx-auto px-4 lg:px-6 max-w-[1520px]">
<div className="flex h-16 items-center justify-between gap-2 lg:gap-3">
{/* Logo */}
<Link
href="/"
className="shrink-0 transition-opacity hover:opacity-80"
>
<div className="relative h-8 w-[180px]">
<Image
src={Logo}
@@ -69,31 +73,36 @@ export default function Header({ locale = "ru" }: HeaderProps) {
</div>
</Link>
{/* Catalog Button - Desktop */}
<Button
data-catalog-trigger
onClick={toggleCategoryMenu}
className="cursor-pointer hidden gap-2 rounded-lg font-bold lg:flex hover:bg-[#005bff] bg-[#005bff] text-white"
className="cursor-pointer hidden gap-2.5 font-semibold lg:flex hover:bg-gray-800 bg-gray-900 text-white transition-all duration-200 shadow-sm hover:shadow-md"
size="lg"
>
{isCategoryOpen ? <X className="h-5 w-5" /> : <CategoryIcon />}
{t("common.catalog")}
</Button>
<div className="flex items-center gap-2 sm:hidden cursor-pointer">
{/* Mobile Search & Language */}
<div className="flex items-center gap-2 sm:hidden">
<Button
variant="ghost"
size="icon"
onClick={() => setIsMobileSearchOpen(true)}
className="hover:bg-gray-100 rounded-lg transition-colors"
>
<Search className="h-5 w-5" />
<Search className="h-5 w-5 text-gray-700" />
</Button>
<LanguageSelector />
</div>
{/* Desktop Language Selector */}
<div className="hidden sm:block">
<LanguageSelector />
</div>
{/* Desktop Search Bar */}
<SearchBar
isMobile={false}
searchPlaceholder={t("common.search")}
@@ -101,6 +110,7 @@ export default function Header({ locale = "ru" }: HeaderProps) {
locale={locale}
/>
{/* Action Buttons */}
<ActionButtons
isAuthenticated={isAuthenticated}
onAuthClick={handleAuthClick}

View File

@@ -9,11 +9,7 @@ import { useCart, useFavorites, useOrders, useCartCount } from "@/lib/hooks";
import { Skeleton } from "@/components/ui/skeleton";
import { useTranslations } from "next-intl";
import { useLogout } from "@/lib/hooks/useAuth";
import {
CartIcon,
FavoriteIcon,
OrderIcon,
} from "@/components/icons";
import { CartIcon, FavoriteIcon, OrderIcon } from "@/components/icons";
interface ActionButtonsProps {
isAuthenticated: boolean;
@@ -44,16 +40,13 @@ export default function ActionButtons({
const { data: favoritesData, isLoading: favoritesLoading } = useFavorites();
const { data: ordersData, isLoading: ordersLoading } = useOrders();
// Calculate cart count from cart items array
const cartCount = useCartCount()
const cartCount = useCartCount();
// Calculate favorites count
const favoritesCount = useMemo(() => {
if (!favoritesData) return 0;
return Array.isArray(favoritesData) ? favoritesData.length : 0;
}, [favoritesData]);
// Calculate orders count
const ordersCount = useMemo(() => {
if (!ordersData) return 0;
return Array.isArray(ordersData) ? ordersData.length : 0;
@@ -64,7 +57,7 @@ const cartCount = useCartCount()
onSuccess: () => {
router.push(`/${locale}`);
router.refresh();
}
},
});
};
@@ -100,50 +93,11 @@ const cartCount = useCartCount()
cartCount,
cartLoading,
t,
]
],
);
return (
<div className="hidden items-center gap-1 lg:flex">
{/* Profile/Login Button with Dropdown */}
{/* {authLoading ? (
<div className="h-10 w-24 animate-pulse bg-gray-200 rounded" />
) : isAuthenticated ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="flex-col cursor-pointer gap-0.5 h-auto px-2 py-2"
>
<ProfileIcon />
<span className="text-xs text-gray-700">{t("profile")}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => router.push(`/${locale}/me`)}>
<User className="mr-2 h-4 w-4" />
{t("profile")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleLogout} disabled={isLoggingOut}>
<LogOut className="mr-2 h-4 w-4" />
{isLoggingOut ? t("logging_out") : t("common.logout")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : (
<Button
variant="ghost"
size="sm"
className="flex-col cursor-pointer gap-0.5 h-auto px-2 py-2"
onClick={onAuthClick}
>
<ProfileIcon />
<span className="text-xs text-gray-700">{t("common.login")}</span>
</Button>
)} */}
{/* Other Action Buttons */}
{buttons.map((button, index) => (
<ActionButton key={index} {...button} />
))}
@@ -163,25 +117,28 @@ function ActionButton({
<Button
variant="ghost"
size="sm"
className="relative flex-col gap-0.5 h-auto px-2 py-2"
className="relative flex-col gap-1 h-auto px-3 py-2.5 hover:bg-gray-100 transition-all duration-200 group"
onClick={onClick}
>
<div className="relative">
<div className="transition-transform duration-200 group-hover:scale-110">
{icon}
</div>
{badgeCount !== undefined && badgeCount > 0 && (
<Badge
variant="destructive"
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
>
<Badge className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px] font-normal bg-gray-900 hover:bg-gray-900 text-white border border-white shadow-sm">
{isLoading ? (
<Skeleton className="h-3 w-3 rounded-full" />
<Skeleton className="h-3 w-3 " />
) : badgeCount > 99 ? (
"99+"
) : (
badgeCount
)}
</Badge>
)}
</div>
<span className="text-xs text-gray-700">{label}</span>
<span className="text-xs text-gray-700 group-hover:text-gray-900 transition-colors">
{label}
</span>
</Button>
);

View File

@@ -5,6 +5,7 @@ import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useCategories } from "@/lib/hooks";
import { Skeleton } from "@/components/ui/skeleton";
import { ChevronRight } from "lucide-react";
interface CategoryMenuProps {
isOpen: boolean;
@@ -16,25 +17,21 @@ export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
const { data: categories, isLoading } = useCategories();
const menuRef = useRef<HTMLDivElement>(null);
// Click outside to close
useEffect(() => {
if (!isOpen) return;
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (target.closest("[data-catalog-trigger]")) {
return;
}
if (menuRef.current && !menuRef.current.contains(target)) {
onClose();
}
};
// Add listener after a small delay to prevent immediate closing
const timeoutId = setTimeout(() => {
document.addEventListener("mousedown", handleClickOutside);
}, 100);
@@ -45,7 +42,6 @@ export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
};
}, [isOpen, onClose]);
// ESC key to close
useEffect(() => {
if (!isOpen) return;
@@ -67,20 +63,25 @@ export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
return (
<>
<div className="fixed inset-0 bg-black/20 z-30" onClick={onClose} />
{/* Overlay */}
<div
className="fixed inset-0 bg-black/30 backdrop-blur-sm z-30 animate-fade-in"
onClick={onClose}
/>
{/* Menu */}
<div
ref={menuRef}
className="fixed left-0 right-0 top-16 z-40 bg-white border-b rounded-b-lg shadow-lg max-w-[1504px] mx-auto"
className="fixed left-0 right-0 top-16 z-40 bg-white border-b border-gray-200 rounded-b-lg shadow-2xl max-w-[1600px] mx-auto animate-slide-up"
>
<div className="mx-auto px-4">
<div className="mx-auto px-6">
<div className="flex">
<CategoryList
categories={categoryList}
isLoading={isLoading}
onCategoryHover={setHoveredCategory}
onCategoryClick={onClose}
hoveredIndex={hoveredCategory}
/>
{activeCategory?.children && (
@@ -101,6 +102,7 @@ interface CategoryListProps {
isLoading: boolean;
onCategoryHover: (index: number) => void;
onCategoryClick: () => void;
hoveredIndex: number | null;
}
function CategoryList({
@@ -108,13 +110,16 @@ function CategoryList({
isLoading,
onCategoryHover,
onCategoryClick,
hoveredIndex,
}: CategoryListProps) {
return (
<div className="w-[280px] border-r">
<div className="max-h-[calc(100vh-4rem)] overflow-y-auto py-2">
<div className="w-[300px] border-r border-gray-200">
<div className="max-h-[calc(100vh-5rem)] overflow-y-auto py-3">
{isLoading
? [1, 2, 3, 4, 5].map((i) => (
<Skeleton key={i} className="h-10 mx-4 my-2 rounded" />
? Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="mx-4 my-2">
<Skeleton className="h-12 rounded-lg" />
</div>
))
: categories.map((category, index) => (
<Link
@@ -122,12 +127,31 @@ function CategoryList({
href={`/category/${category.slug}?category_id=${category.id}`}
onClick={onCategoryClick}
onMouseEnter={() => onCategoryHover(index)}
className="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-100 hover:text-primary transition-colors"
className={`flex items-center justify-between gap-3 mx-2 px-4 py-3.5 rounded-lg transition-all duration-200 group ${
hoveredIndex === index
? "bg-gray-900 text-white shadow-md"
: "hover:bg-gray-100 text-gray-900"
}`}
>
<div className="flex items-center gap-3">
{category.icon_class && (
<i className={`${category.icon_class} text-xl`} />
<i
className={`${category.icon_class} text-xl ${
hoveredIndex === index ? "text-white" : "text-gray-700"
}`}
/>
)}
<span className="font-medium">{category.name}</span>
</div>
{category.children && category.children.length > 0 && (
<ChevronRight
className={`h-4 w-4 transition-all duration-200 ${
hoveredIndex === index
? "text-white translate-x-0.5"
: "text-gray-400 group-hover:text-gray-700"
}`}
/>
)}
<span>{category.name}</span>
</Link>
))}
</div>
@@ -145,17 +169,24 @@ function SubcategoryList({
onSubcategoryClick,
}: SubcategoryListProps) {
return (
<div className="flex-1 p-6">
<h3 className="text-xl font-semibold mb-4">{category.name}</h3>
<div className="grid grid-cols-3 gap-4">
<div className="flex-1 p-8 animate-fade-in">
<div className="mb-6">
<h3 className="text-2xl font-bold text-gray-900 mb-2">
{category.name}
</h3>
<div className="h-1 w-32 bg-gray-900 rounded-full" />
</div>
<div className="grid grid-cols-3 gap-x-6 gap-y-3">
{category.children?.map((subCategory: any) => (
<Link
key={subCategory.id}
href={`/category/${subCategory.slug}?category_id=${subCategory.id}`}
onClick={onSubcategoryClick}
className="text-gray-600 hover:text-black text-sm py-1 hover:underline"
className="text-gray-700 hover:text-gray-900 text-sm py-2 px-3 hover:bg-gray-50 transition-all duration-200 font-medium group flex items-center gap-2"
>
{subCategory.name}
<span className="flex-1">{subCategory.name}</span>
<ChevronRight className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-all duration-200 -translate-x-1 group-hover:translate-x-0" />
</Link>
))}
</div>

View File

@@ -43,17 +43,21 @@ export default function LanguageSelector() {
return (
<Select value={locale} onValueChange={handleLanguageChange}>
<SelectTrigger className="w-[70px] md:h-10! flex items-center justify-center rounded-lg border-gray-300">
<SelectTrigger className="w-[70px] h-10! flex items-center justify-center border-gray-200 hover:border-gray-900 hover:bg-gray-50 transition-all duration-200 shadow-sm">
<SelectValue>
<FlagIcon locale={locale} />
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectContent className=" border-gray-200 shadow-lg">
{LANGUAGES.map((language) => (
<SelectItem key={language.code} value={language.code}>
<div className="flex items-center gap-2">
<SelectItem
key={language.code}
value={language.code}
className="rounded-lg cursor-pointer hover:bg-gray-100 transition-colors"
>
<div className="flex items-center gap-3">
<FlagIcon locale={language.code} />
<span>{language.name}</span>
<span className="font-medium">{language.name}</span>
</div>
</SelectItem>
))}
@@ -68,12 +72,12 @@ function FlagIcon({ locale }: { locale: string }) {
if (!language) return null;
return (
<div className="relative h-5 w-7">
<div className="relative h-5 w-7 overflow-hidden shadow-sm">
<Image
src={language.flag || "/placeholder.svg"}
alt={language.name}
fill
className="object-cover rounded"
className="object-cover"
/>
</div>
);

View File

@@ -87,53 +87,66 @@ export default function SearchBar({
if (!showResults || !data?.data) return null;
return (
<div className="absolute top-full left-0 right-0 mt-2 bg-white border rounded-xl shadow-lg max-h-[400px] overflow-y-auto z-50">
{data.data.map((product) => (
<div className="absolute top-full left-0 right-0 mt-2 bg-white border border-gray-200 rounded-lg shadow-2xl max-h-[500px] overflow-y-auto z-50 animate-slide-up">
<div className="p-2">
{data.data.map((product, index) => (
<button
key={product.id}
onClick={() => handleProductClick(product.id)}
className="w-full cursor-pointer flex items-center gap-3 p-3 hover:bg-gray-50 transition-colors border-b last:border-b-0"
className={`w-full cursor-pointer flex items-center gap-4 p-3 rounded-lg hover:bg-gray-50 transition-all duration-200 group ${
index !== data.data.length - 1 ? "border-b border-gray-100" : ""
}`}
>
<div className="relative w-16 h-16 shrink-0">
<div className="relative w-20 h-20 shrink-0 rounded-lg overflow-hidden bg-gray-50 border border-gray-100">
<Image
src={product.thumbnail}
alt={product.name}
fill
className="object-cover rounded-lg"
className="object-cover group-hover:scale-105 transition-transform duration-200"
/>
</div>
<div className="flex-1 text-left">
<p className="font-medium text-sm line-clamp-2">{product.name}</p>
<p className="text-sm text-gray-600 mt-1">
<div className="flex-1 text-left min-w-0">
<p className="font-semibold text-sm line-clamp-2 text-gray-900 group-hover:text-gray-700 transition-colors mb-1">
{product.name}
</p>
<p className="text-base font-bold text-gray-900 mb-1">
{product.price_amount} TMT
</p>
<p className="text-xs text-gray-500">{product.brand.name}</p>
<p className="text-xs text-gray-500 font-medium">
{product.brand.name}
</p>
</div>
</button>
))}
</div>
</div>
);
};
if (isMobile) {
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="top-4 translate-y-0">
<DialogContent className="top-4 translate-y-0 rounded-lg border-gray-200">
<DialogHeader>
<DialogTitle>{searchPlaceholder}</DialogTitle>
<DialogTitle className="text-xl font-bold">
{searchPlaceholder}
</DialogTitle>
</DialogHeader>
<div className="relative" ref={searchRef}>
<div className="relative">
<Input
type="text"
placeholder={searchPlaceholder}
value={searchValue}
onChange={(e) => handleSearch(e.target.value)}
className="h-10 rounded-xl focus:border-[#005bff] focus-visible:border-[#005bff] focus-visible:ring-0 active:border-[#005bff]"
className="h-12 rounded-lg pl-12 pr-10 border-gray-200 focus:border-gray-900 focus-visible:border-gray-900 focus-visible:ring-0 transition-colors"
autoFocus
/>
<Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
{isLoading && (
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-gray-400" />
<Loader2 className="absolute right-4 top-1/2 -translate-y-1/2 h-5 w-5 animate-spin text-gray-400" />
)}
</div>
<SearchResults />
</div>
</DialogContent>
@@ -142,22 +155,28 @@ export default function SearchBar({
}
return (
<div className={`bg-[#005bff] rounded-xl flex items-center relative ${className}`} ref={searchRef}>
<div
className={`bg-gray-900 rounded-lg flex items-center relative shadow-sm hover:shadow-md transition-shadow duration-200 ${className}`}
ref={searchRef}
>
<div className="w-full relative">
<div className="relative">
<Input
type="text"
placeholder={searchPlaceholder}
value={searchValue}
onChange={(e) => handleSearch(e.target.value)}
className="border-[#005bff] w-full rounded-xl border-2 focus-visible:ring-0 bg-white px-2"
className="border w-full rounded-lg h-11 border-gray-900 bg-white pl-12 pr-4 focus-visible:ring-2 focus-visible:ring-gray-300 transition-all"
/>
<Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400 pointer-events-none" />
</div>
{isLoading && (
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-gray-400" />
<Loader2 className="absolute right-4 top-1/2 -translate-y-1/2 h-5 w-5 animate-spin text-gray-400" />
)}
</div>
<Button
size="icon"
className="h-auto hover:bg-[#005bff] cursor-pointer bg-transparent flex items-center mr-1.5 text-white"
className="h-11 w-11 hover:bg-gray-800 cursor-pointer bg-transparent flex items-center mr-1 text-white rounded-lg transition-colors"
>
<SearchIcon />
</Button>

View File

@@ -20,7 +20,6 @@ interface CartItemCardProps {
onUpdate?: () => void;
}
// Session Storage Key
const PENDING_CART_UPDATES_KEY = "pendingCartUpdates";
interface PendingUpdate {
@@ -32,39 +31,33 @@ interface PendingUpdate {
export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
const t = useTranslations();
// Local UI State (Instant feedback)
const [localQuantity, setLocalQuantity] = useState(item.quantity);
// Sync State
const [isSyncing, setIsSyncing] = useState(false);
const [syncError, setSyncError] = useState(false);
// Stock limit modal
const [showStockModal, setShowStockModal] = useState(false);
// Refs
const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const isRequestInFlightRef = useRef(false);
const pendingQuantityRef = useRef<number | null>(null);
const retryCountRef = useRef(0);
const retryTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const isInitializedRef = useRef(false);
// Function refs to solve circular dependency
const syncToServerRef = useRef<((quantity: number) => void) | null>(null);
const retrySyncRef = useRef<((quantity: number) => void) | null>(null);
const { mutate: updateQuantity } = useUpdateCartItemQuantity();
const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart();
// Get available stock
const availableStock = item.product.stock || 0;
// Initialize from server state
useEffect(() => {
setLocalQuantity(item.quantity);
if (!isInitializedRef.current) {
isInitializedRef.current = true;
}
}, [item.quantity]);
// Save to sessionStorage
const savePendingUpdate = useCallback(
(quantity: number) => {
try {
@@ -90,7 +83,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
[item.product_id],
);
// Remove from sessionStorage
const clearPendingUpdate = useCallback(() => {
try {
const stored = sessionStorage.getItem(PENDING_CART_UPDATES_KEY);
@@ -112,7 +104,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
}
}, [item.product_id]);
// Exponential backoff retry
const retrySync = useCallback((quantity: number) => {
const maxRetries = 4;
const retryCount = retryCountRef.current;
@@ -123,7 +114,7 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
return;
}
const delay = Math.min(1000 * Math.pow(2, retryCount), 16000); // Max 16s
const delay = Math.min(1000 * Math.pow(2, retryCount), 16000);
retryCountRef.current++;
retryTimerRef.current = setTimeout(() => {
@@ -131,19 +122,15 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
}, delay);
}, []);
// Update ref
retrySyncRef.current = retrySync;
// Sync to server
const syncToServer = useCallback(
(quantity: number) => {
// If already syncing, queue this update
if (isRequestInFlightRef.current) {
pendingQuantityRef.current = quantity;
return;
}
// Mark as syncing
isRequestInFlightRef.current = true;
setIsSyncing(true);
setSyncError(false);
@@ -157,7 +144,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
clearPendingUpdate();
onUpdate?.();
// Process queued update if any
if (pendingQuantityRef.current !== null) {
const nextQuantity = pendingQuantityRef.current;
pendingQuantityRef.current = null;
@@ -181,7 +167,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
clearPendingUpdate();
onUpdate?.();
// Process queued update if any
if (pendingQuantityRef.current !== null) {
const nextQuantity = pendingQuantityRef.current;
pendingQuantityRef.current = null;
@@ -192,7 +177,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
console.error("Update failed:", error);
isRequestInFlightRef.current = false;
// Rollback on error after retries exhausted
if (retryCountRef.current >= 3) {
setLocalQuantity(item.quantity);
clearPendingUpdate();
@@ -214,55 +198,29 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
],
);
// Update ref
syncToServerRef.current = syncToServer;
// Load pending updates from sessionStorage on mount
useEffect(() => {
const loadPendingUpdates = () => {
try {
const stored = sessionStorage.getItem(PENDING_CART_UPDATES_KEY);
if (stored) {
const pending: Record<number, PendingUpdate> = JSON.parse(stored);
const productPending = pending[item.product_id];
if (productPending && productPending.quantity !== item.quantity) {
// Apply pending update
setLocalQuantity(productPending.quantity);
pendingQuantityRef.current = productPending.quantity;
retryCountRef.current = productPending.retryCount;
// Trigger sync after a short delay
setTimeout(
() => syncToServerRef.current?.(productPending.quantity),
500,
);
if (!isInitializedRef.current) {
return;
}
}
} catch (error) {
console.error("Failed to load pending updates:", error);
}
};
loadPendingUpdates();
}, [item.product_id, item.quantity]);
// Debounced sync
useEffect(() => {
// Clear existing timers
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
// If local quantity matches server, no sync needed
if (localQuantity === item.quantity) {
return;
}
// Save to sessionStorage immediately
if (localQuantity <= 0 && item.quantity > 0) {
// Delete operation
} else if (localQuantity <= 0) {
return;
}
savePendingUpdate(localQuantity);
// Debounce the API call
debounceTimerRef.current = setTimeout(() => {
syncToServerRef.current?.(localQuantity);
}, 800);
@@ -274,7 +232,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
};
}, [localQuantity, item.quantity, savePendingUpdate]);
// Cleanup
useEffect(() => {
return () => {
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
@@ -286,13 +243,11 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
e.preventDefault();
e.stopPropagation();
// Check stock limit
if (localQuantity >= availableStock) {
setShowStockModal(true);
return;
}
// Optimistic update (instant UI feedback)
setLocalQuantity((prev) => prev + 1);
};
@@ -305,7 +260,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
return;
}
// Optimistic update (instant UI feedback)
setLocalQuantity((prev) => prev - 1);
};
@@ -323,49 +277,70 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
return (
<>
<Card className="p-4 shadow-none border">
<div className="flex flex-col sm:flex-row gap-4">
<Card className="p-6 shadow-sm border border-gray-200 rounded-2xl hover:shadow-md transition-shadow duration-200">
<div className="flex flex-col sm:flex-row gap-6">
{/* Product Image & Info */}
<div className="flex gap-4 flex-1">
<div className="relative w-[88px] h-[117px] rounded-xl border overflow-hidden shrink-0">
<div className="relative w-[100px] h-[133px] rounded-xl border border-gray-200 overflow-hidden shrink-0 bg-gray-50">
<Image
src={getImageSrc()}
alt={item.product.name}
fill
className="object-contain"
className="object-contain p-2"
/>
</div>
<div className="flex flex-col gap-2">
<h3 className="font-semibold text-base">{item.product.name}</h3>
<h3 className="font-bold text-base text-gray-900 line-clamp-2">
{item.product.name}
</h3>
{/* <p className="text-sm text-gray-500 font-medium">
{item.seller?.name || "Store"}
</p> */}
{/* {availableStock <= 5 && (
<div className="flex items-center gap-1.5">
<div className="h-2 w-2 rounded-full bg-amber-500 animate-pulse" />
<p className="text-xs text-amber-600 font-semibold">
{t("only_left", { count: availableStock })}
</p>
</div>
)} */}
<Button
variant="ghost"
size="sm"
onClick={handleDelete}
disabled={isRemoving}
className="w-fit cursor-pointer p-0 h-auto hover:bg-transparent hover:text-red-500"
className="w-fit cursor-pointer p-0 h-auto hover:bg-transparent text-gray-600 hover:text-red-500 transition-colors group"
>
<Trash2 className="h-5 w-5" />
<Trash2 className="h-5 w-5 group-hover:scale-110 transition-transform" />
</Button>
</div>
</div>
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
<div className="space-y-1">
<p className="text-sm font-semibold">
{/* Price & Quantity */}
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-6 justify-between">
<div className="space-y-2">
<p className="text-sm font-medium text-gray-600">
{t("unit_price")}{" "}
<span className="text-primary">{item.price_formatted}</span>
<span className="text-gray-900 font-bold">
{item.price_formatted}
</span>
</p>
{item.discount_formatted &&
item.discount_formatted !== "0 TMT" && (
<p className="text-sm font-semibold">
<p className="text-sm font-medium text-emerald-600">
{t("discount")} {item.discount_formatted}
</p>
)}
<div className="flex items-center gap-2">
<span className="text-sm font-semibold">
<span className="text-sm font-medium text-gray-600">
{t("total_price")}
</span>
<span className="bg-green-500 text-white px-3 py-1 rounded-lg font-semibold text-base">
<span className="bg-emerald-500 text-white px-4 py-1.5 rounded-[10px] font-bold text-base shadow-sm">
{(
parseFloat(item.product.price_amount || "0") * localQuantity
).toFixed(2)}{" "}
@@ -374,23 +349,31 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
</div>
</div>
<div className="flex items-center gap-2">
{/* Quantity Controls */}
<div className="flex items-center gap-3">
<Button
variant="outline"
size="icon"
onClick={handleQuantityDecrease}
className={` cursor-pointer rounded-lg bg-blue-50 ${
isSyncing ? "opacity-70" : ""
disabled={isSyncing}
className={`cursor-pointer rounded-[10px] h-10 w-10 border-2 border-gray-200 hover:border-gray-900 hover:bg-gray-50 transition-all duration-200 ${
isSyncing ? "opacity-50" : ""
}`}
>
<Minus className="h-4 w-4" />
<Minus className="h-4 w-4 text-gray-700" />
</Button>
<div className="w-12 text-center font-semibold relative">
{localQuantity}
<div className="min-w-[48px] text-center font-bold text-lg relative">
{isSyncing ? (
<div className="flex items-center justify-center">
<div className="w-4 h-4 border-2 border-gray-300 border-t-gray-900 rounded-full animate-spin" />
</div>
) : (
localQuantity
)}
{syncError && (
<span
className="absolute -top-1 -right-3 h-2 w-2 bg-red-500 rounded-full"
className="absolute -top-1 -right-2 h-2.5 w-2.5 bg-red-500 rounded-full border-2 border-white shadow-sm"
title="Sync error"
/>
)}
@@ -400,16 +383,16 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
variant="outline"
size="icon"
onClick={handleQuantityIncrease}
// disabled={localQuantity >= availableStock}
className={`rounded-lg cursor-pointer bg-blue-50 ${
isSyncing ? "opacity-70" : ""
} ${
disabled={isSyncing || localQuantity >= availableStock}
className={`rounded-[10px] h-10 w-10 cursor-pointer border-2 transition-all duration-200 ${
localQuantity >= availableStock
? "opacity-50 cursor-not-allowed"
: ""
}`}
? "opacity-30 cursor-not-allowed border-gray-200"
: "border-gray-900 bg-gray-900 hover:bg-gray-800"
} ${isSyncing ? "opacity-50" : ""}`}
>
<Plus className="h-4 w-4 text-[#007AFF]" />
<Plus
className={`h-4 w-4 ${localQuantity >= availableStock ? "text-gray-400" : "text-white"}`}
/>
</Button>
</div>
</div>
@@ -418,27 +401,27 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
{/* Stock Limit Modal */}
<Dialog open={showStockModal} onOpenChange={setShowStockModal}>
<DialogContent className="sm:max-w-md">
<DialogContent className="sm:max-w-md rounded-3xl border-gray-200">
<DialogHeader>
<div className="flex items-center justify-center mb-4">
<div className="rounded-full bg-orange-100 p-3">
<AlertTriangle className="h-6 w-6 text-orange-600" />
<div className="rounded-full bg-amber-100 p-4">
<AlertTriangle className="h-7 w-7 text-amber-600" />
</div>
</div>
<DialogTitle className="text-center text-xl">
<DialogTitle className="text-center text-2xl font-bold text-gray-900">
{t("stock_limit_title")}
</DialogTitle>
<DialogDescription className="text-center text-base pt-2">
<DialogDescription className="text-center text-base pt-3 text-gray-600 leading-relaxed">
{t("stock_limit_message", {
product: item.product.name,
stock: availableStock,
})}
</DialogDescription>
</DialogHeader>
<div className="flex justify-center mt-4">
<div className="flex justify-center mt-6">
<Button
onClick={() => setShowStockModal(false)}
className="w-full rounded-lg cursor-pointer"
className="w-full h-12 rounded-2xl cursor-pointer bg-gray-900 hover:bg-gray-800 font-semibold shadow-md"
>
{t("understood")}
</Button>

View File

@@ -1,52 +1,62 @@
"use client"
import { Truck, Warehouse } from "lucide-react"
import { Card } from "@/components/ui/card"
import { useTranslations } from "next-intl"
import type { DeliveryType } from "@/lib/types/api"
"use client";
import { Truck, Warehouse } from "lucide-react";
import { Card } from "@/components/ui/card";
import { useTranslations } from "next-intl";
import type { DeliveryType } from "@/lib/types/api";
interface DeliveryTypeSelectorProps {
selectedType: DeliveryType
onSelect: (type: DeliveryType) => void
selectedType: DeliveryType;
onSelect: (type: DeliveryType) => void;
}
export default function DeliveryTypeSelector({
selectedType,
onSelect,
}: DeliveryTypeSelectorProps) {
const t = useTranslations()
const t = useTranslations();
const deliveryOptions: {
type: DeliveryType
label: string
icon: typeof Truck
type: DeliveryType;
label: string;
icon: typeof Truck;
}[] = [
{ type: "SELECTED_DELIVERY", label: t("delivery"), icon: Truck },
{ type: "PICK_UP", label: t("pickup"), icon: Warehouse },
]
];
return (
<div className="mb-6">
<h3 className="text-lg font-semibold mb-3">{t("delivery_type")}</h3>
<div className="flex gap-2">
<div className="mb-8">
<h3 className="text-lg font-bold mb-4 text-gray-900">
{t("delivery_type")}
</h3>
<div className="flex gap-3">
{deliveryOptions.map(({ type, label, icon: Icon }) => (
<Card
key={type}
className={`flex-1 cursor-pointer transition-all hover:shadow-md ${
className={`flex-1 cursor-pointer transition-all duration-200 hover:shadow-md rounded-lg ${
selectedType === type
? "border-2 border-[#005bff] bg-blue-50"
: "border-2 border-gray-200"
? "border-2 border-gray-900 bg-gray-50 shadow-md"
: "border-2 border-gray-200 hover:border-gray-400"
}`}
onClick={() => onSelect(type)}
>
<div className="flex flex-col items-center justify-center p-4 gap-2">
<div className="flex flex-col items-center justify-center p-5 gap-3">
<div
className={`h-12 w-12 rounded-lg flex items-center justify-center transition-colors ${
selectedType === type ? "bg-gray-900" : "bg-gray-100"
}`}
>
<Icon
className={`h-8 w-8 ${
selectedType === type ? "text-[#005bff]" : "text-gray-600"
className={`h-6 w-6 transition-colors ${
selectedType === type ? "text-white" : "text-gray-700"
}`}
/>
<span className={`text-xs font-medium ${
selectedType === type ? "text-[#005bff]" : "text-gray-700"
}`}>
</div>
<span
className={`text-sm font-semibold transition-colors ${
selectedType === type ? "text-gray-900" : "text-gray-600"
}`}
>
{label}
</span>
</div>
@@ -54,5 +64,5 @@ export default function DeliveryTypeSelector({
))}
</div>
</div>
)
);
}

View File

@@ -6,22 +6,26 @@ import { useRouter } from "next/navigation";
export default function EmptyCart() {
const t = useTranslations();
const router = useRouter();
return (
<div className="flex min-h-[60vh] items-center justify-center px-4">
<div className="w-full max-w-md rounded-2xl bg-linear-to-br from-blue-50 to-white p-8 text-center shadow-lg">
<div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-blue-100">
<ShoppingCart className="h-10 w-10 text-blue-600" />
<div className="w-full max-w-md rounded-3xl bg-gradient-to-br from-gray-50 to-white p-12 text-center shadow-xl border border-gray-100">
<div className="mx-auto mb-8 flex h-24 w-24 items-center justify-center rounded-full bg-gray-100">
<ShoppingCart className="h-12 w-12 text-gray-700" />
</div>
<h2 className="mb-2 text-2xl font-semibold text-gray-900">
<h2 className="mb-3 text-3xl font-bold text-gray-900">
{t("cart_empty")}
</h2>
<p className="mb-6 text-sm text-gray-500">
<p className="mb-8 text-base text-gray-600 leading-relaxed">
{t("cart_empty_message")}
</p>
<Button onClick={()=>router.push("/")} className="w-full cursor-pointer rounded-xl bg-blue-600 px-6 py-3 text-sm font-medium text-white transition hover:bg-blue-700 active:scale-95">
<Button
onClick={() => router.push("/")}
className="w-full cursor-pointer rounded-2xl bg-gradient-to-r from-gray-900 to-gray-800 hover:from-gray-800 hover:to-gray-700 px-8 py-6 text-base font-bold text-white shadow-lg hover:shadow-xl transition-all duration-300 active:scale-95"
>
{t("start_shopping")}
</Button>
</div>

View File

@@ -111,7 +111,6 @@ export default function OrderSummary({
}
const digitsOnly = input.substring(prefix.length).replace(/\D/g, "");
const limitedDigits = digitsOnly.substring(0, 8);
let formattedPhone = prefix;
@@ -134,15 +133,15 @@ export default function OrderSummary({
};
return (
<Card className="w-full md:w-[380px] p-4 md:p-6 rounded-xl h-fit sticky top-20">
<Card className="w-full md:w-[420px] p-8 rounded-lg border border-gray-200 shadow-lg h-fit sticky top-20">
{/* Customer Information */}
<div className="mb-6">
<h3 className="text-lg font-semibold mb-3">
<div className="mb-8">
<h3 className="text-xl font-bold mb-5 text-gray-900">
{t("customer_information")}
</h3>
<div className="space-y-5">
<div>
<Label className="text-sm font-medium mb-2 block">
<Label className="text-sm font-semibold mb-2 block text-gray-700">
{t("name")}
</Label>
<Input
@@ -150,16 +149,21 @@ export default function OrderSummary({
value={name}
onChange={(e) => onNameChange(e.target.value)}
placeholder={t("name")}
className={`rounded-lg ${
showValidation && name.trim() === "" ? "border-red-500" : ""
className={`rounded-[10px] h-12 border-2 transition-colors ${
showValidation && name.trim() === ""
? "border-red-500"
: "border-gray-200 focus:border-gray-900"
}`}
/>
{showValidation && name.trim() === "" && (
<p className="text-xs text-red-500 mt-1">{t("requiredField")}</p>
<p className="text-xs text-red-500 mt-2 font-medium">
{t("requiredField")}
</p>
)}
</div>
<div>
<Label className="text-sm font-medium mb-2 block">
<Label className="text-sm font-semibold mb-2 block text-gray-700">
{t("last_name")}
</Label>
<Input
@@ -167,16 +171,21 @@ export default function OrderSummary({
value={lastName}
onChange={(e) => onLastNameChange(e.target.value)}
placeholder={t("last_name")}
className={`rounded-lg ${
showValidation && lastName.trim() === "" ? "border-red-500" : ""
className={`rounded-[10px] h-12 border-2 transition-colors ${
showValidation && lastName.trim() === ""
? "border-red-500"
: "border-gray-200 focus:border-gray-900"
}`}
/>
{showValidation && lastName.trim() === "" && (
<p className="text-xs text-red-500 mt-1">{t("requiredField")}</p>
<p className="text-xs text-red-500 mt-2 font-medium">
{t("requiredField")}
</p>
)}
</div>
<div>
<Label className="text-sm font-medium mb-2 block">
<Label className="text-sm font-semibold mb-2 block text-gray-700">
{t("phone")}
</Label>
<Input
@@ -184,20 +193,24 @@ export default function OrderSummary({
value={phone}
onChange={handlePhoneChange}
placeholder="+993 61 097651"
className={`rounded-lg ${
showValidation && !isPhoneValid ? "border-red-500" : ""
className={`rounded-[10px] h-12 border-2 transition-colors ${
showValidation && !isPhoneValid
? "border-red-500"
: "border-gray-200 focus:border-gray-900"
}`}
/>
{showValidation && !isPhoneValid && (
<p className="text-xs text-red-500 mt-1">{t("requiredField")}</p>
<p className="text-xs text-red-500 mt-2 font-medium">
{t("requiredField")}
</p>
)}
</div>
</div>
</div>
{/* Region Selection */}
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">
<div className="mb-8">
<Label className="text-xl font-bold mb-4 block text-gray-900">
{t("choose_region")}
</Label>
<RadioGroup
@@ -209,19 +222,19 @@ export default function OrderSummary({
className="flex flex-wrap gap-4"
>
{availableRegions.map((regionCode) => (
<div key={regionCode} className="flex items-center space-x-2">
<div key={regionCode} className="flex items-center space-x-3">
<RadioGroupItem
value={regionCode}
id={`region-${regionCode}`}
className={`border-2 ${
className={`border-2 h-5 w-5 ${
showValidation && !selectedRegion
? "border-red-500"
: "border-gray-400"
} data-[state=checked]:border-[#005bff] data-[state=checked]:bg-white`}
} data-[state=checked]:border-gray-900 data-[state=checked]:bg-gray-900`}
/>
<Label
htmlFor={`region-${regionCode}`}
className="cursor-pointer uppercase"
className="cursor-pointer uppercase font-semibold text-gray-700 hover:text-gray-900 transition-colors"
>
{regionCode}
</Label>
@@ -229,14 +242,16 @@ export default function OrderSummary({
))}
</RadioGroup>
{showValidation && !selectedRegion && (
<p className="text-xs text-red-500 mt-1">{t("requiredField")}</p>
<p className="text-xs text-red-500 mt-3 font-medium">
{t("requiredField")}
</p>
)}
</div>
{/* Province Selection */}
{selectedRegion && provincesForSelectedRegion.length > 0 && (
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">
<div className="mb-8">
<Label className="text-xl font-bold mb-4 block text-gray-900">
{t("choose_address")}
</Label>
<Select
@@ -244,44 +259,54 @@ export default function OrderSummary({
onValueChange={(value) => onProvinceChange(parseInt(value))}
>
<SelectTrigger
className={`rounded-lg w-full ${
showValidation && !selectedProvince ? "border-red-500" : ""
className={`rounded-[10px] h-12 w-full border-2 font-medium ${
showValidation && !selectedProvince
? "border-red-500"
: "border-gray-200 hover:border-gray-900"
}`}
>
<SelectValue placeholder={t("choose_address")} />
</SelectTrigger>
<SelectContent>
<SelectContent className="rounded-lg">
{provincesForSelectedRegion.map((province) => (
<SelectItem key={province.id} value={province.id.toString()}>
<SelectItem
key={province.id}
value={province.id.toString()}
className="rounded-lg"
>
{province.name}
</SelectItem>
))}
</SelectContent>
</Select>
{showValidation && !selectedProvince && (
<p className="text-xs text-red-500 mt-1">{t("requiredField")}</p>
<p className="text-xs text-red-500 mt-3 font-medium">
{t("requiredField")}
</p>
)}
</div>
)}
{/* Note */}
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">{t("note")}</Label>
<div className="mb-8">
<Label className="text-xl font-bold mb-4 block text-gray-900">
{t("note")}
</Label>
<Textarea
value={note}
onChange={(e) => onNoteChange(e.target.value)}
className="rounded-xl resize-none"
className="rounded-[10px] resize-none border-2 border-gray-200 focus:border-gray-900 transition-colors"
rows={3}
placeholder={t("note")}
/>
</div>
{/* Billing */}
<div className="space-y-2 mb-4">
<div className="space-y-3 mb-6">
{order.billing.body.map((item, index) => (
<div
key={index}
className="flex justify-between text-base font-medium"
className="flex justify-between text-base font-semibold text-gray-700"
>
<span>{item.title}:</span>
<span>{item.value}</span>
@@ -289,13 +314,13 @@ export default function OrderSummary({
))}
</div>
<Separator className="my-4" />
<Separator className="my-6 bg-gray-200" />
<div className="flex justify-between items-center mb-6">
<span className="text-lg font-semibold">
<div className="flex justify-between items-center mb-8">
<span className="text-xl font-bold text-gray-900">
{order.billing.footer.title}:
</span>
<span className="text-lg font-bold text-green-600">
<span className="text-2xl font-bold text-emerald-600">
{order.billing.footer.value}
</span>
</div>
@@ -303,10 +328,17 @@ export default function OrderSummary({
<Button
onClick={handleCompleteOrderClick}
disabled={isLoading}
className="w-full rounded-lg cursor-pointer bg-[#005bff] hover:bg-[#004dcc] h-12 text-lg font-bold disabled:opacity-50"
className="w-full rounded-[10px] cursor-pointer bg-gradient-to-r from-gray-900 to-gray-800 hover:from-gray-800 hover:to-gray-700 h-14 text-lg font-bold disabled:opacity-50 shadow-md hover:shadow-lg transition-all duration-300"
size="lg"
>
{isLoading ? `${t("order")}...` : t("order")}
{isLoading ? (
<div className="flex items-center gap-2">
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
<span>{t("order")}...</span>
</div>
) : (
t("order")
)}
</Button>
</Card>
);

View File

@@ -151,7 +151,7 @@ export function useAddToCart() {
pendingUpdates.forEach((pendingQty, pendingId) => {
const idx = updated.data.findIndex(
(item: any) => item.product?.id === pendingId
(item: any) => item.product?.id === pendingId,
);
if (idx !== -1) {
updated.data[idx] = {
@@ -162,7 +162,7 @@ export function useAddToCart() {
});
const existingItem = updated.data.find(
(item: any) => item.product?.id === productId
(item: any) => item.product?.id === productId,
);
if (existingItem) {
@@ -172,7 +172,7 @@ export function useAddToCart() {
...item,
product_quantity: item.product_quantity + quantity,
}
: item
: item,
);
} else {
updated.data = [
@@ -185,7 +185,7 @@ export function useAddToCart() {
}
const finalItem = updated.data.find(
(item: any) => item.product?.id === productId
(item: any) => item.product?.id === productId,
);
if (finalItem) {
pendingUpdates.set(productId, finalItem.product_quantity);
@@ -261,7 +261,7 @@ export function useRemoveFromCart() {
pendingUpdates.forEach((pendingQty, pendingId) => {
if (pendingId !== productId) {
const idx = updated.data.findIndex(
(item: any) => item.product?.id === pendingId
(item: any) => item.product?.id === pendingId,
);
if (idx !== -1) {
updated.data[idx] = {
@@ -273,7 +273,7 @@ export function useRemoveFromCart() {
});
updated.data = updated.data.filter(
(item: any) => item.product?.id !== productId
(item: any) => item.product?.id !== productId,
);
pendingUpdates.delete(productId);
@@ -413,7 +413,7 @@ export function useUpdateCartItemQuantity() {
pendingUpdates.forEach((pendingQty, pendingId) => {
const idx = updated.data.findIndex(
(item: any) => item.product?.id === pendingId
(item: any) => item.product?.id === pendingId,
);
if (idx !== -1) {
updated.data[idx] = {
@@ -426,7 +426,7 @@ export function useUpdateCartItemQuantity() {
updated.data = updated.data.map((item: any) =>
item.product?.id === productId
? { ...item, product_quantity: quantity }
: item
: item,
);
pendingUpdates.set(productId, quantity);
@@ -470,14 +470,16 @@ export function useCreateOrder() {
delivery_time?: string;
delivery_at?: string;
region: string;
note?: string;
notes?: string;
}) => {
const response = await apiClient.post("/orders", payload);
return response.data;
},
onSuccess: (data) => {
if (data && data.payment_url) {
window.open(data.payment_url, '_blank')?.focus();
// Handle payment URL - check both data.payment_url and data.data.payment_url
const paymentUrl = data?.data?.payment_url || data?.payment_url;
if (paymentUrl) {
window.open(paymentUrl, "_blank")?.focus();
}
pendingUpdates.clear();
@@ -491,7 +493,7 @@ export function useCreateOrder() {
onError: (error: any) => {
console.error(
"Create order error:",
error.response?.data?.message || error.message
error.response?.data?.message || error.message,
);
},
});
@@ -502,7 +504,7 @@ export function useCartCount() {
return (
data?.data?.reduce(
(sum: number, item: any) => sum + (item.product_quantity || 0),
0
0,
) || 0
);
}

View File

@@ -2,7 +2,14 @@
import { useState, useEffect, useRef, useCallback, MouseEvent } from "react";
import { useRouter } from "next/navigation";
import { Heart, ShoppingCart, Plus, Minus, AlertTriangle } from "lucide-react";
import {
Heart,
ShoppingCart,
Plus,
Minus,
AlertTriangle,
Zap,
} from "lucide-react";
import { toast } from "sonner";
import {
Carousel,
@@ -53,9 +60,9 @@ export default function ProductCard({
struct_price_text,
images,
labels = [],
price_color = "#005bff",
height = 360,
width = 280,
price_color = "#0A0A0A",
height = 400,
width = 300,
button = false,
stock,
}: ProductCardProps) {
@@ -73,6 +80,7 @@ export default function ProductCard({
const [localQuantity, setLocalQuantity] = useState(1);
const [isSyncing, setIsSyncing] = useState(false);
const [showStockModal, setShowStockModal] = useState(false);
const [isHovered, setIsHovered] = useState(false);
const autoplayRef = useRef<NodeJS.Timeout | null>(null);
const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
@@ -141,7 +149,7 @@ export default function ProductCard({
setIsSyncing(false);
}
},
[id, updateCartMutation, cartItem, refetchCart]
[id, updateCartMutation, cartItem, refetchCart],
);
useEffect(() => {
@@ -169,13 +177,15 @@ export default function ProductCard({
{
onSuccess: (data) =>
toast.success(
data.wasAdded ? t("added_to_favorites") : t("removed_from_favorites")
data.wasAdded
? t("added_to_favorites")
: t("removed_from_favorites"),
),
onError: () => toast.error("Error. Try again"),
}
},
);
},
[id, isFavorite, toggleFavorite]
[id, isFavorite, toggleFavorite],
);
const handleAddToCart = useCallback(
@@ -205,7 +215,7 @@ export default function ProductCard({
setIsSyncing(false);
}
},
[id, name, localQuantity, availableStock, addToCartMutation]
[id, name, localQuantity, availableStock, addToCartMutation],
);
const handleQuantityChange = useCallback(
@@ -224,13 +234,13 @@ export default function ProductCard({
setLocalQuantity(newQuantity);
},
[localQuantity, availableStock]
[localQuantity, availableStock],
);
const handleCardClick = useCallback((e: MouseEvent<HTMLDivElement>) => {
const handleCardClick = useCallback(
(e: MouseEvent<HTMLDivElement>) => {
const target = e.target as HTMLElement;
// Prevent navigation if clicking on buttons or interactive elements
if (
target.closest("button") ||
target.closest('[data-carousel-control="true"]') ||
@@ -241,10 +251,11 @@ export default function ProductCard({
return;
}
// Programmatic navigation
e.preventDefault();
router.push(`/product/${id}`);
}, [router, id]);
},
[router, id],
);
const handleNavClick = (e: MouseEvent, action: () => void) => {
e.preventDefault();
@@ -256,26 +267,31 @@ export default function ProductCard({
<>
<div
onClick={handleCardClick}
className="flex justify-center cursor-pointer"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className="flex justify-center cursor-pointer group"
>
<Card
className="relative gap-2 border-none shadow-none p-0 w-full overflow-hidden rounded-2xl"
className="relative bg-white border border-gray-100 shadow-sm hover:shadow-xl transition-all duration-300 p-0 w-full overflow-hidden rounded-lg"
style={{ height, maxWidth: width }}
>
<div className="relative w-full h-[260px] group">
{/* Image Section */}
<div className="relative w-full h-[280px] bg-gradient-to-br from-gray-50 to-gray-100 overflow-hidden">
<Carousel
opts={{ align: "start", loop: true, watchDrag: false }}
setApi={setApi}
className="w-full h-full"
>
<CarouselContent className="h-[260px] ml-0">
<CarouselContent className="h-[280px] ml-0">
{images.map((image, idx) => (
<CarouselItem key={idx} className="h-[260px] pl-0">
<div className="h-full flex items-center justify-center">
<CarouselItem key={idx} className="h-[280px] pl-0">
<div className="h-full flex items-center justify-center p-3">
<img
src={image}
alt={`${name} - ${idx + 1}`}
className="max-w-full max-h-full object-contain"
className={`max-w-full max-h-full object-contain transition-transform duration-500 ${
isHovered ? "scale-105" : "scale-100"
}`}
draggable="false"
/>
</div>
@@ -287,42 +303,47 @@ export default function ProductCard({
<>
<CarouselPrevious
data-carousel-control="true"
className="absolute left-2 opacity-0 group-hover:opacity-100 transition-opacity z-20"
className="absolute left-3 opacity-0 group-hover:opacity-100 transition-all duration-300 z-20 h-9 w-9 bg-white/95 hover:bg-white border-0 shadow-lg"
onClick={(e) => handleNavClick(e, () => api?.scrollPrev())}
/>
<CarouselNext
data-carousel-control="true"
className="absolute right-2 opacity-0 group-hover:opacity-100 transition-opacity z-20"
className="absolute right-3 opacity-0 group-hover:opacity-100 transition-all duration-300 z-20 h-9 w-9 bg-white/95 hover:bg-white border-0 shadow-lg"
onClick={(e) => handleNavClick(e, () => api?.scrollNext())}
/>
</>
)}
</Carousel>
{/* Image Dots */}
{hasMultipleImages && (
<div className="absolute bottom-2 left-1/2 -translate-x-1/2 z-10 flex gap-1.5">
<div className="absolute bottom-3 left-1/2 -translate-x-1/2 z-10 flex gap-1.5">
{images.map((_, idx) => (
<button
key={idx}
data-carousel-control="true"
onClick={(e) => handleNavClick(e, () => api?.scrollTo(idx))}
className={`h-1.5 rounded-full cursor-pointer transition-all ${
idx === current ? "w-6 bg-white" : "w-1.5 bg-white/60"
className={`h-1.5 rounded-full transition-all duration-300 ${
idx === current
? "w-8 bg-gray-900"
: "w-1.5 bg-gray-400 hover:bg-gray-600"
}`}
/>
))}
</div>
)}
{/* Labels */}
{labels.length > 0 && (
<div className="absolute top-2 left-2 flex flex-col gap-1 z-10">
<div className="absolute top-3 left-3 flex flex-col gap-2 z-10">
{labels.map((label, idx) => (
<Badge
key={idx}
className="text-white text-[10px] font-bold uppercase rounded-r-md"
style={{ backgroundColor: label.bg_color }}
className="text-white text-xs font-bold px-3 py-1 shadow-md backdrop-blur-sm"
style={{
backgroundColor: label.bg_color,
borderRadius: "12px",
}}
>
{label.text}
</Badge>
@@ -330,61 +351,74 @@ export default function ProductCard({
</div>
)}
{/* Out of Stock Overlay */}
{isOutOfStock && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center z-10">
<Badge variant="secondary" className="text-sm font-bold">
<div className="absolute inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center z-20">
<div className="text-center">
<Badge
variant="secondary"
className="text-sm font-bold px-4 py-2 bg-gray-900 text-white"
>
{t("outOfStock")}
</Badge>
</div>
</div>
)}
</div>
<CardContent className="p-0 space-y-1">
{/* Content Section */}
<CardContent className="p-3 space-y-3">
{/* Product Name */}
<h3 className="text-gray-900 text-base font-semibold leading-tight line-clamp-2 min-h-[2.5rem]">
{name}
</h3>
{/* Price */}
<div className="flex items-baseline gap-2">
<p
className="text-sm mx-2 font-medium"
className="text-2xl font-bold tracking-tight"
style={{ color: price_color }}
>
{struct_price_text}
</p>
<p className="text-black text-sm font-semibold leading-normal truncate mx-2">
{name}
</p>
</CardContent>
<div className="flex">
<button
</div>
<div className="flex gap-2 items-center">
{/* Favorite Button */}
<Button
onClick={handleFavorite}
disabled={isFavoriteToggling || isFavoriteLoading}
className=" cursor-pointer z-10 rounded-full bg-white/80 p-2 hover:bg-white transition-all disabled:opacity-50"
className=" w-9 h-9 rounded-[10px] bg-white/95 backdrop-blur-sm hover:bg-white hover:scale-110 transition-all duration-200 shadow-md disabled:opacity-50"
>
{isFavoriteLoading ? (
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin" />
<div className="w-5 h-5 border-2 border-gray-200 border-t-gray-700 rounded-full animate-spin" />
) : (
<Heart
className={`w-5 h-5 ${
isFavorite ? "text-[#005bff] fill-[#005bff]" : "text-gray-700"
className={`w-5 h-5 transition-all duration-200 ${
isFavorite
? "text-rose-500 fill-rose-500 scale-110"
: "text-gray-600 hover:text-rose-500"
}`}
/>
)}
</button>
</Button>
{/* Action Buttons */}
{button && !isOutOfStock && (
<div className="px-1 w-full">
<div className="pt-2 w-full">
{!isInCart ? (
<Button
onClick={handleAddToCart}
disabled={isSyncing}
className="w-full rounded-lg cursor-pointer gap-2 bg-[#005bff] hover:bg-[#0041c4]"
size="sm"
className="w-full h-9 rounded-[10px] bg-gradient-to-r from-gray-900 to-gray-800 hover:from-gray-800 hover:to-gray-700 text-white font-semibold shadow-md hover:shadow-lg transition-all duration-300 gap-2"
>
{isSyncing ? (
<>
{t("adding")}
</>
<div className="flex items-center gap-2">
<div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
<span>{t("adding")}</span>
</div>
) : (
<>
<ShoppingCart className="h-4 w-4" />
{t("add_to_cart")}
<ShoppingCart className="h-5 w-5" />
<span>{t("add_to_cart")}</span>
</>
)}
</Button>
@@ -395,55 +429,69 @@ export default function ProductCard({
size="icon"
onClick={(e) => handleQuantityChange(e, -1)}
disabled={isSyncing || localQuantity <= 1}
className="rounded-lg cursor-pointer h-9 w-9 shrink-0"
className="rounded-[10px] h-9 w-9 border-2 border-gray-200 hover:border-gray-900 hover:bg-gray-50 transition-all duration-200 disabled:opacity-30"
>
<Minus className="h-4 w-4" />
<Minus className="h-5 w-5 text-gray-700" />
</Button>
<div className="flex-1 text-center font-semibold text-sm border rounded-lg h-9 flex items-center justify-center bg-white relative">
{localQuantity}
<div className="flex-1 text-center font-bold text-lg border-2 border-gray-200 rounded-[10px] h-9 flex items-center justify-center bg-white relative">
{isSyncing && (
<div className="absolute inset-0 bg-white/80 rounded-xl flex items-center justify-center">
<div className="w-4 h-4 border-2 border-gray-300 border-t-gray-700 rounded-full animate-spin" />
</div>
)}
<span className={isSyncing ? "opacity-30" : ""}>
{localQuantity}
</span>
</div>
<Button
variant="outline"
size="icon"
onClick={(e) => handleQuantityChange(e, 1)}
disabled={isSyncing}
className="rounded-lg cursor-pointer h-9 w-9 shrink-0"
className="rounded-[10px] h-9 w-9 border-2 border-gray-900 bg-gray-900 hover:bg-gray-800 transition-all duration-200 disabled:opacity-30"
>
<Plus className="h-4 w-4 text-[#005bff]" />
<Plus className="h-5 w-5 text-white" />
</Button>
</div>
)}
</div>
)}
</div>
</CardContent>
</Card>
</div>
{/* Stock Warning Modal */}
<Dialog open={showStockModal} onOpenChange={setShowStockModal}>
<DialogContent className="sm:max-w-md" onClick={(e) => e.stopPropagation()}>
<DialogContent
className="sm:max-w-md rounded-lg border-0 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<DialogHeader>
<div className="flex items-center justify-center mb-4">
<div className="rounded-full bg-orange-100 p-3">
<AlertTriangle className="h-6 w-6 text-orange-600" />
<div className="flex items-center justify-center mb-6">
<div className="rounded-full bg-amber-100 p-3">
<AlertTriangle className="h-8 w-8 text-amber-600" />
</div>
</div>
<DialogTitle className="text-center text-xl">
<DialogTitle className="text-center text-2xl font-bold text-gray-900">
{t("stock_limit_title")}
</DialogTitle>
<DialogDescription className="text-center text-base pt-2">
<DialogDescription className="text-center text-base pt-4 text-gray-600 leading-relaxed">
{t("stock_limit_message", {
product: name,
stock: availableStock,
})}
</DialogDescription>
</DialogHeader>
<div className="flex justify-center mt-4">
<div className="flex justify-center mt-6">
<Button
onClick={(e) => {
e.stopPropagation();
setShowStockModal(false);
}}
className="w-full rounded-lg cursor-pointer"
className="w-full h-12 rounded-lg bg-gray-900 hover:bg-gray-800 text-white font-semibold shadow-md hover:shadow-lg transition-all duration-300"
>
{t("understood")}
</Button>

View File

@@ -1,6 +1,16 @@
import { useState, useEffect, useRef, useCallback } from "react";
import Image from "next/image";
import {
X,
ZoomIn,
ZoomOut,
RotateCw,
RotateCcw,
Maximize2,
ChevronLeft,
ChevronRight,
} from "lucide-react";
import { useTranslations } from "next-intl";
interface ProductImageGalleryProps {
images: string[];
productName: string;
@@ -13,10 +23,22 @@ export function ProductImageGallery({
noImageText,
}: ProductImageGalleryProps) {
const [selectedImage, setSelectedImage] = useState(0);
const [isModalOpen, setIsModalOpen] = useState(false);
const [zoom, setZoom] = useState(1);
const [rotation, setRotation] = useState(0);
const [position, setPosition] = useState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
const t = useTranslations();
const autoplayTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const modalImageRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (images.length <= 1) return;
setSelectedImage(0);
}, [images]);
useEffect(() => {
if (images.length <= 1 || isModalOpen) return;
const startAutoplay = () => {
autoplayTimerRef.current = setInterval(() => {
@@ -28,35 +50,136 @@ export function ProductImageGallery({
return () => {
if (autoplayTimerRef.current) clearInterval(autoplayTimerRef.current);
};
}, [images.length]);
}, [images.length, isModalOpen]);
useEffect(() => {
if (isModalOpen) {
document.body.style.overflow = "hidden";
if (autoplayTimerRef.current) clearInterval(autoplayTimerRef.current);
} else {
document.body.style.overflow = "unset";
}
return () => {
document.body.style.overflow = "unset";
};
}, [isModalOpen]);
const handleImageSelect = useCallback(
(index: number) => {
setSelectedImage(index);
if (autoplayTimerRef.current) clearInterval(autoplayTimerRef.current);
if (images.length > 1) {
if (images.length > 1 && !isModalOpen) {
autoplayTimerRef.current = setInterval(() => {
setSelectedImage((prev) => (prev + 1) % images.length);
}, 3000);
}
},
[images.length]
[images.length, isModalOpen],
);
const openModal = () => {
setIsModalOpen(true);
resetTransform();
};
const closeModal = () => {
setIsModalOpen(false);
resetTransform();
};
const resetTransform = () => {
setZoom(1);
setRotation(0);
setPosition({ x: 0, y: 0 });
};
const handleZoomIn = () => {
setZoom((prev) => Math.min(prev + 0.25, 5));
};
const handleZoomOut = () => {
setZoom((prev) => Math.max(prev - 0.25, 0.5));
};
const handleRotateClockwise = () => {
setRotation((prev) => (prev + 90) % 360);
};
const handleRotateCounterClockwise = () => {
setRotation((prev) => (prev - 90 + 360) % 360);
};
const handleMouseDown = (e: React.MouseEvent | React.TouchEvent) => {
if (zoom > 1) {
setIsDragging(true);
const clientX = "touches" in e ? e.touches[0].clientX : e.clientX;
const clientY = "touches" in e ? e.touches[0].clientY : e.clientY;
setDragStart({
x: clientX - position.x,
y: clientY - position.y,
});
}
};
const handleMouseMove = (e: React.MouseEvent | React.TouchEvent) => {
if (isDragging && zoom > 1) {
const clientX = "touches" in e ? e.touches[0].clientX : e.clientX;
const clientY = "touches" in e ? e.touches[0].clientY : e.clientY;
setPosition({
x: clientX - dragStart.x,
y: clientY - dragStart.y,
});
}
};
const handleMouseUp = () => {
setIsDragging(false);
};
const handleWheel = (e: React.WheelEvent) => {
e.preventDefault();
if (e.deltaY < 0) {
handleZoomIn();
} else {
handleZoomOut();
}
};
const handleModalImageChange = (direction: "prev" | "next") => {
if (direction === "next") {
setSelectedImage((prev) => (prev + 1) % images.length);
} else {
setSelectedImage((prev) => (prev - 1 + images.length) % images.length);
}
resetTransform();
};
return (
<div className="contents max-w-2xl">
<>
<div className="w-full lg:flex-1 max-w-2xl">
<div className="relative">
<div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-white">
{images.length > 0 ? (
<div
className="relative aspect-square w-full rounded-xl md:rounded-2xl overflow-hidden bg-gradient-to-br from-gray-50 to-gray-100 cursor-pointer group shadow-sm hover:shadow-md transition-all"
onClick={openModal}
>
{images.length > 0 && images[selectedImage] ? (
<>
<Image
src={images[selectedImage]}
alt={productName}
fill
className="object-contain"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
className="object-contain transition-transform group-hover:scale-105"
priority
/>
<div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
<div className="bg-white/90 backdrop-blur-sm rounded-full p-2 md:p-3 transform translate-y-4 group-hover:translate-y-0 transition-transform">
<Maximize2 className="w-4 h-4 md:w-5 md:h-5 text-gray-800" />
</div>
</div>
</>
) : (
<div className="flex items-center justify-center h-full text-gray-400">
<div className="flex items-center justify-center h-full text-gray-400 text-sm md:text-base">
{noImageText}
</div>
)}
@@ -86,5 +209,258 @@ export function ProductImageGallery({
)}
</div>
</div>
{/* Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-99 bg-gradient-to-br from-gray-900/95 via-gray-800/95 to-gray-900/95 backdrop-blur-xl flex flex-col">
{/* Top Bar */}
<div className="absolute top-0 left-0 right-0 p-3 md:p-4 z-20 bg-gradient-to-b from-black/20 to-transparent">
<div className="max-w-7xl mx-auto flex items-center justify-between">
<div className="flex items-center gap-2 md:gap-3 min-w-0 flex-1">
<div className="w-1 h-4 md:h-6 bg-blue-500 rounded-full shrink-0" />
<span className="text-white font-medium text-sm md:text-base truncate">
{productName}
</span>
</div>
<button
onClick={closeModal}
className="p-2 md:p-2.5 bg-white/10 hover:bg-white/20 rounded-lg md:rounded-xl transition-all backdrop-blur-sm border border-white/10 shrink-0 ml-2"
aria-label="Close"
>
<X className="w-4 h-4 md:w-5 md:h-5 text-white" />
</button>
</div>
</div>
{/* Main Image Area */}
<div className="flex-1 flex items-center justify-center relative px-2 md:px-16 lg:px-20">
{/* Left Arrow - Desktop */}
{images.length > 1 && (
<button
onClick={() => handleModalImageChange("prev")}
className="hidden md:flex absolute left-3 lg:left-6 p-2.5 md:p-3 bg-white/10 hover:bg-white/20 rounded-xl md:rounded-2xl transition-all backdrop-blur-md border border-white/10 hover:scale-110 z-10 group"
aria-label="Previous image"
>
<ChevronLeft className="w-5 h-5 md:w-6 md:h-6 text-white" />
</button>
)}
{/* Image Container */}
<div
ref={modalImageRef}
className="w-full h-full flex items-center justify-center overflow-hidden"
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
onTouchStart={handleMouseDown}
onTouchMove={handleMouseMove}
onTouchEnd={handleMouseUp}
onWheel={handleWheel}
style={{
cursor:
zoom > 1 ? (isDragging ? "grabbing" : "grab") : "default",
}}
>
<div
style={{
transform: `translate(${position.x}px, ${position.y}px) scale(${zoom}) rotate(${rotation}deg)`,
transition: isDragging
? "none"
: "transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
}}
className="relative w-[90vw] h-[60vh] md:w-[75vw] md:h-[70vh]"
>
<Image
src={images[selectedImage]}
alt={productName}
fill
className="object-contain pointer-events-none select-none"
priority
draggable={false}
/>
</div>
</div>
{/* Right Arrow - Desktop */}
{images.length > 1 && (
<button
onClick={() => handleModalImageChange("next")}
className="hidden md:flex absolute right-3 lg:right-6 p-2.5 md:p-3 bg-white/10 hover:bg-white/20 rounded-xl md:rounded-2xl transition-all backdrop-blur-md border border-white/10 hover:scale-110 z-10 group"
aria-label="Next image"
>
<ChevronRight className="w-5 h-5 md:w-6 md:h-6 text-white" />
</button>
)}
</div>
{/* Bottom Control Bar */}
<div className="bg-gradient-to-t from-black/40 via-black/20 to-transparent backdrop-blur-xl border-t border-white/10">
<div className="max-w-7xl mx-auto px-3 md:px-6 py-3 md:py-4">
{/* Mobile Layout */}
<div className="md:hidden flex flex-col gap-2">
{/* Row 1: Navigation */}
{images.length > 1 && (
<div className="flex items-center justify-between gap-2">
<button
onClick={() => handleModalImageChange("prev")}
className="flex-1 p-2 bg-white/10 hover:bg-white/20 rounded-lg transition-all border border-white/10"
aria-label="Previous"
>
<ChevronLeft className="w-5 h-5 text-white mx-auto" />
</button>
<div className="px-4 py-2 bg-white/10 backdrop-blur-md rounded-lg border border-white/10">
<span className="text-white text-sm font-medium whitespace-nowrap">
{selectedImage + 1} / {images.length}
</span>
</div>
<button
onClick={() => handleModalImageChange("next")}
className="flex-1 p-2 bg-white/10 hover:bg-white/20 rounded-lg transition-all border border-white/10"
aria-label="Next"
>
<ChevronRight className="w-5 h-5 text-white mx-auto" />
</button>
</div>
)}
{/* Row 2: Zoom & Rotate */}
<div className="flex items-center gap-2">
<div className="flex items-center gap-1 bg-white/10 backdrop-blur-md rounded-lg p-1 border border-white/10 flex-1">
<button
onClick={handleZoomOut}
className="p-2 hover:bg-white/20 rounded-md transition-all flex-1"
aria-label="Zoom out"
>
<ZoomOut className="w-4 h-4 text-white mx-auto" />
</button>
<div className="px-2 py-1 bg-white/10 rounded text-center min-w-[50px]">
<span className="text-white text-xs font-medium">
{Math.round(zoom * 100)}%
</span>
</div>
<button
onClick={handleZoomIn}
className="p-2 hover:bg-white/20 rounded-md transition-all flex-1"
aria-label="Zoom in"
>
<ZoomIn className="w-4 h-4 text-white mx-auto" />
</button>
</div>
<div className="flex items-center gap-1 bg-white/10 backdrop-blur-md rounded-lg p-1 border border-white/10">
<button
onClick={handleRotateCounterClockwise}
className="p-2 hover:bg-white/20 rounded-md transition-all"
aria-label="Rotate counter-clockwise"
>
<RotateCcw className="w-4 h-4 text-white" />
</button>
<button
onClick={handleRotateClockwise}
className="p-2 hover:bg-white/20 rounded-md transition-all"
aria-label="Rotate clockwise"
>
<RotateCw className="w-4 h-4 text-white" />
</button>
</div>
<button
onClick={resetTransform}
className="px-3 py-2 bg-white/10 hover:bg-white/20 rounded-lg transition-all text-white text-xs font-medium border border-white/10"
aria-label="Reset view"
>
{t("reset")}
</button>
</div>
</div>
{/* Desktop Layout */}
<div className="hidden md:flex items-center justify-center gap-2">
<button
onClick={() => handleModalImageChange("prev")}
disabled={images.length <= 1}
className="p-2 bg-white/10 hover:bg-white/20 rounded-lg transition-all disabled:opacity-30 disabled:cursor-not-allowed border border-white/10"
aria-label="Previous"
>
<ChevronLeft className="w-4 h-4 text-white" />
</button>
<div className="flex items-center gap-1.5 bg-white/10 backdrop-blur-md rounded-lg p-1 border border-white/10">
<button
onClick={handleZoomOut}
className="p-2 hover:bg-white/20 rounded-md transition-all"
aria-label="Zoom out"
>
<ZoomOut className="w-4 h-4 text-white" />
</button>
<div className="px-3 py-1 bg-white/10 rounded min-w-[60px] text-center">
<span className="text-white text-sm font-medium">
{Math.round(zoom * 100)}%
</span>
</div>
<button
onClick={handleZoomIn}
className="p-2 hover:bg-white/20 rounded-md transition-all"
aria-label="Zoom in"
>
<ZoomIn className="w-4 h-4 text-white" />
</button>
</div>
<div className="w-px h-8 bg-white/20" />
<div className="flex items-center gap-1.5 bg-white/10 backdrop-blur-md rounded-lg p-1 border border-white/10">
<button
onClick={handleRotateCounterClockwise}
className="p-2 hover:bg-white/20 rounded-md transition-all"
aria-label="Rotate counter-clockwise"
>
<RotateCcw className="w-4 h-4 text-white" />
</button>
<button
onClick={handleRotateClockwise}
className="p-2 hover:bg-white/20 rounded-md transition-all"
aria-label="Rotate clockwise"
>
<RotateCw className="w-4 h-4 text-white" />
</button>
</div>
<button
onClick={resetTransform}
className="px-4 py-2 bg-white/10 hover:bg-white/20 rounded-lg transition-all text-white text-sm font-medium border border-white/10"
aria-label="Reset view"
>
Reset
</button>
<div className="w-px h-8 bg-white/20" />
<button
onClick={() => handleModalImageChange("next")}
disabled={images.length <= 1}
className="p-2 bg-white/10 hover:bg-white/20 rounded-lg transition-all disabled:opacity-30 disabled:cursor-not-allowed border border-white/10"
aria-label="Next"
>
<ChevronRight className="w-4 h-4 text-white" />
</button>
{images.length > 1 && (
<>
<div className="w-px h-8 bg-white/20" />
<div className="px-4 py-2 bg-white/10 backdrop-blur-md rounded-lg border border-white/10">
<span className="text-white text-sm font-medium">
{selectedImage + 1} / {images.length}
</span>
</div>
</>
)}
</div>
</div>
</div>
</div>
)}
</>
);
}

View File

@@ -1,6 +1,6 @@
import { Card } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Star } from "lucide-react";
import { Star, Package, Tag, Palette } from "lucide-react";
interface ProductProperty {
name: string;
@@ -33,38 +33,76 @@ export function ProductInfoCard({
t,
}: ProductInfoCardProps) {
return (
<div className="flex-1 space-y-6 bg-white">
<Card className="p-4 rounded-xl border-gray-200">
<h3 className="text-xl font-semibold mb-4">{name}</h3>
<div className="space-y-3">
<div className="flex-1 space-y-6 bg-transparent">
{/* Main Info Card */}
<Card className="p-6 rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-300 gap-0">
<div className="">
<h1 className="text-3xl font-bold text-gray-900 leading-tight mb-3">
{name}
</h1>
{/* Rating Section */}
{reviewsCount > 0 && (
<div className="flex items-center gap-3 pt-2">
<div className="flex items-center gap-1.5">
{Array.from({ length: 5 }).map((_, idx) => (
<Star
key={idx}
className={`h-5 w-5 ${
idx < Math.floor(averageRating)
? "fill-amber-400 text-amber-400"
: "fill-gray-200 text-gray-200"
}`}
/>
))}
</div>
<span className="text-sm font-semibold text-gray-900">
{averageRating.toFixed(1)}
</span>
<span className="text-sm text-gray-500">
({reviewsCount} {t("reviews")})
</span>
</div>
)}
</div>
<Separator className="my-6 bg-gray-100" />
{/* Specifications */}
<div className="space-y-1">
{brandName && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t("brands")}</span>
<span className="font-medium">{brandName}</span>
<div className="flex justify-between items-center py-3.5 px-4 rounded-xl hover:bg-gray-50 transition-colors group">
<div className="flex items-center gap-3">
<div className="h-9 w-9 rounded-xl bg-gray-100 group-hover:bg-gray-200 flex items-center justify-center transition-colors">
<Package className="h-4.5 w-4.5 text-gray-700" />
</div>
<Separator />
<span className="text-gray-600 font-medium">
{t("brands")}
</span>
</div>
<span className="font-semibold text-gray-900">{brandName}</span>
</div>
<Separator className="bg-gray-100" />
</>
)}
{/* {barcode && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t("barcode")}</span>
<span className="font-mono text-sm">{barcode}</span>
</div>
<Separator />
</>
)} */}
{colour && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t("color")}</span>
<span className="font-medium">{colour}</span>
<div className="flex justify-between items-center py-3.5 px-4 rounded-xl hover:bg-gray-50 transition-colors group">
<div className="flex items-center gap-3">
<div className="h-9 w-9 rounded-xl bg-gray-100 group-hover:bg-gray-200 flex items-center justify-center transition-colors">
<Palette className="h-4.5 w-4.5 text-gray-700" />
</div>
<Separator />
<span className="text-gray-600 font-medium">
{t("color")}
</span>
</div>
<div className="flex items-center gap-2">
<span className="font-semibold text-gray-900">{colour}</span>
</div>
</div>
<Separator className="bg-gray-100" />
</>
)}
@@ -74,26 +112,62 @@ export function ProductInfoCard({
(prop, idx) =>
prop.value && (
<div key={idx}>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{prop.name}</span>
<span className="font-medium">{prop.value}</span>
<div className="flex justify-between items-center py-3.5 px-4 rounded-xl hover:bg-gray-50 transition-colors group">
<div className="flex items-center gap-3">
<div className="h-9 w-9 rounded-xl bg-gray-100 group-hover:bg-gray-200 flex items-center justify-center transition-colors">
<Tag className="h-4.5 w-4.5 text-gray-700" />
</div>
{idx < properties.length - 1 && <Separator />}
<span className="text-gray-600 font-medium">
{prop.name}
</span>
</div>
)
<span className="font-semibold text-gray-900 text-right max-w-[200px] truncate">
{prop.value}
</span>
</div>
{idx < properties.length - 1 && (
<Separator className="bg-gray-100" />
)}
</div>
),
)}
</>
)}
</div>
</Card>
{/* Description Card */}
{description && (
<Card className="p-4 rounded-xl border-gray-200 gap-2">
<h3 className="text-xl font-semibold mb-3">
<Card className="p-8 rounded-3xl border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-300">
<div className="flex items-center gap-3 mb-6">
<div className="h-10 w-10 rounded-xl bg-gray-900 flex items-center justify-center">
<svg
className="h-5 w-5 text-white"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
</div>
<h3 className="text-2xl font-bold text-gray-900">
{t("product_description")}
</h3>
</div>
<div
className="text-gray-700 leading-relaxed prose prose-sm max-w-none"
className="text-gray-700 leading-relaxed prose prose-sm max-w-none
prose-headings:text-gray-900 prose-headings:font-bold
prose-p:text-gray-700 prose-p:leading-relaxed
prose-ul:text-gray-700 prose-ol:text-gray-700
prose-li:text-gray-700 prose-li:leading-relaxed
prose-strong:text-gray-900 prose-strong:font-semibold
prose-a:text-gray-900 prose-a:font-medium hover:prose-a:text-gray-700"
dangerouslySetInnerHTML={{ __html: description }}
/>
</Card>

View File

@@ -39,6 +39,10 @@ interface PendingUpdate {
retryCount: number;
}
// const DEBUG = true
// const log = (...args: any[]) => {
// if (DEBUG) console.log("[ProductPage]", ...args)
// }
export default function ProductPageContent({ slug }: ProductDetailProps) {
const [localQuantity, setLocalQuantity] = useState(1);
@@ -68,7 +72,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
refetch: refetchProduct,
} = useProductsBySlug(slug);
const { isFavorite, isLoading: isFavLoading } = useIsFavorite(
product?.id || 0
product?.id || 0,
);
const cartOptions = useMemo(
() => ({
@@ -76,7 +80,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
refetchOnWindowFocus: true,
staleTime: 0,
}),
[]
[],
);
const { mutate: toggleFavoriteMutation } = useToggleFavorite();
const {
@@ -96,7 +100,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
const cartItem = useMemo(() => {
const item = cartData?.data?.find(
(item: any) => item.product?.id === product?.id
(item: any) => item.product?.id === product?.id,
);
return item;
@@ -105,19 +109,29 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
const isInCart = !!cartItem;
const availableStock = product?.stock || 0;
const imageUrls = useMemo(
() =>
product?.media?.map(
(m) => m.images_800x800 || m.images_720x720 || m.thumbnail
) || [],
[product]
);
const imageUrls = useMemo(() => {
if (!product?.media || product.media.length === 0) {
return [];
}
const urls = product.media
.map((m) => {
const url =
m.images_800x800 ||
m.images_720x720 ||
m.images_400x400 ||
m.thumbnail;
return url;
})
.filter(Boolean);
return urls;
}, [product]);
const reviews = useMemo(() => product?.reviews_resources || [], [product]);
const averageRating = useMemo(
() =>
product?.reviews?.rating ? Number.parseFloat(product.reviews.rating) : 0,
[product]
[product],
);
const transformedRelatedProducts = useMemo(() => {
@@ -169,13 +183,13 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
};
sessionStorage.setItem(
PENDING_PRODUCT_UPDATES_KEY,
JSON.stringify(pending)
JSON.stringify(pending),
);
} catch (error) {
console.error("Failed to save pending update:", error);
}
},
[product?.id]
[product?.id],
);
const clearPendingUpdate = useCallback(() => {
@@ -190,7 +204,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
} else {
sessionStorage.setItem(
PENDING_PRODUCT_UPDATES_KEY,
JSON.stringify(pending)
JSON.stringify(pending),
);
}
}
@@ -221,7 +235,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
syncToServerRef.current?.(quantity);
}, delay);
},
[t]
[t],
);
retrySyncRef.current = retrySync;
@@ -284,7 +298,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
cartItem,
clearPendingUpdate,
t,
]
],
);
syncToServerRef.current = syncToServer;
@@ -397,7 +411,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
toast.success(
data?.wasAdded
? t("added_to_favorites")
: t("removed_from_favorites")
: t("removed_from_favorites"),
);
},
onError: () => {
@@ -405,10 +419,10 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
description: "Try again later",
});
},
}
},
);
},
[product?.id, isFavorite, toggleFavoriteMutation, t]
[product?.id, isFavorite, toggleFavoriteMutation, t],
);
const handleSubmitReview = useCallback(
@@ -438,7 +452,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
});
}
},
[product?.id, submitReviewMutation, refetchProduct, t]
[product?.id, submitReviewMutation, refetchProduct, t],
);
const loadingSkeleton = useMemo(
@@ -460,7 +474,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
</div>
</div>
),
[]
[],
);
if (productLoading) return loadingSkeleton;
@@ -520,14 +534,14 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
/>
</div>
{/* <ProductReviewsSection
<ProductReviewsSection
reviews={reviews}
averageRating={averageRating}
isLoading={false}
onWriteReview={() => setShowReviewModal(true)}
/>
<RelatedProductsSection products={transformedRelatedProducts} /> */}
<RelatedProductsSection products={transformedRelatedProducts} />
</div>
<StockLimitModal

View File

@@ -38,122 +38,150 @@ export function ProductPurchaseCard({
onToggleFavorite,
t,
}: ProductPurchaseCardProps) {
const isOutOfStock = productStock === 0;
return (
<div className="lg:w-[380px] space-y-4">
<Card className="p-6 rounded-xl">
<div className="flex justify-between items-start mb-6">
<span className="text-lg text-gray-500">{t("price")}:</span>
<div className="lg:w-[420px] space-y-4">
<Card className="p-6 rounded-lg border border-gray-200 shadow-lg hover:shadow-xl transition-shadow duration-300">
{/* Price Section */}
<div className="flex justify-between items-baseline mb-3 pb-4 border-b border-gray-100 ">
<span className="text-lg font-medium text-gray-600">
{t("price")}:
</span>
<div className="flex flex-col items-end">
<span className="text-3xl font-bold text-primary">{price} TMT</span>
<span className="text-4xl font-bold text-gray-900 tracking-tight">
{price}{" "}
<span className="text-2xl font-semibold text-gray-500">TMT</span>
</span>
{oldPrice && parseFloat(oldPrice) > 0 && (
<span className="text-lg text-gray-400 line-through">
<span className="text-lg text-gray-400 line-through mt-1">
{oldPrice} TMT
</span>
)}
</div>
</div>
<div className="space-y-2">
{/* Action Buttons Section */}
<div className="space-y-3">
{isInCart ? (
<>
{/* Go to Cart Button */}
<Link href="/cart">
<Button
size="lg"
className="w-full rounded-lg cursor-pointer text-lg font-bold bg-green-600 hover:bg-green-700 mb-4"
className="w-full h-12 rounded-[10px] cursor-pointer text-lg font-bold bg-gradient-to-r from-emerald-600 to-emerald-500 hover:from-emerald-700 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-300"
>
<ShoppingCart className="mr-2 h-5 w-5" />
{t("go_to_cart")}
</Button>
</Link>
<div className="flex items-center gap-2">
{/* Quantity Controls */}
<div className="flex items-center gap-3 pt-2">
<Button
variant="outline"
size="icon"
onClick={onQuantityDecrease}
disabled={isSyncing}
className={`rounded-lg cursor-pointer h-12 w-12 ${
isSyncing ? "opacity-70" : ""
className={`rounded-[10px] h-12 w-12 border-2 border-gray-200 hover:border-gray-900 hover:bg-gray-50 transition-all duration-200 disabled:opacity-30 disabled:cursor-not-allowed ${
isSyncing ? "opacity-50" : ""
}`}
>
<Minus className="h-5 w-5" />
<Minus className="h-5 w-5 text-gray-700" />
</Button>
<div className="flex-1 text-center font-semibold text-xl border rounded-xl h-12 flex items-center justify-center relative">
<div className="flex-1 text-center font-semibold text-2xl border-2 border-gray-200 rounded-[10px] h-12 flex items-center justify-center bg-white relative">
{isSyncing ? (
<div className="absolute inset-0 bg-white/80 rounded-2xl flex items-center justify-center">
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-900 rounded-full animate-spin" />
</div>
) : null}
<span className={isSyncing ? "opacity-30" : ""}>
{localQuantity}
</span>
{syncError && (
<span
className="absolute -top-1 -right-1 h-2 w-2 bg-red-500 rounded-full"
className="absolute -top-1 -right-1 h-3 w-3 bg-red-500 rounded-full border-2 border-white shadow-sm"
title="Sync error"
/>
)}
</div>
<Button
variant="outline"
size="icon"
onClick={onQuantityIncrease}
disabled={isSyncing}
className={`rounded-lg cursor-pointer h-12 w-12 ${
isSyncing ? "opacity-70" : ""
disabled={isSyncing || localQuantity >= availableStock}
className={`rounded-[10px] h-12 w-12 border-2 border-gray-900 bg-gray-900 hover:bg-gray-800 transition-all duration-200 disabled:opacity-30 disabled:cursor-not-allowed ${
isSyncing ? "opacity-50" : ""
}`}
>
<Plus className="h-5 w-5" />
<Plus className="h-5 w-5 text-white" />
</Button>
{/* Favorite Button - In Cart */}
<Button
variant="outline"
size="icon"
onClick={onToggleFavorite}
className={`rounded-lg h-12 w-12 transition-all border cursor-pointer ${
className={`rounded-[10px] h-12 w-12 transition-all duration-200 border-2 cursor-pointer ${
isFavorite
? "bg-[#F0F8FF] border-blue-300 hover:bg-blue-100"
: "hover:bg-gray-50"
? "bg-rose-50 border-rose-200 hover:bg-rose-100 hover:border-rose-300"
: "border-gray-200 hover:border-gray-900 hover:bg-gray-50"
}`}
>
<Heart
className={`h-6! w-6! transition-all ${
className={`h-6 w-6 transition-all duration-200 ${
isFavorite
? "fill-[#005bff] text-[#005bff]"
: "text-[#005bff]"
? "fill-rose-500 text-rose-500 scale-110"
: "text-gray-700 hover:text-rose-500"
}`}
/>
</Button>
</div>
</>
) : (
<div className="flex items-center gap-2">
<div className="flex items-center gap-3">
{/* Add to Cart Button */}
<Button
size="lg"
onClick={onAddToCart}
disabled={isSyncing || productStock === 0}
className="flex-1 rounded-lg text-lg font-bold bg-[#005bff] hover:bg-[#0041c4] cursor-pointer"
disabled={isSyncing || isOutOfStock}
className={`flex-1 h-12 rounded-[10px] text-lg font-bold shadow-md hover:shadow-lg transition-all duration-300 cursor-pointer ${
isOutOfStock
? "bg-gray-300 text-gray-600 cursor-not-allowed"
: "bg-gradient-to-r from-gray-900 to-gray-800 hover:from-gray-800 hover:to-gray-700"
}`}
>
{isSyncing ? (
<>{t("adding")}</>
<div className="flex items-center gap-2">
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
<span>{t("adding")}</span>
</div>
) : (
<>
<ShoppingCart className="mr-2 h-5 w-5" />
{productStock === 0 ? t("out_of_stock") : t("add_to_cart")}
{isOutOfStock ? t("out_of_stock") : t("add_to_cart")}
</>
)}
</Button>
{/* Favorite Button - Not in Cart */}
<Button
variant="outline"
size="icon"
onClick={onToggleFavorite}
className={`rounded-lg h-12 w-12 transition-all border cursor-pointer ${
className={`rounded-[10px] h-12 w-12 transition-all duration-200 border-2 cursor-pointer ${
isFavorite
? "bg-[#F0F8FF] border-blue-300 hover:bg-blue-100"
: "hover:bg-gray-50"
? "bg-rose-50 border-rose-200 hover:bg-rose-100 hover:border-rose-300"
: "border-gray-200 hover:border-gray-900 hover:bg-gray-50"
}`}
>
<Heart
className={`h-6! w-6! transition-all ${
className={`h-6 w-6 transition-all duration-200 ${
isFavorite
? "fill-[#005bff] text-[#005bff]"
: "text-[#005bff]"
? "fill-rose-500 text-rose-500 scale-110"
: "text-gray-700 hover:text-rose-500"
}`}
/>
</Button>
@@ -161,8 +189,6 @@ export function ProductPurchaseCard({
)}
</div>
</Card>
</div>
);
}

View File

@@ -1,6 +1,10 @@
// lib/api.ts
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from "axios";
import axios, {
type AxiosInstance,
type AxiosRequestConfig,
type AxiosResponse,
} from "axios";
import TokenStorage from "./tokenStorage";
const localeToApiLang = (locale: string): string => {
@@ -42,7 +46,12 @@ class APIClient {
config.headers.Authorization = `Bearer ${token}`;
}
// Add language parameter
// Add language parameter (except for POST requests to /orders)
const url = config.url || "";
const isOrderPost =
config.method?.toLowerCase() === "post" && url.includes("/orders");
if (!isOrderPost) {
let lang = "tm";
if (typeof window !== "undefined") {
@@ -56,13 +65,13 @@ class APIClient {
}
}
const url = config.url || "";
const separator = url.includes("?") ? "&" : "?";
config.url = `${url}${separator}lang=${lang}`;
}
return config;
},
(error) => Promise.reject(error)
(error) => Promise.reject(error),
);
// Response interceptor
@@ -92,10 +101,11 @@ class APIClient {
"Content-Type": "application/json",
"Api-Token": process.env.NEXT_PUBLIC_API_TOKEN || "123",
},
}
},
);
const newToken = guestTokenResponse.data?.token || guestTokenResponse.data?.data;
const newToken =
guestTokenResponse.data?.token || guestTokenResponse.data?.data;
if (newToken) {
TokenStorage.setGuestToken(newToken);
@@ -131,7 +141,7 @@ class APIClient {
}
return Promise.reject(error);
}
},
);
}
@@ -146,23 +156,41 @@ class APIClient {
this.failedQueue = [];
}
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
get<T = any>(
url: string,
config?: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
return this.client.get<T>(url, config);
}
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
post<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
return this.client.post<T>(url, data, config);
}
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
put<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
return this.client.put<T>(url, data, config);
}
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
patch<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
return this.client.patch<T>(url, data, config);
}
delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
delete<T = any>(
url: string,
config?: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
return this.client.delete<T>(url, config);
}
}

View File

@@ -11,8 +11,8 @@ const nextConfig: NextConfig = {
unoptimized: true,
remotePatterns: [
{
protocol: "http",
hostname: "shop.post.tm",
protocol: "https",
hostname: "hyzmat.app",
// port: "8080",
},
],

82
package-lock.json generated
View File

@@ -1,11 +1,11 @@
{
"name": "ecommerce",
"name": "Smart-Electronics",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ecommerce",
"name": "Smart-Electronics",
"version": "0.1.0",
"dependencies": {
"@radix-ui/react-avatar": "^1.1.11",
@@ -1159,9 +1159,9 @@
}
},
"node_modules/@next/env": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.1.tgz",
"integrity": "sha512-3oxyM97Sr2PqiVyMyrZUtrtM3jqqFxOQJVuKclDsgj/L728iZt/GyslkN4NwarledZATCenbk4Offjk1hQmaAA==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.6.tgz",
"integrity": "sha512-N1ySLuZjnAtN3kFnwhAwPvZah8RJxKasD7x1f8shFqhncnWZn4JMfg37diLNuoHsLAlrDfM3g4mawVdtAG8XLQ==",
"license": "MIT"
},
"node_modules/@next/eslint-plugin-next": {
@@ -1175,9 +1175,9 @@
}
},
"node_modules/@next/swc-darwin-arm64": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.1.1.tgz",
"integrity": "sha512-JS3m42ifsVSJjSTzh27nW+Igfha3NdBOFScr9C80hHGrWx55pTrVL23RJbqir7k7/15SKlrLHhh/MQzqBBYrQA==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.1.6.tgz",
"integrity": "sha512-wTzYulosJr/6nFnqGW7FrG3jfUUlEf8UjGA0/pyypJl42ExdVgC6xJgcXQ+V8QFn6niSG2Pb8+MIG1mZr2vczw==",
"cpu": [
"arm64"
],
@@ -1191,9 +1191,9 @@
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.1.1.tgz",
"integrity": "sha512-hbyKtrDGUkgkyQi1m1IyD3q4I/3m9ngr+V93z4oKHrPcmxwNL5iMWORvLSGAf2YujL+6HxgVvZuCYZfLfb4bGw==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.1.6.tgz",
"integrity": "sha512-BLFPYPDO+MNJsiDWbeVzqvYd4NyuRrEYVB5k2N3JfWncuHAy2IVwMAOlVQDFjj+krkWzhY2apvmekMkfQR0CUQ==",
"cpu": [
"x64"
],
@@ -1207,9 +1207,9 @@
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.1.1.tgz",
"integrity": "sha512-/fvHet+EYckFvRLQ0jPHJCUI5/B56+2DpI1xDSvi80r/3Ez+Eaa2Yq4tJcRTaB1kqj/HrYKn8Yplm9bNoMJpwQ==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.1.6.tgz",
"integrity": "sha512-OJYkCd5pj/QloBvoEcJ2XiMnlJkRv9idWA/j0ugSuA34gMT6f5b7vOiCQHVRpvStoZUknhl6/UxOXL4OwtdaBw==",
"cpu": [
"arm64"
],
@@ -1223,9 +1223,9 @@
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.1.1.tgz",
"integrity": "sha512-MFHrgL4TXNQbBPzkKKur4Fb5ICEJa87HM7fczFs2+HWblM7mMLdco3dvyTI+QmLBU9xgns/EeeINSZD6Ar+oLg==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.1.6.tgz",
"integrity": "sha512-S4J2v+8tT3NIO9u2q+S0G5KdvNDjXfAv06OhfOzNDaBn5rw84DGXWndOEB7d5/x852A20sW1M56vhC/tRVbccQ==",
"cpu": [
"arm64"
],
@@ -1239,9 +1239,9 @@
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.1.1.tgz",
"integrity": "sha512-20bYDfgOQAPUkkKBnyP9PTuHiJGM7HzNBbuqmD0jiFVZ0aOldz+VnJhbxzjcSabYsnNjMPsE0cyzEudpYxsrUQ==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.1.6.tgz",
"integrity": "sha512-2eEBDkFlMMNQnkTyPBhQOAyn2qMxyG2eE7GPH2WIDGEpEILcBPI/jdSv4t6xupSP+ot/jkfrCShLAa7+ZUPcJQ==",
"cpu": [
"x64"
],
@@ -1255,9 +1255,9 @@
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.1.1.tgz",
"integrity": "sha512-9pRbK3M4asAHQRkwaXwu601oPZHghuSC8IXNENgbBSyImHv/zY4K5udBusgdHkvJ/Tcr96jJwQYOll0qU8+fPA==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.1.6.tgz",
"integrity": "sha512-oicJwRlyOoZXVlxmIMaTq7f8pN9QNbdes0q2FXfRsPhfCi8n8JmOZJm5oo1pwDaFbnnD421rVU409M3evFbIqg==",
"cpu": [
"x64"
],
@@ -1271,9 +1271,9 @@
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.1.1.tgz",
"integrity": "sha512-bdfQkggaLgnmYrFkSQfsHfOhk/mCYmjnrbRCGgkMcoOBZ4n+TRRSLmT/CU5SATzlBJ9TpioUyBW/vWFXTqQRiA==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.1.6.tgz",
"integrity": "sha512-gQmm8izDTPgs+DCWH22kcDmuUp7NyiJgEl18bcr8irXA5N2m2O+JQIr6f3ct42GOs9c0h8QF3L5SzIxcYAAXXw==",
"cpu": [
"arm64"
],
@@ -1287,9 +1287,9 @@
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.1.1.tgz",
"integrity": "sha512-Ncwbw2WJ57Al5OX0k4chM68DKhEPlrXBaSXDCi2kPi5f4d8b3ejr3RRJGfKBLrn2YJL5ezNS7w2TZLHSti8CMw==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.1.6.tgz",
"integrity": "sha512-NRfO39AIrzBnixKbjuo2YiYhB6o9d8v/ymU9m/Xk8cyVk+k7XylniXkHwjs4s70wedVffc6bQNbufk5v0xEm0A==",
"cpu": [
"x64"
],
@@ -7554,12 +7554,12 @@
}
},
"node_modules/next": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/next/-/next-16.1.1.tgz",
"integrity": "sha512-QI+T7xrxt1pF6SQ/JYFz95ro/mg/1Znk5vBebsWwbpejj1T0A23hO7GYEaVac9QUOT2BIMiuzm0L99ooq7k0/w==",
"version": "16.1.6",
"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz",
"integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==",
"license": "MIT",
"dependencies": {
"@next/env": "16.1.1",
"@next/env": "16.1.6",
"@swc/helpers": "0.5.15",
"baseline-browser-mapping": "^2.8.3",
"caniuse-lite": "^1.0.30001579",
@@ -7573,14 +7573,14 @@
"node": ">=20.9.0"
},
"optionalDependencies": {
"@next/swc-darwin-arm64": "16.1.1",
"@next/swc-darwin-x64": "16.1.1",
"@next/swc-linux-arm64-gnu": "16.1.1",
"@next/swc-linux-arm64-musl": "16.1.1",
"@next/swc-linux-x64-gnu": "16.1.1",
"@next/swc-linux-x64-musl": "16.1.1",
"@next/swc-win32-arm64-msvc": "16.1.1",
"@next/swc-win32-x64-msvc": "16.1.1",
"@next/swc-darwin-arm64": "16.1.6",
"@next/swc-darwin-x64": "16.1.6",
"@next/swc-linux-arm64-gnu": "16.1.6",
"@next/swc-linux-arm64-musl": "16.1.6",
"@next/swc-linux-x64-gnu": "16.1.6",
"@next/swc-linux-x64-musl": "16.1.6",
"@next/swc-win32-arm64-msvc": "16.1.6",
"@next/swc-win32-x64-msvc": "16.1.6",
"sharp": "^0.34.4"
},
"peerDependencies": {