added empty pages
This commit is contained in:
@@ -14,7 +14,7 @@ import { userStore } from "@/features/profile/userStore";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { DeliveryType, PaymentType } from "@/lib/types/api";
|
||||
|
||||
import EmptyCart from "@/features/cart/components/EmptyCart";
|
||||
export default function CartPage() {
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
const [paymentType, setPaymentType] = useState<PaymentType | null>(null);
|
||||
@@ -129,21 +129,11 @@ export default function CartPage() {
|
||||
|
||||
if (!isClient) return null;
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 min-h-[90vh] flex items-center justify-center">
|
||||
<p>{t("common.loading")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
if (isError || cartItems.length === 0) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 min-h-[90vh] flex items-center justify-center">
|
||||
<h2 className="text-3xl md:text-4xl lg:text-5xl text-gray-400 font-semibold">
|
||||
{t("cart_empty")}
|
||||
</h2>
|
||||
</div>
|
||||
<EmptyCart/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useTranslations } from "next-intl";
|
||||
import ProductCard from "@/features/home/components/ProductCard";
|
||||
import type { Favorite } from "@/lib/types/api";
|
||||
|
||||
import EmptyFavorites from "@/features/favorites/components/EmptyFavorites";
|
||||
export default function FavoritesPage() {
|
||||
const t = useTranslations();
|
||||
const { data: favorites, isLoading, isError } = useFavorites();
|
||||
@@ -25,12 +25,7 @@ export default function FavoritesPage() {
|
||||
|
||||
if (isError || !favorites || favorites.length === 0) {
|
||||
return (
|
||||
<div className="container mx-auto px-6 py-8 bg-white">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("favorite_products")}</h1>
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<p className="text-2xl text-gray-400">{t("empty_favorites")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<EmptyFavorites/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,10 +12,9 @@ import AuthDialog from "./ui/AuthDialog";
|
||||
import ActionButtons from "./ui/ActionButtons";
|
||||
import LanguageSelector from "./ui/LanguageSelector";
|
||||
import MobileBottomNav from "./MobileBar";
|
||||
import { useAuthStatus, useLogout } from "@/lib/hooks/useAuth";
|
||||
import { useAuthStatus } from "@/lib/hooks/useAuth";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { CategoryIcon } from "../icons";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
interface HeaderProps {
|
||||
locale?: string;
|
||||
@@ -27,10 +26,10 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
|
||||
const [isLoginOpen, setIsLoginOpen] = useState(false);
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
|
||||
|
||||
const { isAuthenticated, isLoading } = useAuthStatus();
|
||||
const { mutate: logout, isPending: isLoggingOut } = useLogout();
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
setIsClient(true);
|
||||
@@ -44,9 +43,7 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
}
|
||||
}, [isAuthenticated, locale]);
|
||||
|
||||
const handleLogout = useCallback(() => {
|
||||
logout();
|
||||
}, [logout]);
|
||||
|
||||
|
||||
const toggleCategoryMenu = useCallback(() => {
|
||||
setIsCategoryOpen((prev) => !prev);
|
||||
@@ -56,9 +53,7 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
setIsCategoryOpen(false);
|
||||
}, []);
|
||||
|
||||
const handleProfileClick = useCallback(() => {
|
||||
router.push(`/${locale}/me`);
|
||||
}, [router, locale]);
|
||||
|
||||
|
||||
if (!isClient) return null;
|
||||
|
||||
@@ -133,7 +128,10 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
<MobileBottomNav
|
||||
locale={locale}
|
||||
|
||||
onLoginClick={() => setIsLoginOpen(true)}
|
||||
onLoginClick={() => {
|
||||
console.log('[Header] Opening login dialog');
|
||||
setIsLoginOpen(true);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -12,10 +12,13 @@ import {
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { useCategories, useCart, useFavorites, useOrders } from "@/lib/hooks";
|
||||
import { useCategories, useFavorites, useOrders } from "@/lib/hooks";
|
||||
import { useCartCount } from "@/features/cart/hooks/useCart";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuthStatus } from "@/lib/hooks/useAuth";
|
||||
import { useTranslations } from "next-intl";
|
||||
import AuthDialog from "./ui/AuthDialog";
|
||||
|
||||
interface MobileBottomNavProps {
|
||||
locale?: string;
|
||||
translations?: {
|
||||
@@ -36,29 +39,33 @@ export default function MobileBottomNav({
|
||||
}: MobileBottomNavProps) {
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
const [isCategoryOpen, setIsCategoryOpen] = useState(false);
|
||||
const t = useTranslations();
|
||||
// AUTH STATE DIRECTLY FROM HOOK - NOT FROM PROPS
|
||||
const [isLoginOpen, setIsLoginOpen] = useState(false);
|
||||
const t = useTranslations();
|
||||
|
||||
const { isAuthenticated, isLoading: authLoading } = useAuthStatus();
|
||||
|
||||
const { data: categories = [] } = useCategories();
|
||||
const { data: cartData } = useCart();
|
||||
|
||||
// OPTIMIZED: Use event-driven cart count instead of full cart data
|
||||
const cartCount = useCartCount();
|
||||
|
||||
const { data: favoritesData } = useFavorites();
|
||||
const { data: ordersData } = useOrders();
|
||||
const router = useRouter();
|
||||
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
setIsClient(true);
|
||||
}, []);
|
||||
|
||||
|
||||
|
||||
const handleProfileClick = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
|
||||
console.log("[MobileBottomNav] Profile clicked", {
|
||||
authLoading,
|
||||
isAuthenticated,
|
||||
hasOnLoginClick: !!onLoginClick,
|
||||
});
|
||||
|
||||
if (authLoading) {
|
||||
return;
|
||||
@@ -68,7 +75,11 @@ export default function MobileBottomNav({
|
||||
router.push(`/${locale}/me`);
|
||||
} else {
|
||||
if (onLoginClick) {
|
||||
console.log("[MobileBottomNav] Calling parent onLoginClick");
|
||||
onLoginClick();
|
||||
} else {
|
||||
console.log("[MobileBottomNav] Using local login dialog");
|
||||
setIsLoginOpen(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -109,14 +120,18 @@ export default function MobileBottomNav({
|
||||
>
|
||||
<div className="relative">
|
||||
<Heart className="h-5 w-5 text-gray-600" />
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{favoritesData?.length || 0}
|
||||
</Badge>
|
||||
{(favoritesData?.length || 0) > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{favoritesData?.length}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-gray-700">{t("common.favorites")}</span>
|
||||
<span className="text-xs text-gray-700">
|
||||
{t("common.favorites")}
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
{/* Orders Button */}
|
||||
@@ -128,17 +143,19 @@ export default function MobileBottomNav({
|
||||
>
|
||||
<div className="relative">
|
||||
<Truck className="h-5 w-5 text-gray-600" />
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{ordersData?.length || 0}
|
||||
</Badge>
|
||||
{(ordersData?.length || 0) > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{ordersData?.length}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-gray-700">{t("common.orders")}</span>
|
||||
</Button>
|
||||
|
||||
{/* Cart Button */}
|
||||
{/* Cart Button - OPTIMIZED */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -147,12 +164,14 @@ export default function MobileBottomNav({
|
||||
>
|
||||
<div className="relative">
|
||||
<ShoppingCart className="h-5 w-5 text-gray-600" />
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{cartData?.data?.length || 0}
|
||||
</Badge>
|
||||
{cartCount > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{cartCount}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-gray-700">{t("common.cart")}</span>
|
||||
</Button>
|
||||
@@ -167,7 +186,11 @@ export default function MobileBottomNav({
|
||||
>
|
||||
<User className="h-5 w-5 text-gray-600" />
|
||||
<span className="text-xs text-gray-700">
|
||||
{authLoading ? "..." : (isAuthenticated ? t("profile") : t("login"))}
|
||||
{authLoading
|
||||
? "..."
|
||||
: isAuthenticated
|
||||
? t("common.profile")
|
||||
: t("common.login")}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
@@ -212,6 +235,9 @@ export default function MobileBottomNav({
|
||||
</ScrollArea>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Local Auth Dialog */}
|
||||
<AuthDialog isOpen={isLoginOpen} onClose={() => setIsLoginOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useCart, useFavorites, useOrders } from "@/lib/hooks";
|
||||
import { useCart, useFavorites, useOrders, useCartCount } from "@/lib/hooks";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLogout } from "@/lib/hooks/useAuth";
|
||||
@@ -53,10 +53,7 @@ export default function ActionButtons({
|
||||
const { data: ordersData, isLoading: ordersLoading } = useOrders();
|
||||
|
||||
// Calculate cart count from cart items array
|
||||
const cartCount = useMemo(() => {
|
||||
if (!cartData?.data) return 0;
|
||||
return cartData.data.length;
|
||||
}, [cartData]);
|
||||
const cartCount = useCartCount()
|
||||
|
||||
// Calculate favorites count
|
||||
const favoritesCount = useMemo(() => {
|
||||
|
||||
@@ -14,7 +14,7 @@ function Checkbox({
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
"peer border-[#0041c4] dark:bg-input/30 data-[state=checked]:bg-[#005bff] data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-[#0041c4] focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -45,7 +45,7 @@ function Slider({
|
||||
<SliderPrimitive.Range
|
||||
data-slot="slider-range"
|
||||
className={cn(
|
||||
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
|
||||
"bg-[#005bff] absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
|
||||
)}
|
||||
/>
|
||||
</SliderPrimitive.Track>
|
||||
|
||||
@@ -1,32 +1,30 @@
|
||||
import { ShoppingCart } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ShoppingCart } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
interface EmptyCartProps {
|
||||
locale?: string
|
||||
message?: string
|
||||
actionText?: string
|
||||
actionHref?: string
|
||||
}
|
||||
|
||||
export default function EmptyCart({
|
||||
locale = "ru",
|
||||
message = "Your cart is empty",
|
||||
actionText = "Start Shopping",
|
||||
actionHref = "/",
|
||||
}: EmptyCartProps) {
|
||||
export default function EmptyCart() {
|
||||
const t=useTranslations();
|
||||
const router=useRouter();
|
||||
return (
|
||||
<div className="min-h-[400px] flex flex-col items-center justify-center p-4">
|
||||
<ShoppingCart className="h-16 w-16 text-gray-300 mb-4" />
|
||||
<h2 className="text-2xl font-semibold text-gray-600 mb-2">{message}</h2>
|
||||
<p className="text-gray-500 mb-6 text-center max-w-sm">
|
||||
{locale === "ru"
|
||||
? "Добавьте товары в корзину, чтобы начать покупки"
|
||||
: "Add items to your cart to start shopping"}
|
||||
</p>
|
||||
<Link href={actionHref}>
|
||||
<Button className="rounded-xl">{actionText}</Button>
|
||||
</Link>
|
||||
<div className="flex min-h-[60vh] items-center justify-center px-4">
|
||||
<div className="w-full max-w-md rounded-2xl bg-gradient-to-br from-blue-50 to-white p-8 text-center shadow-lg">
|
||||
<div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-blue-100">
|
||||
<ShoppingCart className="h-10 w-10 text-blue-600" />
|
||||
</div>
|
||||
|
||||
<h2 className="mb-2 text-2xl font-semibold text-gray-900">
|
||||
{t("cart_empty")}
|
||||
</h2>
|
||||
|
||||
<p className="mb-6 text-sm text-gray-500">
|
||||
{t("cart_empty_message")}
|
||||
</p>
|
||||
|
||||
<Button onClick={()=>router.push("/")} className="w-full rounded-xl bg-blue-600 px-6 py-3 text-sm font-medium text-white transition hover:bg-blue-700 active:scale-95">
|
||||
{t("start_shopping")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -1,148 +1,277 @@
|
||||
import { useQuery, useMutation, useQueryClient, UseQueryOptions } from "@tanstack/react-query"
|
||||
import { apiClient } from "@/lib/api"
|
||||
import type { CartItem } from "@/lib/types/api"
|
||||
import {
|
||||
useQuery,
|
||||
useMutation,
|
||||
useQueryClient,
|
||||
UseQueryOptions,
|
||||
} from "@tanstack/react-query";
|
||||
import { apiClient } from "@/lib/api";
|
||||
import type { CartItem } from "@/lib/types/api";
|
||||
import { useEffect } from "react";
|
||||
|
||||
interface CartResponse {
|
||||
message: string
|
||||
data: CartItem[]
|
||||
errorDetails?: string
|
||||
message: string;
|
||||
data: CartItem[];
|
||||
errorDetails?: string;
|
||||
}
|
||||
|
||||
// Transform response to handle HTML/malformed responses
|
||||
// Event emitter for cross-component cart updates
|
||||
class CartEventEmitter {
|
||||
private listeners: Set<() => void> = new Set();
|
||||
|
||||
subscribe(callback: () => void) {
|
||||
this.listeners.add(callback);
|
||||
return () => this.listeners.delete(callback);
|
||||
}
|
||||
|
||||
emit() {
|
||||
this.listeners.forEach((cb) => cb());
|
||||
}
|
||||
}
|
||||
|
||||
export const cartEvents = new CartEventEmitter();
|
||||
|
||||
function transformCartResponse(response: any): CartResponse {
|
||||
if (
|
||||
typeof response === "string" &&
|
||||
(response.trim().startsWith("<!DOCTYPE") || response.trim().startsWith("<html"))
|
||||
(response.trim().startsWith("<!DOCTYPE") ||
|
||||
response.trim().startsWith("<html"))
|
||||
) {
|
||||
console.error("Received HTML response instead of JSON:", response.substring(0, 100))
|
||||
console.error(
|
||||
"Received HTML response instead of JSON:",
|
||||
response.substring(0, 100)
|
||||
);
|
||||
return {
|
||||
message: "error",
|
||||
data: [],
|
||||
errorDetails: "Server returned HTML instead of JSON. The server might be down or experiencing issues.",
|
||||
}
|
||||
errorDetails:
|
||||
"Server returned HTML instead of JSON. The server might be down or experiencing issues.",
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof response === "object") {
|
||||
if (response.data) {
|
||||
return response
|
||||
return response;
|
||||
}
|
||||
return { message: "success", data: [] }
|
||||
return { message: "success", data: [] };
|
||||
}
|
||||
|
||||
if (typeof response === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(response)
|
||||
return parsed
|
||||
const parsed = JSON.parse(response);
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
console.error("Failed to parse response:", error)
|
||||
return { message: "error", data: [] }
|
||||
console.error("Failed to parse response:", error);
|
||||
return { message: "error", data: [] };
|
||||
}
|
||||
}
|
||||
|
||||
return { message: "unknown", data: [] }
|
||||
return { message: "unknown", data: [] };
|
||||
}
|
||||
|
||||
export function useCart(options?: Partial<UseQueryOptions<CartResponse>>) {
|
||||
return useQuery({
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["cart"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get("/carts")
|
||||
return transformCartResponse(response.data)
|
||||
const response = await apiClient.get("/carts");
|
||||
return transformCartResponse(response.data);
|
||||
},
|
||||
refetchInterval: 10000, // Increased to 10 seconds (less aggressive)
|
||||
refetchOnMount: true,
|
||||
refetchOnWindowFocus: true, // Enable to catch updates on tab focus
|
||||
refetchOnReconnect: true,
|
||||
staleTime: 5000, // Data considered fresh for 5 seconds
|
||||
// REMOVED: Aggressive polling
|
||||
// ADDED: Smart refetching only when needed
|
||||
refetchOnMount: false, // Don't refetch on every mount
|
||||
refetchOnWindowFocus: false, // Don't refetch on tab focus
|
||||
refetchOnReconnect: true, // Only refetch on reconnect
|
||||
staleTime: Infinity, // Data never goes stale automatically
|
||||
gcTime: 1000 * 60 * 5, // Cache for 5 minutes
|
||||
retry: 2,
|
||||
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 10000),
|
||||
...options,
|
||||
})
|
||||
});
|
||||
|
||||
// Subscribe to cart events for cross-component updates
|
||||
useEffect(() => {
|
||||
const unsubscribe = cartEvents.subscribe(() => {
|
||||
// Only update cache, don't refetch
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["cart"],
|
||||
refetchType: "none",
|
||||
});
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [queryClient]);
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
export function useAddToCart() {
|
||||
const queryClient = useQueryClient()
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ productId, quantity = 1 }: { productId: number; quantity?: number }) => {
|
||||
mutationFn: async ({
|
||||
productId,
|
||||
quantity = 1,
|
||||
}: {
|
||||
productId: number;
|
||||
quantity?: number;
|
||||
}) => {
|
||||
const params = new URLSearchParams({
|
||||
product_id: String(productId),
|
||||
product_quantity: String(quantity),
|
||||
})
|
||||
});
|
||||
|
||||
const response = await apiClient.post("/carts", params.toString(), {
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
if (typeof response.data === "object" && response.data.data) {
|
||||
return response.data
|
||||
return response.data;
|
||||
}
|
||||
|
||||
if (typeof response.data === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(response.data)
|
||||
return parsed
|
||||
const parsed = JSON.parse(response.data);
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
console.error("Failed to parse add to cart response:", error)
|
||||
return { message: "success", data: "Added to cart" }
|
||||
console.error("Failed to parse add to cart response:", error);
|
||||
return { message: "success", data: "Added to cart" };
|
||||
}
|
||||
}
|
||||
|
||||
return { message: "success", data: "Added to cart" }
|
||||
return { message: "success", data: "Added to cart" };
|
||||
},
|
||||
onMutate: async ({ productId, quantity }) => {
|
||||
// Cancel outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey: ["cart"] });
|
||||
|
||||
// Snapshot previous value
|
||||
const previousCart = queryClient.getQueryData<CartResponse>(["cart"]);
|
||||
|
||||
// Optimistically update cart
|
||||
queryClient.setQueryData<CartResponse>(["cart"], (old) => {
|
||||
if (!old) return old;
|
||||
|
||||
const existingItem = old.data.find(
|
||||
(item: any) => item.product?.id === productId
|
||||
);
|
||||
|
||||
if (existingItem) {
|
||||
// Update existing item quantity
|
||||
return {
|
||||
...old,
|
||||
data: old.data.map((item: any) =>
|
||||
item.product?.id === productId
|
||||
? {
|
||||
...item,
|
||||
product_quantity: item.product_quantity + quantity,
|
||||
}
|
||||
: item
|
||||
),
|
||||
};
|
||||
} else {
|
||||
// Add new item (we don't have full product data, so we add placeholder)
|
||||
return {
|
||||
...old,
|
||||
data: [
|
||||
...old.data,
|
||||
{
|
||||
product: { id: productId },
|
||||
product_quantity: quantity,
|
||||
} as any,
|
||||
],
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// Notify other components
|
||||
cartEvents.emit();
|
||||
|
||||
return { previousCart };
|
||||
},
|
||||
onError: (error, variables, context) => {
|
||||
// Rollback on error
|
||||
if (context?.previousCart) {
|
||||
queryClient.setQueryData(["cart"], context.previousCart);
|
||||
cartEvents.emit();
|
||||
}
|
||||
console.error("Add to cart error:", error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Invalidate but don't refetch immediately (let polling handle it)
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"], refetchType: 'none' })
|
||||
// Silently refetch in background to sync with server
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["cart"],
|
||||
refetchType: "active", // Only refetch if actively being watched
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Add to cart error:", error.response?.data?.message || error.message)
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useRemoveFromCart() {
|
||||
const queryClient = useQueryClient()
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (productId: number) => {
|
||||
const params = new URLSearchParams({ product_id: String(productId) })
|
||||
const params = new URLSearchParams({ product_id: String(productId) });
|
||||
|
||||
const response = await apiClient.patch("/carts", params.toString(), {
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
if (typeof response.data === "object" && response.data.data) {
|
||||
return response.data.data
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
if (typeof response.data === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(response.data)
|
||||
return parsed.data || []
|
||||
const parsed = JSON.parse(response.data);
|
||||
return parsed.data || [];
|
||||
} catch (error) {
|
||||
console.error("Failed to parse cart response:", error)
|
||||
return []
|
||||
console.error("Failed to parse cart response:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
return []
|
||||
return [];
|
||||
},
|
||||
onMutate: async (productId) => {
|
||||
await queryClient.cancelQueries({ queryKey: ["cart"] });
|
||||
|
||||
const previousCart = queryClient.getQueryData<CartResponse>(["cart"]);
|
||||
|
||||
queryClient.setQueryData<CartResponse>(["cart"], (old) => {
|
||||
if (!old) return old;
|
||||
return {
|
||||
...old,
|
||||
data: old.data.filter((item: any) => item.product?.id !== productId),
|
||||
};
|
||||
});
|
||||
|
||||
cartEvents.emit();
|
||||
|
||||
return { previousCart };
|
||||
},
|
||||
onError: (error, variables, context) => {
|
||||
if (context?.previousCart) {
|
||||
queryClient.setQueryData(["cart"], context.previousCart);
|
||||
cartEvents.emit();
|
||||
}
|
||||
console.error("Remove from cart error:", error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Immediate refetch after removal
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["cart"],
|
||||
refetchType: "active",
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Remove from cart error:", error.response?.data?.message || error.message)
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCleanCart() {
|
||||
const queryClient = useQueryClient()
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
@@ -150,98 +279,171 @@ export function useCleanCart() {
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
if (typeof response.data === "object" && response.data.data) {
|
||||
return response.data.data
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
if (typeof response.data === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(response.data)
|
||||
return parsed.data || []
|
||||
const parsed = JSON.parse(response.data);
|
||||
return parsed.data || [];
|
||||
} catch (error) {
|
||||
console.error("Failed to parse cart response:", error)
|
||||
return []
|
||||
console.error("Failed to parse cart response:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
return []
|
||||
return [];
|
||||
},
|
||||
onMutate: async () => {
|
||||
await queryClient.cancelQueries({ queryKey: ["cart"] });
|
||||
|
||||
const previousCart = queryClient.getQueryData<CartResponse>(["cart"]);
|
||||
|
||||
queryClient.setQueryData<CartResponse>(["cart"], (old) => {
|
||||
if (!old) return old;
|
||||
return { ...old, data: [] };
|
||||
});
|
||||
|
||||
cartEvents.emit();
|
||||
|
||||
return { previousCart };
|
||||
},
|
||||
onError: (error, variables, context) => {
|
||||
if (context?.previousCart) {
|
||||
queryClient.setQueryData(["cart"], context.previousCart);
|
||||
cartEvents.emit();
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] });
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateCartItemQuantity() {
|
||||
const queryClient = useQueryClient()
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ productId, quantity }: { productId: number; quantity: number }) => {
|
||||
mutationFn: async ({
|
||||
productId,
|
||||
quantity,
|
||||
}: {
|
||||
productId: number;
|
||||
quantity: number;
|
||||
}) => {
|
||||
const params = new URLSearchParams({
|
||||
product_id: String(productId),
|
||||
product_quantity: String(quantity),
|
||||
})
|
||||
});
|
||||
|
||||
const response = await apiClient.post("/carts", params.toString(), {
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
timeout: 15000, // 15 second timeout
|
||||
})
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
if (typeof response.data === "object" && response.data.data) {
|
||||
return response.data
|
||||
return response.data;
|
||||
}
|
||||
|
||||
if (typeof response.data === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(response.data)
|
||||
return parsed
|
||||
const parsed = JSON.parse(response.data);
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
console.error("Failed to parse update cart response:", error)
|
||||
return { message: "success", data: "Updated cart" }
|
||||
console.error("Failed to parse update cart response:", error);
|
||||
return { message: "success", data: "Updated cart" };
|
||||
}
|
||||
}
|
||||
|
||||
return { message: "success", data: "Updated cart" }
|
||||
return { message: "success", data: "Updated cart" };
|
||||
},
|
||||
onMutate: async ({ productId, quantity }) => {
|
||||
await queryClient.cancelQueries({ queryKey: ["cart"] });
|
||||
|
||||
const previousCart = queryClient.getQueryData<CartResponse>(["cart"]);
|
||||
|
||||
queryClient.setQueryData<CartResponse>(["cart"], (old) => {
|
||||
if (!old) return old;
|
||||
return {
|
||||
...old,
|
||||
data: old.data.map((item: any) =>
|
||||
item.product?.id === productId
|
||||
? { ...item, product_quantity: quantity }
|
||||
: item
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
cartEvents.emit();
|
||||
|
||||
return { previousCart };
|
||||
},
|
||||
onError: (error, variables, context) => {
|
||||
if (context?.previousCart) {
|
||||
queryClient.setQueryData(["cart"], context.previousCart);
|
||||
cartEvents.emit();
|
||||
}
|
||||
console.error("API update failed:", error);
|
||||
throw error;
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Invalidate but don't refetch immediately (let optimistic update handle it)
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"], refetchType: 'none' })
|
||||
// Background sync
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["cart"],
|
||||
refetchType: "none", // Don't refetch, trust optimistic update
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("API update failed:", error.response?.data?.message || error.message)
|
||||
throw error // Re-throw to trigger retry mechanism
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateOrder() {
|
||||
const queryClient = useQueryClient()
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (payload: {
|
||||
customer_name?: string
|
||||
customer_phone: string
|
||||
customer_address: string
|
||||
shipping_method: string
|
||||
payment_type_id: number
|
||||
delivery_time?: string
|
||||
delivery_at?: string
|
||||
region: string
|
||||
note?: string
|
||||
customer_name?: string;
|
||||
customer_phone: string;
|
||||
customer_address: string;
|
||||
shipping_method: string;
|
||||
payment_type_id: number;
|
||||
delivery_time?: string;
|
||||
delivery_at?: string;
|
||||
region: string;
|
||||
note?: string;
|
||||
}) => {
|
||||
const response = await apiClient.post("/orders", payload)
|
||||
return response.data
|
||||
const response = await apiClient.post("/orders", payload);
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] })
|
||||
// Clear cart after successful order
|
||||
queryClient.setQueryData<CartResponse>(["cart"], (old) => {
|
||||
if (!old) return old;
|
||||
return { ...old, data: [] };
|
||||
});
|
||||
cartEvents.emit();
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Create order error:", error.response?.data?.message || error.message)
|
||||
console.error(
|
||||
"Create order error:",
|
||||
error.response?.data?.message || error.message
|
||||
);
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// Hook to get cart count for badges
|
||||
export function useCartCount() {
|
||||
const { data } = useCart();
|
||||
return (
|
||||
data?.data?.reduce(
|
||||
(sum: number, item: any) => sum + (item.product_quantity || 0),
|
||||
0
|
||||
) || 0
|
||||
);
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export default function CategoryFiltersSheet({
|
||||
<Sheet open={isOpen} onOpenChange={onOpenChange}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
|
||||
className="bg-[#005bff] hover:bg-[#0041c4] sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
|
||||
size="lg"
|
||||
>
|
||||
{filterLabel}
|
||||
|
||||
@@ -240,7 +240,7 @@ export default function CategoryPageClient({
|
||||
[t]
|
||||
);
|
||||
|
||||
if (categoriesLoading) return <div>{t("common.loading")}</div>;
|
||||
|
||||
if (!selectedCategory)
|
||||
return <div className="text-center py-8">{t("category_not_found")}</div>;
|
||||
|
||||
@@ -250,7 +250,7 @@ export default function CategoryPageClient({
|
||||
{selectedCategory.name}
|
||||
</h2>
|
||||
|
||||
<div className="flex gap-4 bg-white rounded-b-lg">
|
||||
<div className="flex p-2 md:p-4 gap-4 bg-white rounded-b-lg">
|
||||
{/* Desktop Filters Sidebar */}
|
||||
<div className="hidden sm:block w-[280px] shrink-0 border-r px-4">
|
||||
<ScrollArea className="h-auto">
|
||||
|
||||
@@ -28,7 +28,7 @@ export default function CollectionFiltersSheet({
|
||||
<Sheet open={isOpen} onOpenChange={onOpenChange}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
|
||||
className="bg-[#005bff] hover:bg-[#0041c4] sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
|
||||
size="lg"
|
||||
>
|
||||
{filterLabel}
|
||||
|
||||
@@ -191,7 +191,7 @@ export default function CollectionPageClient({
|
||||
[t]
|
||||
);
|
||||
|
||||
if (collectionsLoading) return <div>{t("common.loading")}</div>;
|
||||
|
||||
if (!selectedCollection)
|
||||
return <div className="text-center py-8">{t("collection_not_found")}</div>;
|
||||
|
||||
@@ -201,7 +201,7 @@ export default function CollectionPageClient({
|
||||
{selectedCollection.name}
|
||||
</h2>
|
||||
|
||||
<div className="flex gap-4 bg-white rounded-b-lg">
|
||||
<div className="flex p-2 md:p-4 gap-4 bg-white rounded-b-lg">
|
||||
{/* Desktop Filters Sidebar */}
|
||||
<div className="hidden sm:block w-[280px] shrink-0 border-r px-4">
|
||||
<ScrollArea className="h-auto">
|
||||
|
||||
@@ -1,32 +1,30 @@
|
||||
import { Heart } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Heart } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
interface EmptyFavoritesProps {
|
||||
locale?: string
|
||||
message?: string
|
||||
actionText?: string
|
||||
actionHref?: string
|
||||
}
|
||||
|
||||
export default function EmptyFavorites({
|
||||
locale = "ru",
|
||||
message = "No favorite items yet",
|
||||
actionText = "Browse Products",
|
||||
actionHref = "/",
|
||||
}: EmptyFavoritesProps) {
|
||||
export default function EmptyFavorites() {
|
||||
const t=useTranslations();
|
||||
const router=useRouter();
|
||||
return (
|
||||
<div className="min-h-[400px] flex flex-col items-center justify-center p-4">
|
||||
<Heart className="h-16 w-16 text-gray-300 mb-4" />
|
||||
<h2 className="text-2xl font-semibold text-gray-600 mb-2">{message}</h2>
|
||||
<p className="text-gray-500 mb-6 text-center max-w-sm">
|
||||
{locale === "ru"
|
||||
? "Сохраняйте понравившиеся товары, чтобы найти их позже"
|
||||
: "Save items you love to find them later"}
|
||||
</p>
|
||||
<Link href={actionHref}>
|
||||
<Button className="rounded-xl">{actionText}</Button>
|
||||
</Link>
|
||||
<div className="flex min-h-[60vh] items-center justify-center px-4">
|
||||
<div className="w-full max-w-md rounded-2xl bg-gradient-to-br from-blue-50 to-white p-8 text-center shadow-lg">
|
||||
<div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-blue-100">
|
||||
<Heart className="h-10 w-10 text-blue-600" />
|
||||
</div>
|
||||
|
||||
<h2 className="mb-2 text-2xl font-semibold text-gray-900">
|
||||
{t("favorites_empty")}
|
||||
</h2>
|
||||
|
||||
<p className="mb-6 text-sm text-gray-500">
|
||||
{t("favorites_empty_message")}
|
||||
</p>
|
||||
|
||||
<Button onClick={()=>router.push("/")} className="w-full rounded-xl bg-blue-600 px-6 py-3 text-sm font-medium text-white transition hover:bg-blue-700 active:scale-95">
|
||||
{t("start_shopping")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -306,7 +306,7 @@ export default function ProductCard({
|
||||
) : (
|
||||
<Heart
|
||||
className={`w-5 h-5 ${
|
||||
isFavorite ? "text-red-500 fill-red-500" : "text-gray-700"
|
||||
isFavorite ? "text-[#005bff] fill-[#005bff]" : "text-gray-700"
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,32 +1,30 @@
|
||||
import { Package } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ShoppingCart } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
interface EmptyOrdersProps {
|
||||
locale?: string
|
||||
message?: string
|
||||
actionText?: string
|
||||
actionHref?: string
|
||||
}
|
||||
|
||||
export default function EmptyOrders({
|
||||
locale = "ru",
|
||||
message = "No orders yet",
|
||||
actionText = "Start Shopping",
|
||||
actionHref = "/",
|
||||
}: EmptyOrdersProps) {
|
||||
export default function EmptyOrders() {
|
||||
const t=useTranslations();
|
||||
const router=useRouter();
|
||||
return (
|
||||
<div className="min-h-[400px] flex flex-col items-center justify-center p-4">
|
||||
<Package className="h-16 w-16 text-gray-300 mb-4" />
|
||||
<h2 className="text-2xl font-semibold text-gray-600 mb-2">{message}</h2>
|
||||
<p className="text-gray-500 mb-6 text-center max-w-sm">
|
||||
{locale === "ru"
|
||||
? "У вас еще нет заказов. Начните покупки прямо сейчас!"
|
||||
: "You haven't placed any orders yet. Start shopping now!"}
|
||||
</p>
|
||||
<Link href={actionHref}>
|
||||
<Button className="rounded-xl">{actionText}</Button>
|
||||
</Link>
|
||||
<div className="flex min-h-[60vh] items-center justify-center px-4">
|
||||
<div className="w-full max-w-md rounded-2xl bg-gradient-to-br from-blue-50 to-white p-8 text-center shadow-lg">
|
||||
<div className="mx-auto mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-blue-100">
|
||||
<ShoppingCart className="h-10 w-10 text-blue-600" />
|
||||
</div>
|
||||
|
||||
<h2 className="mb-2 text-2xl font-semibold text-gray-900">
|
||||
{t("orders_empty")}
|
||||
</h2>
|
||||
|
||||
<p className="mb-6 text-sm text-gray-500">
|
||||
{t("orders_empty_message")}
|
||||
</p>
|
||||
|
||||
<Button onClick={()=>router.push("/")} className="w-full rounded-xl bg-blue-600 px-6 py-3 text-sm font-medium text-white transition hover:bg-blue-700 active:scale-95">
|
||||
{t("start_shopping")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -28,7 +28,7 @@ import { useToast } from "@/hooks/use-toast";
|
||||
import { useOrders, useCancelOrder } from "@/lib/hooks";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { Order } from "@/lib/types/api";
|
||||
|
||||
import EmptyOrders from "./EmptyOrders";
|
||||
interface OrdersPageClientProps {
|
||||
locale: string;
|
||||
}
|
||||
@@ -181,12 +181,7 @@ export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
|
||||
if (isError || !orders || orders.length === 0) {
|
||||
return (
|
||||
<div className="container mx-auto p-4 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("my_orders")}</h1>
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<p className="text-2xl text-gray-400">{t("no_orders")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<EmptyOrders/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Card } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
interface Review {
|
||||
id: number;
|
||||
@@ -41,11 +42,13 @@ export function ProductReviewsSection({
|
||||
);
|
||||
};
|
||||
|
||||
const t= useTranslations();
|
||||
|
||||
return (
|
||||
<Card className="p-6 rounded-xl">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<div className="flex justify-between items-center ">
|
||||
<div>
|
||||
<h3 className="text-2xl font-bold">Customer Reviews</h3>
|
||||
<h3 className="text-2xl font-bold">{t("customer_reviews")}</h3>
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
{renderStars(Math.round(averageRating))}
|
||||
<span className="text-sm text-gray-600">
|
||||
@@ -53,9 +56,9 @@ export function ProductReviewsSection({
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={onWriteReview} className="rounded-lg">
|
||||
<Button onClick={onWriteReview} className="rounded-lg bg-[#005bff] hover:bg-[#0041c4]">
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
Write Review
|
||||
{t("write_review")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -83,7 +86,7 @@ export function ProductReviewsSection({
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
No reviews yet. Be the first to review this product!
|
||||
{t("no_reviews")}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import ProductCard from "@/features/home/components/ProductCard";
|
||||
|
||||
import {useTranslations} from "next-intl";
|
||||
interface RelatedProduct {
|
||||
id: number;
|
||||
slug: string;
|
||||
@@ -30,12 +30,13 @@ interface RelatedProductsSectionProps {
|
||||
export function RelatedProductsSection({
|
||||
products,
|
||||
}: RelatedProductsSectionProps) {
|
||||
const t = useTranslations();
|
||||
if (!products || products.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg p-6">
|
||||
<h2 className="text-2xl font-bold mb-6">Related Products</h2>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
<h2 className="text-2xl font-bold mb-6">{t("related_products")}</h2>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{products.slice(0, 4).map((product) => {
|
||||
// Extract image URLs from media
|
||||
const images =
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
interface ReviewModalProps {
|
||||
open: boolean;
|
||||
@@ -27,6 +28,8 @@ export function ReviewModal({
|
||||
const [text, setText] = useState("");
|
||||
const [hoveredStar, setHoveredStar] = useState(0);
|
||||
|
||||
const t = useTranslations();
|
||||
|
||||
const handleClose = () => {
|
||||
onOpenChange(false);
|
||||
setRating(0);
|
||||
@@ -63,29 +66,29 @@ export function ReviewModal({
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-xl">Write a Review</DialogTitle>
|
||||
<DialogTitle className="text-xl">{t("write_review")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Share your experience with this product
|
||||
{t("share_experience")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 pt-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2">Rating</label>
|
||||
<label className="block text-sm font-medium mb-2">{t("rating")}</label>
|
||||
{renderStars()}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2">
|
||||
Your Review
|
||||
{t("your_review")}
|
||||
</label>
|
||||
<Textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="Write your review here..."
|
||||
placeholder={t("write_review")}
|
||||
className="min-h-[120px] resize-none"
|
||||
maxLength={500}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
{text.length}/500 characters
|
||||
{text.length}/500 {t("characters")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -95,22 +98,22 @@ export function ReviewModal({
|
||||
onClick={handleClose}
|
||||
className="flex-1 rounded-lg"
|
||||
>
|
||||
Cancel
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={rating === 0 || !text.trim() || isSubmitting}
|
||||
className="flex-1 rounded-lg"
|
||||
className="flex-1 rounded-lg bg-[#005bff] hover:bg-[#0041c4]"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Submitting...
|
||||
{t("submitting")}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
Submit Review
|
||||
{t("submit_review")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
@@ -163,5 +163,21 @@
|
||||
"enter_address": "Введите адрес",
|
||||
"save_changes": "Сохранить изменения",
|
||||
"saving": "Сохранение...",
|
||||
"cancel": "Отменить"
|
||||
"cancel": "Отменить",
|
||||
"write_review": "Написать отзыв",
|
||||
"no_reviews": "Отзывов пока нет, стать первым, кто оставил отзыв!",
|
||||
"customer_reviews": "Отзывы",
|
||||
"share_experience": "Поделитесь опытом с этим товаром",
|
||||
"rating": "Рейтинг",
|
||||
"your_review": "Ваш отзыв",
|
||||
"submitting": "Отправляется...",
|
||||
"submit_review": "Отправить отзыв",
|
||||
"characters": "символы",
|
||||
"related_products": "Связанные товары",
|
||||
"cart_empty_message": "Вы пока не добавили товары в корзину. Начните поиск и добавьте любимые товары в корзину.",
|
||||
"start_shopping": "Начните поиск",
|
||||
"favorites_empty": "У вас пока нет избранных товаров",
|
||||
"favorites_empty_message": "Добавьте любимые товары в избранное",
|
||||
"orders_empty": "У вас пока нет заказов",
|
||||
"orders_empty_message": "Начните делать заказы"
|
||||
}
|
||||
|
||||
@@ -163,6 +163,21 @@
|
||||
"enter_address": "Adres giriziň",
|
||||
"save_changes": "Ýatda sakla",
|
||||
"saving": "Ýatda saklýar...",
|
||||
"cancel": "Goýbolsun"
|
||||
|
||||
"cancel": "Goýbolsun",
|
||||
"write_review": "Teswir ýaz",
|
||||
"no_reviews": "Entek teswir ýok, ilkinji teswiri siz ýazyň!",
|
||||
"customer_reviews": "Teswirler",
|
||||
"share_experience": "Bu haryt barada öz teswiriňizi ýazyň",
|
||||
"rating": "Reýting",
|
||||
"your_review": "Teswiriňiz",
|
||||
"submitting": "Ugradylýar...",
|
||||
"submit_review": "Teswiri ugrat",
|
||||
"characters": "simbol",
|
||||
"related_products": "Meňzeş harytlar",
|
||||
"cart_empty_message": "Entek sebediňize haryt goşmadyňyz. Söwda etmäge başlaň!!!",
|
||||
"start_shopping": "Söwda etmäge başla!",
|
||||
"favorites_empty": "Siziň saýlanan harytlaryňyz ýok",
|
||||
"favorites_empty_message": "Halan harydyňyz saýlap goýuň!",
|
||||
"orders_empty": "Siziň sargytlaryňyz ýok",
|
||||
"orders_empty_message": "Sargyt etmäge başlaň!"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user