first commit
This commit is contained in:
132
components/layout/Header.tsx
Normal file
132
components/layout/Header.tsx
Normal file
@@ -0,0 +1,132 @@
|
||||
// Header.tsx
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { X, Search } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Logo from "@/public/logo.webp";
|
||||
import CategoryMenu from "./ui/CategoryMenu";
|
||||
import SearchBar from "./ui/SearchBar";
|
||||
import AuthDialog from "./ui/AuthDialog";
|
||||
import ActionButtons from "./ui/ActionButtons";
|
||||
import LanguageSelector from "./ui/LanguageSelector";
|
||||
import MobileBottomNav from "./MobileBar";
|
||||
import { useAuthStatus } from "@/lib/hooks/useAuth";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { CategoryIcon } from "../icons";
|
||||
|
||||
interface HeaderProps {
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
const [isCategoryOpen, setIsCategoryOpen] = useState(false);
|
||||
const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
|
||||
const [isLoginOpen, setIsLoginOpen] = useState(false);
|
||||
const t = useTranslations();
|
||||
|
||||
const { isAuthenticated } = useAuthStatus();
|
||||
|
||||
useEffect(() => {
|
||||
setIsClient(true);
|
||||
}, []);
|
||||
|
||||
const handleAuthClick = useCallback(() => {
|
||||
if (isAuthenticated) {
|
||||
window.location.href = `/${locale}/me`;
|
||||
} else {
|
||||
setIsLoginOpen(true);
|
||||
}
|
||||
}, [isAuthenticated, locale]);
|
||||
|
||||
const toggleCategoryMenu = useCallback(() => {
|
||||
setIsCategoryOpen((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
const closeCategoryMenu = useCallback(() => {
|
||||
setIsCategoryOpen(false);
|
||||
}, []);
|
||||
|
||||
if (!isClient) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="sticky top-0 z-50 w-full border-b bg-white shadow-sm">
|
||||
<div className="mx-auto px-4">
|
||||
<div className="flex h-16 items-center justify-between gap-3">
|
||||
<Link href="/" className="shrink-0">
|
||||
<div className="relative h-8 w-[180px]">
|
||||
<Image
|
||||
src={Logo}
|
||||
alt="Logo"
|
||||
fill
|
||||
className="object-contain"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Button
|
||||
data-catalog-trigger
|
||||
onClick={toggleCategoryMenu}
|
||||
className="cursor-pointer hidden gap-2 rounded-lg font-bold lg:flex hover:bg-[#005bff] bg-[#005bff] text-white"
|
||||
size="lg"
|
||||
>
|
||||
{isCategoryOpen ? <X className="h-5 w-5" /> : <CategoryIcon />}
|
||||
{t("common.catalog")}
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-2 sm:hidden cursor-pointer">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setIsMobileSearchOpen(true)}
|
||||
>
|
||||
<Search className="h-5 w-5" />
|
||||
</Button>
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
|
||||
<div className="hidden sm:block">
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
|
||||
<SearchBar
|
||||
isMobile={false}
|
||||
searchPlaceholder={t("common.search")}
|
||||
className="hidden flex-1 md:flex"
|
||||
locale={locale}
|
||||
/>
|
||||
|
||||
<ActionButtons
|
||||
isAuthenticated={isAuthenticated}
|
||||
onAuthClick={handleAuthClick}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<CategoryMenu isOpen={isCategoryOpen} onClose={closeCategoryMenu} />
|
||||
|
||||
<SearchBar
|
||||
isMobile={true}
|
||||
isOpen={isMobileSearchOpen}
|
||||
onClose={() => setIsMobileSearchOpen(false)}
|
||||
searchPlaceholder={t("common.search")}
|
||||
locale={locale}
|
||||
/>
|
||||
|
||||
<AuthDialog isOpen={isLoginOpen} onClose={() => setIsLoginOpen(false)} />
|
||||
|
||||
<MobileBottomNav
|
||||
locale={locale}
|
||||
onLoginClick={() => {
|
||||
setIsLoginOpen(true);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
232
components/layout/MobileBar.tsx
Normal file
232
components/layout/MobileBar.tsx
Normal file
@@ -0,0 +1,232 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { Menu, Heart, Truck, ShoppingCart, User } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
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?: {
|
||||
catalog: string;
|
||||
favorites: string;
|
||||
orders: string;
|
||||
cart: string;
|
||||
login: string;
|
||||
profile: string;
|
||||
};
|
||||
onLoginClick?: () => void;
|
||||
}
|
||||
|
||||
export default function MobileBottomNav({
|
||||
locale = "ru",
|
||||
translations,
|
||||
onLoginClick,
|
||||
}: MobileBottomNavProps) {
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
const [isCategoryOpen, setIsCategoryOpen] = useState(false);
|
||||
const [isLoginOpen, setIsLoginOpen] = useState(false);
|
||||
const t = useTranslations();
|
||||
|
||||
const { isAuthenticated, isLoading: authLoading } = useAuthStatus();
|
||||
|
||||
const { data: categories = [] } = useCategories();
|
||||
|
||||
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();
|
||||
|
||||
if (authLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAuthenticated) {
|
||||
router.push(`/${locale}/me`);
|
||||
} else {
|
||||
if (onLoginClick) {
|
||||
onLoginClick();
|
||||
} else {
|
||||
setIsLoginOpen(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleNavigation = (path: string) => (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
router.push(path);
|
||||
};
|
||||
|
||||
if (!isClient) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile Bottom Navigation */}
|
||||
<div className="fixed bottom-0 left-0 right-0 z-50 bg-white border-t shadow-lg lg:hidden">
|
||||
<div className="flex items-center justify-around h-16 px-2">
|
||||
{/* Catalog Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={() => {
|
||||
setIsCategoryOpen(true);
|
||||
}}
|
||||
>
|
||||
<Menu className="h-5 w-5 text-gray-600" />
|
||||
<span className="text-xs text-gray-700">{t("common.catalog")}</span>
|
||||
</Button>
|
||||
|
||||
{/* Favorites Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="relative flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={handleNavigation("/favorites")}
|
||||
>
|
||||
<div className="relative">
|
||||
<Heart className="h-5 w-5 text-gray-600" />
|
||||
{(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>
|
||||
</Button>
|
||||
|
||||
{/* Orders Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="relative flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={handleNavigation("/orders")}
|
||||
>
|
||||
<div className="relative">
|
||||
<Truck className="h-5 w-5 text-gray-600" />
|
||||
{(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 - OPTIMIZED */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="relative flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={handleNavigation("/cart")}
|
||||
>
|
||||
<div className="relative">
|
||||
<ShoppingCart className="h-5 w-5 text-gray-600" />
|
||||
{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>
|
||||
|
||||
{/* Profile/Login Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={handleProfileClick}
|
||||
disabled={authLoading}
|
||||
>
|
||||
<User className="h-5 w-5 text-gray-600" />
|
||||
<span className="text-xs text-gray-700">
|
||||
{authLoading
|
||||
? "..."
|
||||
: isAuthenticated
|
||||
? t("common.profile")
|
||||
: t("common.login")}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Sheet/Drawer */}
|
||||
<Sheet open={isCategoryOpen} onOpenChange={setIsCategoryOpen}>
|
||||
<SheetContent side="left" className="w-[300px] p-0">
|
||||
<SheetHeader className="p-4 border-b">
|
||||
<SheetTitle>{t("common.catalog")}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className="h-[calc(100vh-80px)]">
|
||||
<div className="p-4">
|
||||
{categories.map((category) => (
|
||||
<div key={category.id} className="mb-4">
|
||||
<Link
|
||||
href={`/category/${category.slug}?category_id=${category.id}`}
|
||||
onClick={() => setIsCategoryOpen(false)}
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors font-semibold"
|
||||
>
|
||||
<span>{category.name}</span>
|
||||
</Link>
|
||||
|
||||
{/* Subcategories */}
|
||||
{category.children && category.children.length > 0 && (
|
||||
<div className="ml-8 mt-2 space-y-1">
|
||||
{category.children.map((child: any) => (
|
||||
<Link
|
||||
key={child.id}
|
||||
href={`/category/${child.slug}?category_id=${child.id}`}
|
||||
onClick={() => setIsCategoryOpen(false)}
|
||||
className="block px-3 py-2 text-sm text-gray-600 hover:text-primary hover:bg-gray-50 rounded-lg transition-colors"
|
||||
>
|
||||
{child.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Local Auth Dialog */}
|
||||
<AuthDialog isOpen={isLoginOpen} onClose={() => setIsLoginOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
206
components/layout/ui/ActionButtons.tsx
Normal file
206
components/layout/ui/ActionButtons.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
"use client";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMemo } from "react";
|
||||
import type React from "react";
|
||||
import Link from "next/link";
|
||||
import { User, Truck, Heart, Store, LogOut } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useCart, useFavorites, useOrders, useCartCount } from "@/lib/hooks";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLogout } from "@/lib/hooks/useAuth";
|
||||
import {
|
||||
CartIcon,
|
||||
FavoriteIcon,
|
||||
OrderIcon,
|
||||
ProfileIcon,
|
||||
} from "@/components/icons";
|
||||
|
||||
interface ActionButtonsProps {
|
||||
isAuthenticated: boolean;
|
||||
onAuthClick: () => void;
|
||||
isLoading?: boolean;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
interface ActionButtonData {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
href?: string;
|
||||
onClick?: () => void;
|
||||
badgeCount?: number;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export default function ActionButtons({
|
||||
isAuthenticated,
|
||||
onAuthClick,
|
||||
isLoading: authLoading,
|
||||
locale = "ru",
|
||||
}: ActionButtonsProps) {
|
||||
const t = useTranslations();
|
||||
const { mutate: logout, isPending: isLoggingOut } = useLogout();
|
||||
const router = useRouter();
|
||||
const { data: cartData, isLoading: cartLoading } = useCart();
|
||||
const { data: favoritesData, isLoading: favoritesLoading } = useFavorites();
|
||||
const { data: ordersData, isLoading: ordersLoading } = useOrders();
|
||||
|
||||
// Calculate cart count from cart items array
|
||||
const cartCount = useCartCount()
|
||||
|
||||
// Calculate favorites count
|
||||
const favoritesCount = useMemo(() => {
|
||||
if (!favoritesData) return 0;
|
||||
return Array.isArray(favoritesData) ? favoritesData.length : 0;
|
||||
}, [favoritesData]);
|
||||
|
||||
// Calculate orders count
|
||||
const ordersCount = useMemo(() => {
|
||||
if (!ordersData) return 0;
|
||||
return Array.isArray(ordersData) ? ordersData.length : 0;
|
||||
}, [ordersData]);
|
||||
|
||||
const handleLogout = () => {
|
||||
logout(undefined, {
|
||||
onSuccess: () => {
|
||||
router.push(`/${locale}`);
|
||||
router.refresh();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const buttons: ActionButtonData[] = useMemo(
|
||||
() => [
|
||||
{
|
||||
icon: <Store />,
|
||||
label: t("common.openStore"),
|
||||
href: "/openStore",
|
||||
},
|
||||
{
|
||||
icon: <OrderIcon />,
|
||||
label: t("common.orders"),
|
||||
href: "/orders",
|
||||
badgeCount: ordersCount,
|
||||
isLoading: ordersLoading,
|
||||
},
|
||||
{
|
||||
icon: <FavoriteIcon />,
|
||||
label: t("common.favorites"),
|
||||
href: "/favorites",
|
||||
badgeCount: favoritesCount,
|
||||
isLoading: favoritesLoading,
|
||||
},
|
||||
{
|
||||
icon: <CartIcon />,
|
||||
label: t("common.cart"),
|
||||
href: "/cart",
|
||||
badgeCount: cartCount,
|
||||
isLoading: cartLoading,
|
||||
},
|
||||
],
|
||||
[
|
||||
ordersCount,
|
||||
ordersLoading,
|
||||
favoritesCount,
|
||||
favoritesLoading,
|
||||
cartCount,
|
||||
cartLoading,
|
||||
t,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="hidden items-center gap-1 lg:flex">
|
||||
{/* Profile/Login Button with Dropdown */}
|
||||
{authLoading ? (
|
||||
<div className="h-10 w-24 animate-pulse bg-gray-200 rounded" />
|
||||
) : isAuthenticated ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col cursor-pointer gap-0.5 h-auto px-2 py-2"
|
||||
>
|
||||
<ProfileIcon />
|
||||
<span className="text-xs text-gray-700">{t("profile")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => router.push(`/${locale}/me`)}>
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
{t("profile")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleLogout} disabled={isLoggingOut}>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
{isLoggingOut ? t("logging_out") : t("common.logout")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col cursor-pointer gap-0.5 h-auto px-2 py-2"
|
||||
onClick={onAuthClick}
|
||||
>
|
||||
<ProfileIcon />
|
||||
<span className="text-xs text-gray-700">{t("common.login")}</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Other Action Buttons */}
|
||||
{buttons.map((button, index) => (
|
||||
<ActionButton key={index} {...button} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({
|
||||
icon,
|
||||
label,
|
||||
href,
|
||||
onClick,
|
||||
badgeCount,
|
||||
isLoading,
|
||||
}: ActionButtonData) {
|
||||
const buttonContent = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="relative flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className="relative">
|
||||
{icon}
|
||||
{badgeCount !== undefined && badgeCount > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Skeleton className="h-3 w-3 rounded-full" />
|
||||
) : (
|
||||
badgeCount
|
||||
)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-gray-700">{label}</span>
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (href) {
|
||||
return <Link href={href}>{buttonContent}</Link>;
|
||||
}
|
||||
|
||||
return buttonContent;
|
||||
}
|
||||
197
components/layout/ui/AuthDialog.tsx
Normal file
197
components/layout/ui/AuthDialog.tsx
Normal file
@@ -0,0 +1,197 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback } from "react";
|
||||
import Image from "next/image";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { toast } from "sonner";
|
||||
import Logo from "@/public/logo.webp";
|
||||
import { useLogin, useVerifyToken } from "@/lib/hooks/useAuth";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
interface AuthDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
|
||||
const [phone, setPhone] = useState("+993 ");
|
||||
const [otp, setOtp] = useState("");
|
||||
const [otpSent, setOtpSent] = useState(false);
|
||||
const t = useTranslations();
|
||||
|
||||
const { mutate: login, isPending: isLoginLoading } = useLogin();
|
||||
const { mutate: verifyToken, isPending: isVerifyLoading } = useVerifyToken();
|
||||
|
||||
const resetDialog = useCallback(() => {
|
||||
setOtpSent(false);
|
||||
setPhone("+993 ");
|
||||
setOtp("");
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
|
||||
const formatPhoneForBackend = (phoneNumber: string): string => {
|
||||
return phoneNumber.replace(/^\+993\s*/, "").replace(/\s+/g, "");
|
||||
};
|
||||
|
||||
const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const input = e.target.value;
|
||||
const prefix = "+993 ";
|
||||
|
||||
if (input.length < prefix.length) {
|
||||
setPhone(prefix);
|
||||
return;
|
||||
}
|
||||
|
||||
const digitsOnly = input.substring(prefix.length).replace(/\D/g, "");
|
||||
|
||||
const limitedDigits = digitsOnly.substring(0, 8);
|
||||
|
||||
let formattedPhone = prefix;
|
||||
if (limitedDigits.length > 0) {
|
||||
formattedPhone += limitedDigits.substring(0, 2);
|
||||
|
||||
if (limitedDigits.length > 2) {
|
||||
formattedPhone += " " + limitedDigits.substring(2);
|
||||
}
|
||||
}
|
||||
|
||||
setPhone(formattedPhone);
|
||||
};
|
||||
|
||||
const isPhoneValid = (): boolean => {
|
||||
const phoneDigits = formatPhoneForBackend(phone);
|
||||
return phoneDigits.length === 8;
|
||||
};
|
||||
|
||||
const handleSendOtp = useCallback(() => {
|
||||
if (!isPhoneValid()) {
|
||||
toast.error(t("invalid_phone"));
|
||||
return;
|
||||
}
|
||||
|
||||
const phoneNumber = formatPhoneForBackend(phone);
|
||||
|
||||
login(
|
||||
{ phone_number: parseInt(phoneNumber, 10) },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(t("code_sent"));
|
||||
setOtpSent(true);
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error?.response?.data?.message || t("error_occurred"));
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [phone, login, t]);
|
||||
|
||||
const handleLogin = useCallback(() => {
|
||||
if (otp.length < 4) {
|
||||
toast.error(t("invalid_code"));
|
||||
return;
|
||||
}
|
||||
|
||||
const phoneNumber = formatPhoneForBackend(phone);
|
||||
|
||||
verifyToken(
|
||||
{
|
||||
phone_number: parseInt(phoneNumber, 10),
|
||||
code: parseInt(otp, 10),
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(t("login_success"));
|
||||
resetDialog();
|
||||
window.location.reload();
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error?.response?.data?.message || t("wrong_code"));
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [otp, phone, verifyToken, resetDialog, t]);
|
||||
|
||||
const handleKeyPress = useCallback(
|
||||
(e: React.KeyboardEvent, action: () => void) => {
|
||||
if (e.key === "Enter") {
|
||||
action();
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={resetDialog}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center justify-center mb-4">
|
||||
<div className="relative h-8 w-[180px]">
|
||||
<Image src={Logo} alt="Logo" fill className="object-contain" />
|
||||
</div>
|
||||
</div>
|
||||
<DialogTitle className="text-2xl text-center">
|
||||
{t("common.enterPhone")}
|
||||
</DialogTitle>
|
||||
<p className="text-center text-sm text-gray-600">
|
||||
{t("common.weWillSendCode")}
|
||||
</p>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 mt-4">
|
||||
<div>
|
||||
<Input
|
||||
type="tel"
|
||||
placeholder="+993 61 097651"
|
||||
value={phone}
|
||||
onChange={handlePhoneChange}
|
||||
className="h-12 rounded-xl"
|
||||
onKeyDown={(e) => handleKeyPress(e, handleSendOtp)}
|
||||
disabled={otpSent || isLoginLoading}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">{t("phone_format")}</p>
|
||||
</div>
|
||||
|
||||
{otpSent && (
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={t("common.code")}
|
||||
value={otp}
|
||||
onChange={(e) =>
|
||||
setOtp(e.target.value.replace(/\D/g, "").substring(0, 6))
|
||||
}
|
||||
className="h-12 rounded-xl"
|
||||
onKeyDown={(e) => handleKeyPress(e, handleLogin)}
|
||||
disabled={isVerifyLoading}
|
||||
autoFocus
|
||||
maxLength={6}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button
|
||||
onClick={otpSent ? handleLogin : handleSendOtp}
|
||||
className="w-full cursor-pointer h-12 rounded-xl font-bold text-base bg-[#005bff] hover:bg-[#0041c4]"
|
||||
size="lg"
|
||||
disabled={
|
||||
isLoginLoading || isVerifyLoading || (!otpSent && !isPhoneValid())
|
||||
}
|
||||
>
|
||||
{isLoginLoading
|
||||
? t("sending")
|
||||
: isVerifyLoading
|
||||
? t("verifying")
|
||||
: otpSent
|
||||
? t("verify")
|
||||
: t("common.send")}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
164
components/layout/ui/CategoryMenu.tsx
Normal file
164
components/layout/ui/CategoryMenu.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
// CategoryMenu.tsx
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import Link from "next/link";
|
||||
import { useCategories } from "@/lib/hooks";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
interface CategoryMenuProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
|
||||
const [hoveredCategory, setHoveredCategory] = useState<number | null>(null);
|
||||
const { data: categories, isLoading } = useCategories();
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Click outside to close
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement;
|
||||
|
||||
|
||||
if (target.closest("[data-catalog-trigger]")) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (menuRef.current && !menuRef.current.contains(target)) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
// Add listener after a small delay to prevent immediate closing
|
||||
const timeoutId = setTimeout(() => {
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
}, 100);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeoutId);
|
||||
document.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
// ESC key to close
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleEscape);
|
||||
return () => document.removeEventListener("keydown", handleEscape);
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const categoryList = categories || [];
|
||||
const activeCategory =
|
||||
hoveredCategory !== null ? categoryList[hoveredCategory] : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="fixed inset-0 bg-black/20 z-30" onClick={onClose} />
|
||||
|
||||
{/* Menu */}
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="fixed left-0 right-0 top-16 z-40 bg-white border-b rounded-b-lg shadow-lg max-w-[1504px] mx-auto"
|
||||
>
|
||||
<div className="mx-auto px-4">
|
||||
<div className="flex">
|
||||
<CategoryList
|
||||
categories={categoryList}
|
||||
isLoading={isLoading}
|
||||
onCategoryHover={setHoveredCategory}
|
||||
onCategoryClick={onClose}
|
||||
/>
|
||||
|
||||
{activeCategory?.children && (
|
||||
<SubcategoryList
|
||||
category={activeCategory}
|
||||
onSubcategoryClick={onClose}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface CategoryListProps {
|
||||
categories: any[];
|
||||
isLoading: boolean;
|
||||
onCategoryHover: (index: number) => void;
|
||||
onCategoryClick: () => void;
|
||||
}
|
||||
|
||||
function CategoryList({
|
||||
categories,
|
||||
isLoading,
|
||||
onCategoryHover,
|
||||
onCategoryClick,
|
||||
}: CategoryListProps) {
|
||||
return (
|
||||
<div className="w-[280px] border-r">
|
||||
<div className="max-h-[calc(100vh-4rem)] overflow-y-auto py-2">
|
||||
{isLoading
|
||||
? [1, 2, 3, 4, 5].map((i) => (
|
||||
<Skeleton key={i} className="h-10 mx-4 my-2 rounded" />
|
||||
))
|
||||
: categories.map((category, index) => (
|
||||
<Link
|
||||
key={category.id}
|
||||
href={`/category/${category.slug}?category_id=${category.id}`}
|
||||
onClick={onCategoryClick}
|
||||
onMouseEnter={() => onCategoryHover(index)}
|
||||
className="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-100 hover:text-primary transition-colors"
|
||||
>
|
||||
{category.icon_class && (
|
||||
<i className={`${category.icon_class} text-xl`} />
|
||||
)}
|
||||
<span>{category.name}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SubcategoryListProps {
|
||||
category: any;
|
||||
onSubcategoryClick: () => void;
|
||||
}
|
||||
|
||||
function SubcategoryList({
|
||||
category,
|
||||
onSubcategoryClick,
|
||||
}: SubcategoryListProps) {
|
||||
return (
|
||||
<div className="flex-1 p-6">
|
||||
<h3 className="text-xl font-semibold mb-4">{category.name}</h3>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{category.children?.map((subCategory: any) => (
|
||||
<Link
|
||||
key={subCategory.id}
|
||||
href={`/category/${subCategory.slug}?category_id=${subCategory.id}`}
|
||||
onClick={onSubcategoryClick}
|
||||
className="text-gray-600 hover:text-black text-sm py-1 hover:underline"
|
||||
>
|
||||
{subCategory.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
80
components/layout/ui/LanguageSelector.tsx
Normal file
80
components/layout/ui/LanguageSelector.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import { useLocale } from "next-intl";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import tm from "@/public/tm.png";
|
||||
import ru from "@/public/ru.png";
|
||||
|
||||
interface Language {
|
||||
code: string;
|
||||
name: string;
|
||||
flag: any;
|
||||
}
|
||||
|
||||
const LANGUAGES: Language[] = [
|
||||
{ code: "ru", name: "Russian", flag: ru },
|
||||
{ code: "tm", name: "Turkmen", flag: tm },
|
||||
];
|
||||
|
||||
export default function LanguageSelector() {
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const handleLanguageChange = async (newLocale: string) => {
|
||||
if (typeof window !== "undefined") {
|
||||
(window as any).i18n = { language: newLocale };
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries();
|
||||
|
||||
const currentPath = pathname.replace(`/${locale}`, "");
|
||||
router.replace(`/${newLocale}${currentPath}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<Select value={locale} onValueChange={handleLanguageChange}>
|
||||
<SelectTrigger className="w-[70px] md:h-10! flex items-center justify-center rounded-lg border-gray-300">
|
||||
<SelectValue>
|
||||
<FlagIcon locale={locale} />
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LANGUAGES.map((language) => (
|
||||
<SelectItem key={language.code} value={language.code}>
|
||||
<div className="flex items-center gap-2">
|
||||
<FlagIcon locale={language.code} />
|
||||
<span>{language.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
|
||||
function FlagIcon({ locale }: { locale: string }) {
|
||||
const language = LANGUAGES.find((lang) => lang.code === locale);
|
||||
|
||||
if (!language) return null;
|
||||
|
||||
return (
|
||||
<div className="relative h-5 w-7">
|
||||
<Image
|
||||
src={language.flag || "/placeholder.svg"}
|
||||
alt={language.name}
|
||||
fill
|
||||
className="object-cover rounded"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
167
components/layout/ui/SearchBar.tsx
Normal file
167
components/layout/ui/SearchBar.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import { Search, X, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useSearchProducts } from "@/features/search/hooks/useSearch";
|
||||
import Image from "next/image";
|
||||
import { SearchIcon } from "@/components/icons";
|
||||
|
||||
interface SearchBarProps {
|
||||
isMobile: boolean;
|
||||
searchPlaceholder: string;
|
||||
isOpen?: boolean;
|
||||
onClose?: () => void;
|
||||
className?: string;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export default function SearchBar({
|
||||
isMobile,
|
||||
searchPlaceholder,
|
||||
isOpen,
|
||||
onClose,
|
||||
className = "",
|
||||
locale = "ru",
|
||||
}: SearchBarProps) {
|
||||
const router = useRouter();
|
||||
const [searchValue, setSearchValue] = useState("");
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("");
|
||||
const [showResults, setShowResults] = useState(false);
|
||||
const searchRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data, isLoading } = useSearchProducts({ q: debouncedSearch });
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedSearch(searchValue);
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchValue]);
|
||||
|
||||
useEffect(() => {
|
||||
if (debouncedSearch && data?.data && data.data.length > 0) {
|
||||
setShowResults(true);
|
||||
} else {
|
||||
setShowResults(false);
|
||||
}
|
||||
}, [debouncedSearch, data]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
|
||||
setShowResults(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const handleSearch = (value: string) => {
|
||||
setSearchValue(value);
|
||||
};
|
||||
|
||||
const handleProductClick = (productId: number) => {
|
||||
router.push(`/${locale}/product/${productId}`);
|
||||
setSearchValue("");
|
||||
setShowResults(false);
|
||||
if (onClose) onClose();
|
||||
};
|
||||
|
||||
const handleClearSearch = () => {
|
||||
setSearchValue("");
|
||||
setShowResults(false);
|
||||
};
|
||||
|
||||
const SearchResults = () => {
|
||||
if (!showResults || !data?.data) return null;
|
||||
|
||||
return (
|
||||
<div className="absolute top-full left-0 right-0 mt-2 bg-white border rounded-xl shadow-lg max-h-[400px] overflow-y-auto z-50">
|
||||
{data.data.map((product) => (
|
||||
<button
|
||||
key={product.id}
|
||||
onClick={() => handleProductClick(product.id)}
|
||||
className="w-full cursor-pointer flex items-center gap-3 p-3 hover:bg-gray-50 transition-colors border-b last:border-b-0"
|
||||
>
|
||||
<div className="relative w-16 h-16 shrink-0">
|
||||
<Image
|
||||
src={product.thumbnail}
|
||||
alt={product.name}
|
||||
fill
|
||||
className="object-cover rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 text-left">
|
||||
<p className="font-medium text-sm line-clamp-2">{product.name}</p>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
{product.price_amount} TMT
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">{product.brand.name}</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="top-4 translate-y-0">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{searchPlaceholder}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="relative" ref={searchRef}>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchValue}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
className="h-10 rounded-xl focus:border-[#005bff] focus-visible:border-[#005bff] focus-visible:ring-0 active:border-[#005bff]"
|
||||
autoFocus
|
||||
/>
|
||||
{isLoading && (
|
||||
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-gray-400" />
|
||||
)}
|
||||
<SearchResults />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`bg-[#005bff] rounded-xl flex items-center relative ${className}`} ref={searchRef}>
|
||||
<div className="w-full relative">
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchValue}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
className="border-[#005bff] w-full rounded-xl border-2 focus-visible:ring-0 bg-white px-2"
|
||||
/>
|
||||
{isLoading && (
|
||||
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-gray-400" />
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size="icon"
|
||||
className="h-auto hover:bg-[#005bff] cursor-pointer bg-transparent flex items-center mr-1.5 text-white"
|
||||
>
|
||||
<SearchIcon />
|
||||
</Button>
|
||||
<SearchResults />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user