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", shipping_method: "standart",
payment_type_id: paymentType.id, payment_type_id: paymentType.id,
region: selectedRegion, region: selectedRegion,
note: note || undefined, notes: note || undefined,
}, },
{ {
onSuccess: () => { onSuccess: () => {

View File

@@ -44,72 +44,72 @@
} }
:root { :root {
--radius: 0.625rem; --radius: 1rem;
--background: #eff3f6; --background: #fafafa;
--foreground: oklch(0.141 0.005 285.823); --foreground: #0a0a0a;
--card: oklch(1 0 0); --card: #ffffff;
--card-foreground: oklch(0.141 0.005 285.823); --card-foreground: #0a0a0a;
--popover: oklch(1 0 0); --popover: #ffffff;
--popover-foreground: oklch(0.141 0.005 285.823); --popover-foreground: #0a0a0a;
--primary: oklch(0.21 0.006 285.885); --primary: #0a0a0a;
--primary-foreground: oklch(0.985 0 0); --primary-foreground: #ffffff;
--secondary: oklch(0.967 0.001 286.375); --secondary: #f5f5f5;
--secondary-foreground: oklch(0.21 0.006 285.885); --secondary-foreground: #0a0a0a;
--muted: oklch(0.967 0.001 286.375); --muted: #f5f5f5;
--muted-foreground: oklch(0.552 0.016 285.938); --muted-foreground: #737373;
--accent: oklch(0.967 0.001 286.375); --accent: #f5f5f5;
--accent-foreground: oklch(0.21 0.006 285.885); --accent-foreground: #0a0a0a;
--destructive: oklch(0.577 0.245 27.325); --destructive: #ef4444;
--border: oklch(0.92 0.004 286.32); --border: #e5e5e5;
--input: oklch(0.92 0.004 286.32); --input: #e5e5e5;
--ring: oklch(0.705 0.015 286.067); --ring: #0a0a0a;
--chart-1: oklch(0.646 0.222 41.116); --chart-1: #6366f1;
--chart-2: oklch(0.6 0.118 184.704); --chart-2: #8b5cf6;
--chart-3: oklch(0.398 0.07 227.392); --chart-3: #ec4899;
--chart-4: oklch(0.828 0.189 84.429); --chart-4: #f59e0b;
--chart-5: oklch(0.769 0.188 70.08); --chart-5: #10b981;
--sidebar: oklch(0.985 0 0); --sidebar: #ffffff;
--sidebar-foreground: oklch(0.141 0.005 285.823); --sidebar-foreground: #0a0a0a;
--sidebar-primary: oklch(0.21 0.006 285.885); --sidebar-primary: #0a0a0a;
--sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-primary-foreground: #ffffff;
--sidebar-accent: oklch(0.967 0.001 286.375); --sidebar-accent: #f5f5f5;
--sidebar-accent-foreground: oklch(0.21 0.006 285.885); --sidebar-accent-foreground: #0a0a0a;
--sidebar-border: oklch(0.92 0.004 286.32); --sidebar-border: #e5e5e5;
--sidebar-ring: oklch(0.705 0.015 286.067); --sidebar-ring: #0a0a0a;
} }
.dark { .dark {
--background: oklch(0.141 0.005 285.823); --background: #0a0a0a;
--foreground: oklch(0.985 0 0); --foreground: #fafafa;
--card: oklch(0.21 0.006 285.885); --card: #171717;
--card-foreground: oklch(0.985 0 0); --card-foreground: #fafafa;
--popover: oklch(0.21 0.006 285.885); --popover: #171717;
--popover-foreground: oklch(0.985 0 0); --popover-foreground: #fafafa;
--primary: oklch(0.92 0.004 286.32); --primary: #fafafa;
--primary-foreground: oklch(0.21 0.006 285.885); --primary-foreground: #0a0a0a;
--secondary: oklch(0.274 0.006 286.033); --secondary: #262626;
--secondary-foreground: oklch(0.985 0 0); --secondary-foreground: #fafafa;
--muted: oklch(0.274 0.006 286.033); --muted: #262626;
--muted-foreground: oklch(0.705 0.015 286.067); --muted-foreground: #a3a3a3;
--accent: oklch(0.274 0.006 286.033); --accent: #262626;
--accent-foreground: oklch(0.985 0 0); --accent-foreground: #fafafa;
--destructive: oklch(0.704 0.191 22.216); --destructive: #dc2626;
--border: oklch(1 0 0 / 10%); --border: #262626;
--input: oklch(1 0 0 / 15%); --input: #262626;
--ring: oklch(0.552 0.016 285.938); --ring: #fafafa;
--chart-1: oklch(0.488 0.243 264.376); --chart-1: #818cf8;
--chart-2: oklch(0.696 0.17 162.48); --chart-2: #a78bfa;
--chart-3: oklch(0.769 0.188 70.08); --chart-3: #f472b6;
--chart-4: oklch(0.627 0.265 303.9); --chart-4: #fbbf24;
--chart-5: oklch(0.645 0.246 16.439); --chart-5: #34d399;
--sidebar: oklch(0.21 0.006 285.885); --sidebar: #171717;
--sidebar-foreground: oklch(0.985 0 0); --sidebar-foreground: #fafafa;
--sidebar-primary: oklch(0.488 0.243 264.376); --sidebar-primary: #fafafa;
--sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-primary-foreground: #0a0a0a;
--sidebar-accent: oklch(0.274 0.006 286.033); --sidebar-accent: #262626;
--sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-accent-foreground: #fafafa;
--sidebar-border: oklch(1 0 0 / 10%); --sidebar-border: #262626;
--sidebar-ring: oklch(0.552 0.016 285.938); --sidebar-ring: #fafafa;
} }
@layer base { @layer base {
@@ -117,13 +117,52 @@
@apply border-border outline-ring/50; @apply border-border outline-ring/50;
} }
body { 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] { [data-sonner-toast] [data-description] {
color: #000 !important; color: #525252 !important;
opacity: 0.9; 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 { @layer utilities {
@@ -133,47 +172,109 @@
.bg-bg { .bg-bg {
background-color: var(--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-primary {
stroke: #005bff; stroke: #0a0a0a;
} }
.stroke-track { .stroke-track {
stroke: hsla(var(--hue), 10%, 10%, 0.1); stroke: rgba(10, 10, 10, 0.1);
transition: stroke var(--trans-dur); transition: stroke 0.3s ease;
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
.stroke-track { .stroke-track {
stroke: hsla(var(--hue), 10%, 90%, 0.1); stroke: rgba(250, 250, 250, 0.1);
} }
} }
.animate-msg { .animate-msg {
animation: msg 0.3s 13.7s linear forwards; animation: msg 0.3s 13.7s linear forwards;
} }
.animate-msgLast { .animate-msgLast {
animation: msg 0.3s 14s linear reverse forwards; animation: msg 0.3s 14s linear reverse forwards;
} }
.animate-cartLines { .animate-cartLines {
animation: cartLines 2s ease-in-out infinite; animation: cartLines 2s ease-in-out infinite;
} }
.animate-cartTop { .animate-cartTop {
animation: cartTop 2s ease-in-out infinite; animation: cartTop 2s ease-in-out infinite;
} }
.animate-cartWheel1 { .animate-cartWheel1 {
animation: cartWheel1 2s ease-in-out infinite; animation: cartWheel1 2s ease-in-out infinite;
transform: rotate(-0.25turn); transform: rotate(-0.25turn);
transform-origin: 43px 111px; transform-origin: 43px 111px;
} }
.animate-cartWheel2 { .animate-cartWheel2 {
animation: cartWheel2 2s ease-in-out infinite; animation: cartWheel2 2s ease-in-out infinite;
transform: rotate(0.25turn); transform: rotate(0.25turn);
transform-origin: 102px 111px; transform-origin: 102px 111px;
} }
.animate-cartWheelStroke { .animate-cartWheelStroke {
animation: cartWheelStroke 2s ease-in-out infinite; 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 { @keyframes msg {
from { from {
opacity: 1; opacity: 1;
@@ -188,6 +289,7 @@
visibility: hidden; visibility: hidden;
} }
} }
@keyframes cartLines { @keyframes cartLines {
from, from,
to { to {
@@ -198,6 +300,7 @@
opacity: 1; opacity: 1;
} }
} }
@keyframes cartTop { @keyframes cartTop {
from { from {
stroke-dashoffset: -338; stroke-dashoffset: -338;
@@ -209,6 +312,7 @@
stroke-dashoffset: 338; stroke-dashoffset: 338;
} }
} }
@keyframes cartWheel1 { @keyframes cartWheel1 {
from { from {
transform: rotate(-0.25turn); transform: rotate(-0.25turn);
@@ -217,6 +321,7 @@
transform: rotate(2.75turn); transform: rotate(2.75turn);
} }
} }
@keyframes cartWheel2 { @keyframes cartWheel2 {
from { from {
transform: rotate(0.25turn); transform: rotate(0.25turn);
@@ -225,6 +330,7 @@
transform: rotate(3.25turn); transform: rotate(3.25turn);
} }
} }
@keyframes cartWheelStroke { @keyframes cartWheelStroke {
from, from,
to { to {
@@ -234,3 +340,21 @@
stroke-dashoffset: 40.84; 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 ( return (
<> <>
<header className="sticky top-0 z-50 w-full border-b bg-white shadow-sm"> <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"> <div className="mx-auto px-4 lg:px-6 max-w-[1520px]">
<div className="flex h-16 items-center justify-between gap-3"> <div className="flex h-16 items-center justify-between gap-2 lg:gap-3">
<Link href="/" className="shrink-0"> {/* Logo */}
<Link
href="/"
className="shrink-0 transition-opacity hover:opacity-80"
>
<div className="relative h-8 w-[180px]"> <div className="relative h-8 w-[180px]">
<Image <Image
src={Logo} src={Logo}
@@ -69,38 +73,44 @@ export default function Header({ locale = "ru" }: HeaderProps) {
</div> </div>
</Link> </Link>
{/* Catalog Button - Desktop */}
<Button <Button
data-catalog-trigger data-catalog-trigger
onClick={toggleCategoryMenu} 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" size="lg"
> >
{isCategoryOpen ? <X className="h-5 w-5" /> : <CategoryIcon />} {isCategoryOpen ? <X className="h-5 w-5" /> : <CategoryIcon />}
{t("common.catalog")} {t("common.catalog")}
</Button> </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 <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
onClick={() => setIsMobileSearchOpen(true)} 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> </Button>
<LanguageSelector /> <LanguageSelector />
</div> </div>
{/* Desktop Language Selector */}
<div className="hidden sm:block"> <div className="hidden sm:block">
<LanguageSelector /> <LanguageSelector />
</div> </div>
{/* Desktop Search Bar */}
<SearchBar <SearchBar
isMobile={false} isMobile={false}
searchPlaceholder={t("common.search")} searchPlaceholder={t("common.search")}
className="hidden flex-1 md:flex" className="hidden flex-1 md:flex "
locale={locale} locale={locale}
/> />
{/* Action Buttons */}
<ActionButtons <ActionButtons
isAuthenticated={isAuthenticated} isAuthenticated={isAuthenticated}
onAuthClick={handleAuthClick} onAuthClick={handleAuthClick}

View File

@@ -9,11 +9,7 @@ import { useCart, useFavorites, useOrders, useCartCount } from "@/lib/hooks";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useLogout } from "@/lib/hooks/useAuth"; import { useLogout } from "@/lib/hooks/useAuth";
import { import { CartIcon, FavoriteIcon, OrderIcon } from "@/components/icons";
CartIcon,
FavoriteIcon,
OrderIcon,
} from "@/components/icons";
interface ActionButtonsProps { interface ActionButtonsProps {
isAuthenticated: boolean; isAuthenticated: boolean;
@@ -44,27 +40,24 @@ export default function ActionButtons({
const { data: favoritesData, isLoading: favoritesLoading } = useFavorites(); const { data: favoritesData, isLoading: favoritesLoading } = useFavorites();
const { data: ordersData, isLoading: ordersLoading } = useOrders(); 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(() => { const favoritesCount = useMemo(() => {
if (!favoritesData) return 0; if (!favoritesData) return 0;
return Array.isArray(favoritesData) ? favoritesData.length : 0; return Array.isArray(favoritesData) ? favoritesData.length : 0;
}, [favoritesData]); }, [favoritesData]);
// Calculate orders count
const ordersCount = useMemo(() => { const ordersCount = useMemo(() => {
if (!ordersData) return 0; if (!ordersData) return 0;
return Array.isArray(ordersData) ? ordersData.length : 0; return Array.isArray(ordersData) ? ordersData.length : 0;
}, [ordersData]); }, [ordersData]);
const handleLogout = () => { const handleLogout = () => {
logout(undefined, { logout(undefined, {
onSuccess: () => { onSuccess: () => {
router.push(`/${locale}`); router.push(`/${locale}`);
router.refresh(); router.refresh();
} },
}); });
}; };
@@ -100,50 +93,11 @@ const cartCount = useCartCount()
cartCount, cartCount,
cartLoading, cartLoading,
t, t,
] ],
); );
return ( return (
<div className="hidden items-center gap-1 lg:flex"> <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) => ( {buttons.map((button, index) => (
<ActionButton key={index} {...button} /> <ActionButton key={index} {...button} />
))} ))}
@@ -163,25 +117,28 @@ function ActionButton({
<Button <Button
variant="ghost" variant="ghost"
size="sm" 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} onClick={onClick}
> >
<div className="relative"> <div className="relative">
{icon} <div className="transition-transform duration-200 group-hover:scale-110">
{icon}
</div>
{badgeCount !== undefined && badgeCount > 0 && ( {badgeCount !== undefined && badgeCount > 0 && (
<Badge <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">
variant="destructive"
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
>
{isLoading ? ( {isLoading ? (
<Skeleton className="h-3 w-3 rounded-full" /> <Skeleton className="h-3 w-3 " />
) : badgeCount > 99 ? (
"99+"
) : ( ) : (
badgeCount badgeCount
)} )}
</Badge> </Badge>
)} )}
</div> </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> </Button>
); );

View File

@@ -5,6 +5,7 @@ import { useState, useEffect, useRef } from "react";
import Link from "next/link"; import Link from "next/link";
import { useCategories } from "@/lib/hooks"; import { useCategories } from "@/lib/hooks";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { ChevronRight } from "lucide-react";
interface CategoryMenuProps { interface CategoryMenuProps {
isOpen: boolean; isOpen: boolean;
@@ -16,25 +17,21 @@ export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
const { data: categories, isLoading } = useCategories(); const { data: categories, isLoading } = useCategories();
const menuRef = useRef<HTMLDivElement>(null); const menuRef = useRef<HTMLDivElement>(null);
// Click outside to close
useEffect(() => { useEffect(() => {
if (!isOpen) return; if (!isOpen) return;
const handleClickOutside = (event: MouseEvent) => { const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement; const target = event.target as HTMLElement;
if (target.closest("[data-catalog-trigger]")) { if (target.closest("[data-catalog-trigger]")) {
return; return;
} }
if (menuRef.current && !menuRef.current.contains(target)) { if (menuRef.current && !menuRef.current.contains(target)) {
onClose(); onClose();
} }
}; };
// Add listener after a small delay to prevent immediate closing
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
document.addEventListener("mousedown", handleClickOutside); document.addEventListener("mousedown", handleClickOutside);
}, 100); }, 100);
@@ -45,7 +42,6 @@ export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
}; };
}, [isOpen, onClose]); }, [isOpen, onClose]);
// ESC key to close
useEffect(() => { useEffect(() => {
if (!isOpen) return; if (!isOpen) return;
@@ -67,20 +63,25 @@ export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
return ( 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 */} {/* Menu */}
<div <div
ref={menuRef} 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"> <div className="flex">
<CategoryList <CategoryList
categories={categoryList} categories={categoryList}
isLoading={isLoading} isLoading={isLoading}
onCategoryHover={setHoveredCategory} onCategoryHover={setHoveredCategory}
onCategoryClick={onClose} onCategoryClick={onClose}
hoveredIndex={hoveredCategory}
/> />
{activeCategory?.children && ( {activeCategory?.children && (
@@ -101,6 +102,7 @@ interface CategoryListProps {
isLoading: boolean; isLoading: boolean;
onCategoryHover: (index: number) => void; onCategoryHover: (index: number) => void;
onCategoryClick: () => void; onCategoryClick: () => void;
hoveredIndex: number | null;
} }
function CategoryList({ function CategoryList({
@@ -108,13 +110,16 @@ function CategoryList({
isLoading, isLoading,
onCategoryHover, onCategoryHover,
onCategoryClick, onCategoryClick,
hoveredIndex,
}: CategoryListProps) { }: CategoryListProps) {
return ( return (
<div className="w-[280px] border-r"> <div className="w-[300px] border-r border-gray-200">
<div className="max-h-[calc(100vh-4rem)] overflow-y-auto py-2"> <div className="max-h-[calc(100vh-5rem)] overflow-y-auto py-3">
{isLoading {isLoading
? [1, 2, 3, 4, 5].map((i) => ( ? Array.from({ length: 8 }).map((_, i) => (
<Skeleton key={i} className="h-10 mx-4 my-2 rounded" /> <div key={i} className="mx-4 my-2">
<Skeleton className="h-12 rounded-lg" />
</div>
)) ))
: categories.map((category, index) => ( : categories.map((category, index) => (
<Link <Link
@@ -122,12 +127,31 @@ function CategoryList({
href={`/category/${category.slug}?category_id=${category.id}`} href={`/category/${category.slug}?category_id=${category.id}`}
onClick={onCategoryClick} onClick={onCategoryClick}
onMouseEnter={() => onCategoryHover(index)} 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"
}`}
> >
{category.icon_class && ( <div className="flex items-center gap-3">
<i className={`${category.icon_class} text-xl`} /> {category.icon_class && (
<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> </Link>
))} ))}
</div> </div>
@@ -145,17 +169,24 @@ function SubcategoryList({
onSubcategoryClick, onSubcategoryClick,
}: SubcategoryListProps) { }: SubcategoryListProps) {
return ( return (
<div className="flex-1 p-6"> <div className="flex-1 p-8 animate-fade-in">
<h3 className="text-xl font-semibold mb-4">{category.name}</h3> <div className="mb-6">
<div className="grid grid-cols-3 gap-4"> <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) => ( {category.children?.map((subCategory: any) => (
<Link <Link
key={subCategory.id} key={subCategory.id}
href={`/category/${subCategory.slug}?category_id=${subCategory.id}`} href={`/category/${subCategory.slug}?category_id=${subCategory.id}`}
onClick={onSubcategoryClick} 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> </Link>
))} ))}
</div> </div>

View File

@@ -43,17 +43,21 @@ export default function LanguageSelector() {
return ( return (
<Select value={locale} onValueChange={handleLanguageChange}> <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> <SelectValue>
<FlagIcon locale={locale} /> <FlagIcon locale={locale} />
</SelectValue> </SelectValue>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent className=" border-gray-200 shadow-lg">
{LANGUAGES.map((language) => ( {LANGUAGES.map((language) => (
<SelectItem key={language.code} value={language.code}> <SelectItem
<div className="flex items-center gap-2"> 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} /> <FlagIcon locale={language.code} />
<span>{language.name}</span> <span className="font-medium">{language.name}</span>
</div> </div>
</SelectItem> </SelectItem>
))} ))}
@@ -68,12 +72,12 @@ function FlagIcon({ locale }: { locale: string }) {
if (!language) return null; if (!language) return null;
return ( return (
<div className="relative h-5 w-7"> <div className="relative h-5 w-7 overflow-hidden shadow-sm">
<Image <Image
src={language.flag || "/placeholder.svg"} src={language.flag || "/placeholder.svg"}
alt={language.name} alt={language.name}
fill fill
className="object-cover rounded" className="object-cover"
/> />
</div> </div>
); );

View File

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

View File

@@ -20,7 +20,6 @@ interface CartItemCardProps {
onUpdate?: () => void; onUpdate?: () => void;
} }
// Session Storage Key
const PENDING_CART_UPDATES_KEY = "pendingCartUpdates"; const PENDING_CART_UPDATES_KEY = "pendingCartUpdates";
interface PendingUpdate { interface PendingUpdate {
@@ -32,39 +31,33 @@ interface PendingUpdate {
export default function CartItemCard({ item, onUpdate }: CartItemCardProps) { export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
const t = useTranslations(); const t = useTranslations();
// Local UI State (Instant feedback)
const [localQuantity, setLocalQuantity] = useState(item.quantity); const [localQuantity, setLocalQuantity] = useState(item.quantity);
// Sync State
const [isSyncing, setIsSyncing] = useState(false); const [isSyncing, setIsSyncing] = useState(false);
const [syncError, setSyncError] = useState(false); const [syncError, setSyncError] = useState(false);
// Stock limit modal
const [showStockModal, setShowStockModal] = useState(false); const [showStockModal, setShowStockModal] = useState(false);
// Refs
const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined); const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const isRequestInFlightRef = useRef(false); const isRequestInFlightRef = useRef(false);
const pendingQuantityRef = useRef<number | null>(null); const pendingQuantityRef = useRef<number | null>(null);
const retryCountRef = useRef(0); const retryCountRef = useRef(0);
const retryTimerRef = useRef<NodeJS.Timeout | undefined>(undefined); 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 syncToServerRef = useRef<((quantity: number) => void) | null>(null);
const retrySyncRef = useRef<((quantity: number) => void) | null>(null); const retrySyncRef = useRef<((quantity: number) => void) | null>(null);
const { mutate: updateQuantity } = useUpdateCartItemQuantity(); const { mutate: updateQuantity } = useUpdateCartItemQuantity();
const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart(); const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart();
// Get available stock
const availableStock = item.product.stock || 0; const availableStock = item.product.stock || 0;
// Initialize from server state
useEffect(() => { useEffect(() => {
setLocalQuantity(item.quantity); setLocalQuantity(item.quantity);
if (!isInitializedRef.current) {
isInitializedRef.current = true;
}
}, [item.quantity]); }, [item.quantity]);
// Save to sessionStorage
const savePendingUpdate = useCallback( const savePendingUpdate = useCallback(
(quantity: number) => { (quantity: number) => {
try { try {
@@ -90,7 +83,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
[item.product_id], [item.product_id],
); );
// Remove from sessionStorage
const clearPendingUpdate = useCallback(() => { const clearPendingUpdate = useCallback(() => {
try { try {
const stored = sessionStorage.getItem(PENDING_CART_UPDATES_KEY); const stored = sessionStorage.getItem(PENDING_CART_UPDATES_KEY);
@@ -112,7 +104,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
} }
}, [item.product_id]); }, [item.product_id]);
// Exponential backoff retry
const retrySync = useCallback((quantity: number) => { const retrySync = useCallback((quantity: number) => {
const maxRetries = 4; const maxRetries = 4;
const retryCount = retryCountRef.current; const retryCount = retryCountRef.current;
@@ -123,7 +114,7 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
return; 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++; retryCountRef.current++;
retryTimerRef.current = setTimeout(() => { retryTimerRef.current = setTimeout(() => {
@@ -131,19 +122,15 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
}, delay); }, delay);
}, []); }, []);
// Update ref
retrySyncRef.current = retrySync; retrySyncRef.current = retrySync;
// Sync to server
const syncToServer = useCallback( const syncToServer = useCallback(
(quantity: number) => { (quantity: number) => {
// If already syncing, queue this update
if (isRequestInFlightRef.current) { if (isRequestInFlightRef.current) {
pendingQuantityRef.current = quantity; pendingQuantityRef.current = quantity;
return; return;
} }
// Mark as syncing
isRequestInFlightRef.current = true; isRequestInFlightRef.current = true;
setIsSyncing(true); setIsSyncing(true);
setSyncError(false); setSyncError(false);
@@ -157,7 +144,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
clearPendingUpdate(); clearPendingUpdate();
onUpdate?.(); onUpdate?.();
// Process queued update if any
if (pendingQuantityRef.current !== null) { if (pendingQuantityRef.current !== null) {
const nextQuantity = pendingQuantityRef.current; const nextQuantity = pendingQuantityRef.current;
pendingQuantityRef.current = null; pendingQuantityRef.current = null;
@@ -181,7 +167,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
clearPendingUpdate(); clearPendingUpdate();
onUpdate?.(); onUpdate?.();
// Process queued update if any
if (pendingQuantityRef.current !== null) { if (pendingQuantityRef.current !== null) {
const nextQuantity = pendingQuantityRef.current; const nextQuantity = pendingQuantityRef.current;
pendingQuantityRef.current = null; pendingQuantityRef.current = null;
@@ -192,7 +177,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
console.error("Update failed:", error); console.error("Update failed:", error);
isRequestInFlightRef.current = false; isRequestInFlightRef.current = false;
// Rollback on error after retries exhausted
if (retryCountRef.current >= 3) { if (retryCountRef.current >= 3) {
setLocalQuantity(item.quantity); setLocalQuantity(item.quantity);
clearPendingUpdate(); clearPendingUpdate();
@@ -214,55 +198,29 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
], ],
); );
// Update ref
syncToServerRef.current = syncToServer; syncToServerRef.current = syncToServer;
// Load pending updates from sessionStorage on mount
useEffect(() => { useEffect(() => {
const loadPendingUpdates = () => { if (!isInitializedRef.current) {
try { return;
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,
);
}
}
} 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) { if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current); clearTimeout(debounceTimerRef.current);
} }
// If local quantity matches server, no sync needed
if (localQuantity === item.quantity) { if (localQuantity === item.quantity) {
return; return;
} }
// Save to sessionStorage immediately if (localQuantity <= 0 && item.quantity > 0) {
// Delete operation
} else if (localQuantity <= 0) {
return;
}
savePendingUpdate(localQuantity); savePendingUpdate(localQuantity);
// Debounce the API call
debounceTimerRef.current = setTimeout(() => { debounceTimerRef.current = setTimeout(() => {
syncToServerRef.current?.(localQuantity); syncToServerRef.current?.(localQuantity);
}, 800); }, 800);
@@ -274,7 +232,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
}; };
}, [localQuantity, item.quantity, savePendingUpdate]); }, [localQuantity, item.quantity, savePendingUpdate]);
// Cleanup
useEffect(() => { useEffect(() => {
return () => { return () => {
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current); if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
@@ -286,13 +243,11 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
// Check stock limit
if (localQuantity >= availableStock) { if (localQuantity >= availableStock) {
setShowStockModal(true); setShowStockModal(true);
return; return;
} }
// Optimistic update (instant UI feedback)
setLocalQuantity((prev) => prev + 1); setLocalQuantity((prev) => prev + 1);
}; };
@@ -305,7 +260,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
return; return;
} }
// Optimistic update (instant UI feedback)
setLocalQuantity((prev) => prev - 1); setLocalQuantity((prev) => prev - 1);
}; };
@@ -323,49 +277,70 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
return ( return (
<> <>
<Card className="p-4 shadow-none border"> <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-4"> <div className="flex flex-col sm:flex-row gap-6">
{/* Product Image & Info */}
<div className="flex gap-4 flex-1"> <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 <Image
src={getImageSrc()} src={getImageSrc()}
alt={item.product.name} alt={item.product.name}
fill fill
className="object-contain" className="object-contain p-2"
/> />
</div> </div>
<div className="flex flex-col gap-2"> <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 <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={handleDelete} onClick={handleDelete}
disabled={isRemoving} 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> </Button>
</div> </div>
</div> </div>
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between"> {/* Price & Quantity */}
<div className="space-y-1"> <div className="flex flex-col sm:flex-row items-start sm:items-center gap-6 justify-between">
<p className="text-sm font-semibold"> <div className="space-y-2">
<p className="text-sm font-medium text-gray-600">
{t("unit_price")}{" "} {t("unit_price")}{" "}
<span className="text-primary">{item.price_formatted}</span> <span className="text-gray-900 font-bold">
{item.price_formatted}
</span>
</p> </p>
{item.discount_formatted && {item.discount_formatted &&
item.discount_formatted !== "0 TMT" && ( 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} {t("discount")} {item.discount_formatted}
</p> </p>
)} )}
<div className="flex items-center gap-2"> <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")} {t("total_price")}
</span> </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 parseFloat(item.product.price_amount || "0") * localQuantity
).toFixed(2)}{" "} ).toFixed(2)}{" "}
@@ -374,23 +349,31 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> {/* Quantity Controls */}
<div className="flex items-center gap-3">
<Button <Button
variant="outline" variant="outline"
size="icon" size="icon"
onClick={handleQuantityDecrease} onClick={handleQuantityDecrease}
className={` cursor-pointer rounded-lg bg-blue-50 ${ disabled={isSyncing}
isSyncing ? "opacity-70" : "" 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> </Button>
<div className="w-12 text-center font-semibold relative"> <div className="min-w-[48px] text-center font-bold text-lg relative">
{localQuantity} {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 && ( {syncError && (
<span <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" title="Sync error"
/> />
)} )}
@@ -400,16 +383,16 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
variant="outline" variant="outline"
size="icon" size="icon"
onClick={handleQuantityIncrease} onClick={handleQuantityIncrease}
// disabled={localQuantity >= availableStock} disabled={isSyncing || localQuantity >= availableStock}
className={`rounded-lg cursor-pointer bg-blue-50 ${ className={`rounded-[10px] h-10 w-10 cursor-pointer border-2 transition-all duration-200 ${
isSyncing ? "opacity-70" : ""
} ${
localQuantity >= availableStock 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> </Button>
</div> </div>
</div> </div>
@@ -418,27 +401,27 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
{/* Stock Limit Modal */} {/* Stock Limit Modal */}
<Dialog open={showStockModal} onOpenChange={setShowStockModal}> <Dialog open={showStockModal} onOpenChange={setShowStockModal}>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md rounded-3xl border-gray-200">
<DialogHeader> <DialogHeader>
<div className="flex items-center justify-center mb-4"> <div className="flex items-center justify-center mb-4">
<div className="rounded-full bg-orange-100 p-3"> <div className="rounded-full bg-amber-100 p-4">
<AlertTriangle className="h-6 w-6 text-orange-600" /> <AlertTriangle className="h-7 w-7 text-amber-600" />
</div> </div>
</div> </div>
<DialogTitle className="text-center text-xl"> <DialogTitle className="text-center text-2xl font-bold text-gray-900">
{t("stock_limit_title")} {t("stock_limit_title")}
</DialogTitle> </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", { {t("stock_limit_message", {
product: item.product.name, product: item.product.name,
stock: availableStock, stock: availableStock,
})} })}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="flex justify-center mt-4"> <div className="flex justify-center mt-6">
<Button <Button
onClick={() => setShowStockModal(false)} 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")} {t("understood")}
</Button> </Button>

View File

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

View File

@@ -4,24 +4,28 @@ import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
export default function EmptyCart() { export default function EmptyCart() {
const t=useTranslations(); const t = useTranslations();
const router=useRouter(); const router = useRouter();
return ( return (
<div className="flex min-h-[60vh] items-center justify-center px-4"> <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="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-6 flex h-20 w-20 items-center justify-center rounded-full bg-blue-100"> <div className="mx-auto mb-8 flex h-24 w-24 items-center justify-center rounded-full bg-gray-100">
<ShoppingCart className="h-10 w-10 text-blue-600" /> <ShoppingCart className="h-12 w-12 text-gray-700" />
</div> </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")} {t("cart_empty")}
</h2> </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")} {t("cart_empty_message")}
</p> </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")} {t("start_shopping")}
</Button> </Button>
</div> </div>

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,16 @@
import { useState, useEffect, useRef, useCallback } from "react"; import { useState, useEffect, useRef, useCallback } from "react";
import Image from "next/image"; import Image from "next/image";
import {
X,
ZoomIn,
ZoomOut,
RotateCw,
RotateCcw,
Maximize2,
ChevronLeft,
ChevronRight,
} from "lucide-react";
import { useTranslations } from "next-intl";
interface ProductImageGalleryProps { interface ProductImageGalleryProps {
images: string[]; images: string[];
productName: string; productName: string;
@@ -13,10 +23,22 @@ export function ProductImageGallery({
noImageText, noImageText,
}: ProductImageGalleryProps) { }: ProductImageGalleryProps) {
const [selectedImage, setSelectedImage] = useState(0); 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 autoplayTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const modalImageRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
if (images.length <= 1) return; setSelectedImage(0);
}, [images]);
useEffect(() => {
if (images.length <= 1 || isModalOpen) return;
const startAutoplay = () => { const startAutoplay = () => {
autoplayTimerRef.current = setInterval(() => { autoplayTimerRef.current = setInterval(() => {
@@ -28,63 +50,417 @@ export function ProductImageGallery({
return () => { return () => {
if (autoplayTimerRef.current) clearInterval(autoplayTimerRef.current); 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( const handleImageSelect = useCallback(
(index: number) => { (index: number) => {
setSelectedImage(index); setSelectedImage(index);
if (autoplayTimerRef.current) clearInterval(autoplayTimerRef.current); if (autoplayTimerRef.current) clearInterval(autoplayTimerRef.current);
if (images.length > 1) { if (images.length > 1 && !isModalOpen) {
autoplayTimerRef.current = setInterval(() => { autoplayTimerRef.current = setInterval(() => {
setSelectedImage((prev) => (prev + 1) % images.length); setSelectedImage((prev) => (prev + 1) % images.length);
}, 3000); }, 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 ( return (
<div className="contents max-w-2xl"> <>
<div className="relative"> <div className="w-full lg:flex-1 max-w-2xl">
<div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-white"> <div className="relative">
{images.length > 0 ? ( <div
<Image 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"
src={images[selectedImage]} onClick={openModal}
alt={productName} >
fill {images.length > 0 && images[selectedImage] ? (
className="object-contain" <>
priority <Image
/> src={images[selectedImage]}
) : ( alt={productName}
<div className="flex items-center justify-center h-full text-gray-400"> fill
{noImageText} 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 text-sm md:text-base">
{noImageText}
</div>
)}
</div>
{images.length > 1 && (
<div className="mt-4 flex gap-2 overflow-x-auto pb-2">
{images.map((image, index) => (
<button
key={index}
onClick={() => handleImageSelect(index)}
className={`relative w-16 h-16 shrink-0 rounded cursor-pointer overflow-hidden border-2 transition-all ${
selectedImage === index
? "border-primary ring-2 ring-primary/20"
: "border-gray-200 hover:border-gray-300"
}`}
>
<Image
src={image}
alt={`${productName} ${index + 1}`}
fill
className="object-cover"
/>
</button>
))}
</div> </div>
)} )}
</div> </div>
</div>
{images.length > 1 && ( {/* Modal */}
<div className="mt-4 flex gap-2 overflow-x-auto pb-2"> {isModalOpen && (
{images.map((image, index) => ( <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 <button
key={index} onClick={closeModal}
onClick={() => handleImageSelect(index)} 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"
className={`relative w-16 h-16 shrink-0 rounded cursor-pointer overflow-hidden border-2 transition-all ${ aria-label="Close"
selectedImage === index >
? "border-primary ring-2 ring-primary/20" <X className="w-4 h-4 md:w-5 md:h-5 text-white" />
: "border-gray-200 hover:border-gray-300" </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 <Image
src={image} src={images[selectedImage]}
alt={`${productName} ${index + 1}`} alt={productName}
fill fill
className="object-cover" 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> </button>
))} )}
</div> </div>
)}
</div> {/* Bottom Control Bar */}
</div> <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 { Card } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { Star } from "lucide-react"; import { Star, Package, Tag, Palette } from "lucide-react";
interface ProductProperty { interface ProductProperty {
name: string; name: string;
@@ -33,38 +33,76 @@ export function ProductInfoCard({
t, t,
}: ProductInfoCardProps) { }: ProductInfoCardProps) {
return ( return (
<div className="flex-1 space-y-6 bg-white"> <div className="flex-1 space-y-6 bg-transparent">
<Card className="p-4 rounded-xl border-gray-200"> {/* Main Info Card */}
<h3 className="text-xl font-semibold mb-4">{name}</h3> <Card className="p-6 rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-300 gap-0">
<div className="space-y-3"> <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 && ( {brandName && (
<> <>
<div className="flex justify-between items-center py-2"> <div className="flex justify-between items-center py-3.5 px-4 rounded-xl hover:bg-gray-50 transition-colors group">
<span className="text-gray-500">{t("brands")}</span> <div className="flex items-center gap-3">
<span className="font-medium">{brandName}</span> <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>
<span className="text-gray-600 font-medium">
{t("brands")}
</span>
</div>
<span className="font-semibold text-gray-900">{brandName}</span>
</div> </div>
<Separator /> <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 && ( {colour && (
<> <>
<div className="flex justify-between items-center py-2"> <div className="flex justify-between items-center py-3.5 px-4 rounded-xl hover:bg-gray-50 transition-colors group">
<span className="text-gray-500">{t("color")}</span> <div className="flex items-center gap-3">
<span className="font-medium">{colour}</span> <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>
<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> </div>
<Separator /> <Separator className="bg-gray-100" />
</> </>
)} )}
@@ -74,26 +112,62 @@ export function ProductInfoCard({
(prop, idx) => (prop, idx) =>
prop.value && ( prop.value && (
<div key={idx}> <div key={idx}>
<div className="flex justify-between items-center py-2"> <div className="flex justify-between items-center py-3.5 px-4 rounded-xl hover:bg-gray-50 transition-colors group">
<span className="text-gray-500">{prop.name}</span> <div className="flex items-center gap-3">
<span className="font-medium">{prop.value}</span> <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>
<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> </div>
{idx < properties.length - 1 && <Separator />} {idx < properties.length - 1 && (
<Separator className="bg-gray-100" />
)}
</div> </div>
) ),
)} )}
</> </>
)} )}
</div> </div>
</Card> </Card>
{/* Description Card */}
{description && ( {description && (
<Card className="p-4 rounded-xl border-gray-200 gap-2"> <Card className="p-8 rounded-3xl border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-300">
<h3 className="text-xl font-semibold mb-3"> <div className="flex items-center gap-3 mb-6">
{t("product_description")} <div className="h-10 w-10 rounded-xl bg-gray-900 flex items-center justify-center">
</h3> <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 <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 }} dangerouslySetInnerHTML={{ __html: description }}
/> />
</Card> </Card>

View File

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

View File

@@ -38,122 +38,150 @@ export function ProductPurchaseCard({
onToggleFavorite, onToggleFavorite,
t, t,
}: ProductPurchaseCardProps) { }: ProductPurchaseCardProps) {
const isOutOfStock = productStock === 0;
return ( return (
<div className="lg:w-[380px] space-y-4"> <div className="lg:w-[420px] space-y-4">
<Card className="p-6 rounded-xl"> <Card className="p-6 rounded-lg border border-gray-200 shadow-lg hover:shadow-xl transition-shadow duration-300">
<div className="flex justify-between items-start mb-6"> {/* Price Section */}
<span className="text-lg text-gray-500">{t("price")}:</span> <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"> <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 && ( {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 {oldPrice} TMT
</span> </span>
)} )}
</div> </div>
</div> </div>
<div className="space-y-2"> {/* Action Buttons Section */}
<div className="space-y-3">
{isInCart ? ( {isInCart ? (
<> <>
{/* Go to Cart Button */}
<Link href="/cart"> <Link href="/cart">
<Button <Button
size="lg" 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" /> <ShoppingCart className="mr-2 h-5 w-5" />
{t("go_to_cart")} {t("go_to_cart")}
</Button> </Button>
</Link> </Link>
<div className="flex items-center gap-2"> {/* Quantity Controls */}
<div className="flex items-center gap-3 pt-2">
<Button <Button
variant="outline" variant="outline"
size="icon" size="icon"
onClick={onQuantityDecrease} onClick={onQuantityDecrease}
disabled={isSyncing} disabled={isSyncing}
className={`rounded-lg cursor-pointer h-12 w-12 ${ 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-70" : "" isSyncing ? "opacity-50" : ""
}`} }`}
> >
<Minus className="h-5 w-5" /> <Minus className="h-5 w-5 text-gray-700" />
</Button> </Button>
<div className="flex-1 text-center font-semibold text-xl border rounded-xl h-12 flex items-center justify-center relative">
{localQuantity} <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 && ( {syncError && (
<span <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" title="Sync error"
/> />
)} )}
</div> </div>
<Button <Button
variant="outline" variant="outline"
size="icon" size="icon"
onClick={onQuantityIncrease} onClick={onQuantityIncrease}
disabled={isSyncing} disabled={isSyncing || localQuantity >= availableStock}
className={`rounded-lg cursor-pointer h-12 w-12 ${ 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-70" : "" isSyncing ? "opacity-50" : ""
}`} }`}
> >
<Plus className="h-5 w-5" /> <Plus className="h-5 w-5 text-white" />
</Button> </Button>
{/* Favorite Button - In Cart */}
<Button <Button
variant="outline" variant="outline"
size="icon" size="icon"
onClick={onToggleFavorite} 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 isFavorite
? "bg-[#F0F8FF] border-blue-300 hover:bg-blue-100" ? "bg-rose-50 border-rose-200 hover:bg-rose-100 hover:border-rose-300"
: "hover:bg-gray-50" : "border-gray-200 hover:border-gray-900 hover:bg-gray-50"
}`} }`}
> >
<Heart <Heart
className={`h-6! w-6! transition-all ${ className={`h-6 w-6 transition-all duration-200 ${
isFavorite isFavorite
? "fill-[#005bff] text-[#005bff]" ? "fill-rose-500 text-rose-500 scale-110"
: "text-[#005bff]" : "text-gray-700 hover:text-rose-500"
}`} }`}
/> />
</Button> </Button>
</div> </div>
</> </>
) : ( ) : (
<div className="flex items-center gap-2"> <div className="flex items-center gap-3">
{/* Add to Cart Button */}
<Button <Button
size="lg" size="lg"
onClick={onAddToCart} onClick={onAddToCart}
disabled={isSyncing || productStock === 0} disabled={isSyncing || isOutOfStock}
className="flex-1 rounded-lg text-lg font-bold bg-[#005bff] hover:bg-[#0041c4] cursor-pointer" 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 ? ( {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" /> <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> </Button>
{/* Favorite Button - Not in Cart */}
<Button <Button
variant="outline" variant="outline"
size="icon" size="icon"
onClick={onToggleFavorite} 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 isFavorite
? "bg-[#F0F8FF] border-blue-300 hover:bg-blue-100" ? "bg-rose-50 border-rose-200 hover:bg-rose-100 hover:border-rose-300"
: "hover:bg-gray-50" : "border-gray-200 hover:border-gray-900 hover:bg-gray-50"
}`} }`}
> >
<Heart <Heart
className={`h-6! w-6! transition-all ${ className={`h-6 w-6 transition-all duration-200 ${
isFavorite isFavorite
? "fill-[#005bff] text-[#005bff]" ? "fill-rose-500 text-rose-500 scale-110"
: "text-[#005bff]" : "text-gray-700 hover:text-rose-500"
}`} }`}
/> />
</Button> </Button>
@@ -161,8 +189,6 @@ export function ProductPurchaseCard({
)} )}
</div> </div>
</Card> </Card>
</div> </div>
); );
} }

View File

@@ -1,6 +1,10 @@
// lib/api.ts // 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"; import TokenStorage from "./tokenStorage";
const localeToApiLang = (locale: string): string => { const localeToApiLang = (locale: string): string => {
@@ -42,27 +46,32 @@ class APIClient {
config.headers.Authorization = `Bearer ${token}`; config.headers.Authorization = `Bearer ${token}`;
} }
// Add language parameter // Add language parameter (except for POST requests to /orders)
let lang = "tm"; const url = config.url || "";
const isOrderPost =
config.method?.toLowerCase() === "post" && url.includes("/orders");
if (typeof window !== "undefined") { if (!isOrderPost) {
if ((window as any).i18n?.language) { let lang = "tm";
lang = localeToApiLang((window as any).i18n.language);
} else { if (typeof window !== "undefined") {
const pathLocale = window.location.pathname.split("/")[1]; if ((window as any).i18n?.language) {
if (pathLocale === "tm" || pathLocale === "ru") { lang = localeToApiLang((window as any).i18n.language);
lang = localeToApiLang(pathLocale); } else {
const pathLocale = window.location.pathname.split("/")[1];
if (pathLocale === "tm" || pathLocale === "ru") {
lang = localeToApiLang(pathLocale);
}
} }
} }
}
const url = config.url || ""; const separator = url.includes("?") ? "&" : "?";
const separator = url.includes("?") ? "&" : "?"; config.url = `${url}${separator}lang=${lang}`;
config.url = `${url}${separator}lang=${lang}`; }
return config; return config;
}, },
(error) => Promise.reject(error) (error) => Promise.reject(error),
); );
// Response interceptor // Response interceptor
@@ -92,10 +101,11 @@ class APIClient {
"Content-Type": "application/json", "Content-Type": "application/json",
"Api-Token": process.env.NEXT_PUBLIC_API_TOKEN || "123", "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) { if (newToken) {
TokenStorage.setGuestToken(newToken); TokenStorage.setGuestToken(newToken);
@@ -131,7 +141,7 @@ class APIClient {
} }
return Promise.reject(error); return Promise.reject(error);
} },
); );
} }
@@ -146,23 +156,41 @@ class APIClient {
this.failedQueue = []; 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); 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); 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); 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); 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); return this.client.delete<T>(url, config);
} }
} }

View File

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

82
package-lock.json generated
View File

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