added some api

This commit is contained in:
Jelaletdin12
2025-11-13 21:56:30 +05:00
parent fdec9e4b0e
commit 21b9e88c5c
22 changed files with 2268 additions and 930 deletions

View File

@@ -20,12 +20,16 @@ export default function CartPage() {
const t = useTranslations()
const { data: cart, isLoading, isError } = useCart()
// useCart dönen data yapısı: { message: "success", data: [...] }
const { data: cartResponse, isLoading, isError } = useCart()
const { data: regions = [] } = useRegions()
const { data: addresses = [] } = useAddresses()
const { data: paymentTypes = [] } = usePaymentTypes()
const { mutate: createOrder, isPending: isCreatingOrder } = useCreateOrder()
// Cart items'ı doğru şekilde al
const cartItems = cartResponse?.data || []
useEffect(() => {
setIsClient(true)
}, [])
@@ -37,12 +41,10 @@ export default function CartPage() {
const handleCompleteOrder = () => {
if (!selectedRegion || !selectedAddress || !paymentType) {
console.warn("[v0] Missing required fields for order")
console.warn("Missing required fields for order")
return
}
const selectedRegionObj = regions.find((r) => r.code === selectedRegion)
createOrder(
{
customer_address: selectedAddress,
@@ -53,7 +55,6 @@ export default function CartPage() {
},
{
onSuccess: () => {
// Navigate to orders page after successful order creation
router.push(`/orders`)
},
},
@@ -70,7 +71,7 @@ export default function CartPage() {
)
}
if (isError || !cart?.items || cart.items.length === 0) {
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">
@@ -101,18 +102,30 @@ export default function CartPage() {
map: t("address"),
}
const itemsBySeller = cart.items.reduce(
// Group items by seller (from channel)
const itemsBySeller = cartItems.reduce(
(acc, item) => {
const sellerId = item.seller.id
const sellerId = item.product.channel?.[0]?.id || 0
const sellerName = item.product.channel?.[0]?.name || "Unknown Seller"
if (!acc[sellerId]) {
acc[sellerId] = { seller: item.seller, items: [] }
acc[sellerId] = {
seller: { id: sellerId, name: sellerName },
items: []
}
}
acc[sellerId].items.push(item)
return acc
},
{} as Record<number, { seller: any; items: typeof cart.items }>,
{} as Record<number, { seller: any; items: typeof cartItems }>
)
// Calculate total
const totalAmount = cartItems.reduce((sum, item) => {
const price = parseFloat(item.product.price_amount || "0")
return sum + (price * item.product_quantity)
}, 0)
return (
<div className="container mx-auto px-4 py-8 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{translations.cart}</h1>
@@ -126,9 +139,34 @@ export default function CartPage() {
<div key={sellerId} className="mb-6">
<p className="text-base font-semibold mb-3">{seller.name}</p>
<div className="space-y-4">
{items.map((item) => (
<CartItemCard key={item.id} item={item} translations={translations} />
))}
{items.map((item) => {
const price = parseFloat(item.product.price_amount || "0")
const quantity = item.product_quantity
const total = price * quantity
return (
<CartItemCard
key={item.id}
item={{
...item,
quantity: quantity,
price: price,
total: total,
seller: seller,
price_formatted: `${item.product.price_amount} TMT`,
sub_total_formatted: `${item.product.price_amount} TMT`,
total_formatted: `${total.toFixed(2)} TMT`,
discount_formatted: "0 TMT",
product: {
...item.product,
image: item.product.media?.[0]?.images_800x800 || item.product.media?.[0]?.thumbnail,
images: item.product.media?.map(m => m.images_800x800 || m.thumbnail) || []
}
}}
translations={translations}
/>
)
})}
</div>
{Object.entries(itemsBySeller).length > 1 && <Separator className="mt-4" />}
</div>
@@ -141,10 +179,27 @@ export default function CartPage() {
order={{
id: 1,
seller: { id: 1, name: "Store" },
items: cart.items,
items: cartItems.map(item => ({
...item,
quantity: item.product_quantity,
price: parseFloat(item.product.price_amount || "0"),
total: parseFloat(item.product.price_amount || "0") * item.product_quantity,
seller: {
id: item.product.channel?.[0]?.id || 0,
name: item.product.channel?.[0]?.name || "Unknown"
}
})),
billing: {
body: [{ title: t("goods"), value: `${cart.total_formatted || `${cart.total} TMT`}` }],
footer: { title: t("total"), value: `${cart.total_formatted || `${cart.total} TMT`}` },
body: [
{
title: t("goods"),
value: `${totalAmount.toFixed(2)} TMT`
}
],
footer: {
title: t("total"),
value: `${totalAmount.toFixed(2)} TMT`
},
},
}}
translations={translations}
@@ -168,4 +223,4 @@ export default function CartPage() {
</div>
</div>
)
}
}

View File

@@ -1,29 +1,147 @@
"use client"
import { useState, useEffect, useRef } from "react"
import Image from "next/image"
import { Minus, Plus, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { useUpdateCartItemQuantity, useRemoveFromCart } from "@/lib/hooks"
import {
useUpdateCartItemQuantity,
useRemoveFromCart
} from "@/lib/hooks"
import type { CartItem, CartTranslations } from "./types"
interface CartItemCardProps {
item: CartItem
translations: CartTranslations
onUpdate?: () => void
}
export default function CartItemCard({ item, translations: t }: CartItemCardProps) {
const { mutate: updateQuantity, isPending: isUpdating } = useUpdateCartItemQuantity()
export default function CartItemCard({
item,
translations: t,
onUpdate
}: CartItemCardProps) {
const [localQuantity, setLocalQuantity] = useState(item.quantity)
const [pendingQuantity, setPendingQuantity] = useState(item.quantity)
const [isLoading, setIsLoading] = useState(false)
const updateTimeoutRef = useRef<NodeJS.Timeout>()
const { mutate: updateQuantity } = useUpdateCartItemQuantity()
const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart()
const handleQuantityChange = (delta: number) => {
const newQuantity = item.quantity + delta
if (newQuantity >= 1) {
updateQuantity({ itemId: item.id, quantity: newQuantity })
// Sync local quantity with server quantity
useEffect(() => {
setLocalQuantity(item.quantity)
setPendingQuantity(item.quantity)
}, [item.quantity])
// Debounced update effect
useEffect(() => {
if (pendingQuantity === item.quantity) {
return
}
// Clear previous timeout
if (updateTimeoutRef.current) {
clearTimeout(updateTimeoutRef.current)
}
// Set new timeout for update
updateTimeoutRef.current = setTimeout(() => {
setIsLoading(true)
if (pendingQuantity <= 0) {
removeItem(item.id, {
onSuccess: () => {
onUpdate?.()
},
onError: (error) => {
console.error("Failed to remove item:", error)
// Revert on error
setLocalQuantity(item.quantity)
setPendingQuantity(item.quantity)
},
onSettled: () => {
setIsLoading(false)
},
})
} else {
updateQuantity(
{ itemId: item.id, quantity: pendingQuantity },
{
onSuccess: () => {
onUpdate?.()
},
onError: (error) => {
console.error("Failed to update quantity:", error)
// Revert on error
setLocalQuantity(item.quantity)
setPendingQuantity(item.quantity)
},
onSettled: () => {
setIsLoading(false)
},
}
)
}
}, 300)
return () => {
if (updateTimeoutRef.current) {
clearTimeout(updateTimeoutRef.current)
}
}
}, [pendingQuantity, item.quantity, item.id, updateQuantity, removeItem, onUpdate])
const handleQuantityIncrease = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
if (isLoading) return
const newQuantity = localQuantity + 1
setLocalQuantity(newQuantity)
setPendingQuantity(newQuantity)
}
const handleQuantityDecrease = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
if (isLoading) return
const newQuantity = localQuantity - 1
if (newQuantity < 1) {
handleDelete()
return
}
setLocalQuantity(newQuantity)
setPendingQuantity(newQuantity)
}
const handleDelete = () => {
removeItem(item.id)
setIsLoading(true)
removeItem(item.id, {
onSuccess: () => {
onUpdate?.()
},
onError: (error) => {
console.error("Failed to remove item:", error)
},
onSettled: () => {
setIsLoading(false)
},
})
}
const getImageSrc = () => {
if (item.product.image) return item.product.image
if (item.product.images && item.product.images.length > 0) {
return item.product.images[0]
}
return "/placeholder.svg"
}
return (
@@ -33,7 +151,7 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
<div className="flex gap-4 flex-1">
<div className="relative w-[88px] h-[117px] rounded-xl border overflow-hidden flex-shrink-0">
<Image
src={item.product.image || item.product.images[0] || "/placeholder.svg"}
src={getImageSrc()}
alt={item.product.name}
fill
className="object-contain"
@@ -46,7 +164,7 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
variant="ghost"
size="sm"
onClick={handleDelete}
disabled={isRemoving}
disabled={isRemoving || isLoading}
className="w-fit p-0 h-auto hover:bg-transparent hover:text-red-500"
>
<Trash2 className="h-5 w-5" />
@@ -58,10 +176,14 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
<div className="space-y-1">
<p className="text-sm font-semibold">
{t.pricePerUnit} <span className="text-primary">{item.price_formatted || `${item.price} TMT`}</span>
{t.pricePerUnit}{" "}
<span className="text-primary">
{item.price_formatted || `${item.price} TMT`}
</span>
</p>
<p className="text-sm font-semibold">
{t.additionalPrice} {item.sub_total_formatted || `${item.total} TMT`}
{t.additionalPrice}{" "}
{item.sub_total_formatted || `${item.total} TMT`}
</p>
{item.discount_formatted && item.discount_formatted !== "0 TMT" && (
<p className="text-sm font-semibold">
@@ -81,18 +203,20 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
<Button
variant="outline"
size="icon"
onClick={() => handleQuantityChange(-1)}
disabled={item.quantity === 1 || isUpdating}
onClick={handleQuantityDecrease}
disabled={isLoading || isRemoving}
className="rounded-xl bg-blue-50"
>
<Minus className="h-4 w-4" />
</Button>
<div className="w-12 text-center font-semibold">{item.quantity}</div>
<div className="w-12 text-center font-semibold">
{localQuantity}
</div>
<Button
variant="outline"
size="icon"
onClick={() => handleQuantityChange(1)}
disabled={isUpdating}
onClick={handleQuantityIncrease}
disabled={isLoading || isRemoving}
className="rounded-xl bg-blue-50"
>
<Plus className="h-4 w-4" />
@@ -102,4 +226,4 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
</div>
</Card>
)
}
}

View File

@@ -1,12 +1,12 @@
import React from "react";
import { Truck, Warehouse } from "lucide-react";
import { Card } from "@/components/ui/card";
import { DeliveryType, CartTranslations } from "./types";
"use client"
import { Truck, Warehouse } from "lucide-react"
import { Card } from "@/components/ui/card"
import { DeliveryType, CartTranslations } from "./types"
interface DeliveryTypeSelectorProps {
selectedType: DeliveryType;
onSelect: (type: DeliveryType) => void;
translations: CartTranslations;
selectedType: DeliveryType
onSelect: (type: DeliveryType) => void
translations: CartTranslations
}
export default function DeliveryTypeSelector({
@@ -15,13 +15,13 @@ export default function DeliveryTypeSelector({
translations: t,
}: DeliveryTypeSelectorProps) {
const deliveryOptions: {
type: DeliveryType;
label: string;
icon: typeof Truck;
type: DeliveryType
label: string
icon: typeof Truck
}[] = [
{ type: "SELECTED_DELIVERY", label: t.delivery, icon: Truck },
{ type: "PICK_UP", label: t.pickup, icon: Warehouse },
];
]
return (
<div className="mb-6">
@@ -30,9 +30,9 @@ export default function DeliveryTypeSelector({
{deliveryOptions.map(({ type, label, icon: Icon }) => (
<Card
key={type}
className={`flex-1 cursor-pointer transition-all ${
className={`flex-1 cursor-pointer transition-all hover:shadow-md ${
selectedType === type
? "border-2 border-[#005bff]"
? "border-2 border-[#005bff] bg-blue-50"
: "border-2 border-gray-200"
}`}
onClick={() => onSelect(type)}
@@ -40,14 +40,18 @@ export default function DeliveryTypeSelector({
<div className="flex flex-col items-center justify-center p-4 gap-2">
<Icon
className={`h-8 w-8 ${
selectedType === type ? "text-[#005bff]" : ""
selectedType === type ? "text-[#005bff]" : "text-gray-600"
}`}
/>
<span className="text-xs">{label}</span>
<span className={`text-xs font-medium ${
selectedType === type ? "text-[#005bff]" : "text-gray-700"
}`}>
{label}
</span>
</div>
</Card>
))}
</div>
</div>
);
)
}

View File

@@ -6,9 +6,22 @@ import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select"
import DeliveryTypeSelector from "./DeliveryTypeSelector"
import type { Order, Region, Address, DeliveryType, CartTranslations, PaymentTypeOption } from "./types"
import type {
Order,
Region,
Address,
DeliveryType,
CartTranslations,
PaymentTypeOption
} from "./types"
interface OrderSummaryProps {
order: Order
@@ -51,6 +64,7 @@ export default function OrderSummary({
onCompleteOrder,
isLoading,
}: OrderSummaryProps) {
// Filter addresses based on selected region
const filteredAddresses = selectedRegion
? addresses.filter((addr) => {
const region = regions.find((r) => r.code === selectedRegion)
@@ -58,11 +72,12 @@ export default function OrderSummary({
})
: []
// Validate form completion
const isFormValid = selectedRegion && selectedAddress && paymentType
return (
<Card className="w-full md:w-[380px] p-6 rounded-xl h-fit sticky top-20">
{/* Payment Type */}
{/* Payment Type Selection */}
<div className="mb-6">
<h3 className="text-lg font-semibold mb-3">{t.paymentType}</h3>
<div className="flex gap-2">
@@ -70,7 +85,9 @@ export default function OrderSummary({
<Card
key={type.id}
className={`flex-1 cursor-pointer transition-all ${
paymentType?.id === type.id ? "border-2 border-[#005bff]" : "border-2 border-gray-200"
paymentType?.id === type.id
? "border-2 border-[#005bff]"
: "border-2 border-gray-200"
}`}
onClick={() => onPaymentTypeChange(type)}
>
@@ -82,13 +99,23 @@ export default function OrderSummary({
</div>
</div>
{/* Delivery Type */}
<DeliveryTypeSelector selectedType={deliveryType} onSelect={onDeliveryTypeChange} translations={t} />
{/* Delivery Type Selection */}
<DeliveryTypeSelector
selectedType={deliveryType}
onSelect={onDeliveryTypeChange}
translations={t}
/>
{/* Region Selection */}
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">{t.selectRegion}</Label>
<RadioGroup value={selectedRegion || ""} onValueChange={onRegionChange} className="flex flex-wrap gap-4">
<Label className="text-lg font-semibold mb-3 block">
{t.selectRegion}
</Label>
<RadioGroup
value={selectedRegion || ""}
onValueChange={onRegionChange}
className="flex flex-wrap gap-4"
>
{regions.map((region) => (
<div key={region.id} className="flex items-center space-x-2">
<RadioGroupItem
@@ -96,7 +123,10 @@ export default function OrderSummary({
id={`region-${region.id}`}
className="border-2 border-gray-400 data-[state=checked]:border-[#005bff] data-[state=checked]:bg-white data-[state=checked]:[&_svg]:fill-[#005bff] data-[state=checked]:[&_svg]:stroke-[#005bff]"
/>
<Label htmlFor={`region-${region.id}`} className="cursor-pointer">
<Label
htmlFor={`region-${region.id}`}
className="cursor-pointer"
>
{region.name}
</Label>
</div>
@@ -104,10 +134,12 @@ export default function OrderSummary({
</RadioGroup>
</div>
{/* Address Selection */}
{filteredAddresses.length > 0 && (
{/* Address Selection (only show when region is selected) */}
{selectedRegion && filteredAddresses.length > 0 && (
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">{t.selectAddress}</Label>
<Label className="text-lg font-semibold mb-3 block">
{t.selectAddress}
</Label>
<div className="flex gap-2">
<Select value={selectedAddress} onValueChange={onAddressChange}>
<SelectTrigger className="rounded-xl">
@@ -133,7 +165,7 @@ export default function OrderSummary({
</div>
)}
{/* Note */}
{/* Note Input */}
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">{t.note}</Label>
<Textarea
@@ -148,7 +180,10 @@ export default function OrderSummary({
{/* Billing Summary */}
<div className="space-y-2 mb-4">
{order.billing.body.map((item, index) => (
<div key={index} className="flex justify-between text-base font-medium">
<div
key={index}
className="flex justify-between text-base font-medium"
>
<span>{item.title}:</span>
<span>{item.value}</span>
</div>
@@ -157,21 +192,25 @@ export default function OrderSummary({
<Separator className="my-4" />
{/* Total */}
{/* Total Amount */}
<div className="flex justify-between items-center mb-6">
<span className="text-lg font-semibold">{order.billing.footer.title}:</span>
<span className="text-lg font-bold text-green-600">{order.billing.footer.value}</span>
<span className="text-lg font-semibold">
{order.billing.footer.title}:
</span>
<span className="text-lg font-bold text-green-600">
{order.billing.footer.value}
</span>
</div>
{/* Complete Order Button */}
<Button
onClick={onCompleteOrder}
disabled={!isFormValid || isLoading}
className="w-full rounded-xl bg-[#005bff] hover:bg-[#005bff] cursor-pointer h-12 text-lg font-bold disabled:opacity-50"
className="w-full rounded-xl bg-[#005bff] hover:bg-[#004dcc] cursor-pointer h-12 text-lg font-bold disabled:opacity-50 disabled:cursor-not-allowed"
size="lg"
>
{isLoading ? t.placeOrder + "..." : t.placeOrder}
{isLoading ? `${t.placeOrder}...` : t.placeOrder}
</Button>
</Card>
)
}
}

View File

@@ -6,14 +6,18 @@ export interface CartItem {
product: {
id: number
name: string
description?: string
images: (StaticImageData | string)[]
image?: StaticImageData | string
stock?: number
price_amount?: string
}
seller: {
id: number
name: string
}
quantity: number
product_quantity?: number // For compatibility with old API
price: number
total: number
price_formatted?: string
@@ -22,6 +26,15 @@ export interface CartItem {
total_formatted?: string
}
export interface Cart {
message: string
data: CartItem[]
errorDetails?: string
total?: number
total_formatted?: string
items?: CartItem[] // Alternative structure
}
export interface Order {
id: number
seller: {
@@ -85,3 +98,22 @@ export interface CartTranslations {
export type PaymentType = "CASH" | "CARD"
export type DeliveryType = "SELECTED_DELIVERY" | "PICK_UP"
// API Response types
export interface ApiResponse<T> {
message: string
data: T
errorDetails?: string
}
export interface CreateOrderPayload {
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
}

View File

@@ -1,262 +1,577 @@
"use client"
"use client";
import { useState } from "react"
import Link from "next/link"
import Image from "next/image"
import { useRouter, useSearchParams } from "next/navigation"
import { ChevronLeft, SlidersHorizontal, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Slider } from "@/components/ui/slider"
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { ScrollArea } from "@/components/ui/scroll-area"
import CategoryPageContent from "./CategoryContent"
import { notFound } from "next/navigation"
interface FilterItem {
key: string
value: number
name: string
hex?: string
image?: string
selected?: boolean
slug?: string
children?: FilterItem[]
}
interface Filter {
uuid: string
title: string
type: "TREE" | "SELECTABLE" | "VOLUME" | "TAB" | "COLOR"
items: FilterItem | FilterItem[]
}
import { useEffect, useState, useMemo, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ChevronLeft, SlidersHorizontal, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import { ScrollArea } from "@/components/ui/scroll-area";
import InfiniteScroll from "react-infinite-scroll-component";
import ProductCard from "@/components/ProductCard";
import Loader from "@/components/Loader";
import {
useCategories,
useAllCategoryProducts,
useAllCategoryProductsPaginated,
useCategoryProducts,
} from "@/lib/hooks/useCategories";
import { notFound } from "next/navigation";
import type { Category, Product } from "@/lib/types/api";
interface CategoryPageClientProps {
params: { locale: string; slug: string }
params: { locale: string; slug: string };
}
export default function CategoryPageClient({ params }: CategoryPageClientProps) {
const { slug, locale } = params
const router = useRouter()
const searchParams = useSearchParams()
const [isOpen, setIsOpen] = useState(false)
export default function CategoryPageClient({
params,
}: CategoryPageClientProps) {
const { slug, locale } = params;
const router = useRouter();
const searchParams = useSearchParams();
const [isOpen, setIsOpen] = useState(false);
// Fetch all categories first
const { data: categoriesData, isLoading: categoriesLoading } =
useCategories();
// Find category from slug
const selectedCategory = useMemo(() => {
if (!categoriesData || !slug) return null;
const findBySlug = (categories: Category[]): Category | null => {
for (const category of categories) {
if (category.slug === slug) return category;
if (category.children) {
const found = findBySlug(category.children);
if (found) return found;
}
}
return null;
};
return findBySlug(categoriesData);
}, [categoriesData, slug]);
// Track subcategories
const [hasSubcategories, setHasSubcategories] = useState(false);
const [subcategoriesToShow, setSubcategoriesToShow] = useState<Category[]>(
[]
);
// Pagination state
const [currentPage, setCurrentPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [allProducts, setAllProducts] = useState<Product[]>([]);
// Price sorting state
const [priceSort, setPriceSort] = useState<
"none" | "lowToHigh" | "highToLow"
>("none");
// Price filter state
const [priceRange, setPriceRange] = useState<[number, number]>([0, 10000])
const [priceRange, setPriceRange] = useState<[number, number]>([0, 10000]);
// Selected filters state
const [selectedFilters, setSelectedFilters] = useState<Record<string, Set<number>>>({
const [selectedFilters, setSelectedFilters] = useState<
Record<string, Set<number>>
>({
brand: new Set(),
color: new Set(),
tag: new Set(),
})
});
// Determine if category is a subcategory
const isSubCategory = useMemo(() => {
if (!categoriesData || !selectedCategory) return false;
const checkIsSubCategory = (
categories: Category[],
targetId: number
): boolean => {
for (const category of categories) {
if (category.children) {
for (const subCategory of category.children) {
if (subCategory.id === targetId) return true;
if (subCategory.children) {
const foundInNested = checkIsSubCategory([subCategory], targetId);
if (foundInNested) return true;
}
}
}
}
return false;
};
return checkIsSubCategory(categoriesData, selectedCategory.id);
}, [categoriesData, selectedCategory]);
// Fetch initial products for subcategories (first page only)
const { data: subcategoryProducts = [], isLoading: subcategoryLoading } =
useAllCategoryProducts(selectedCategory || undefined, {
enabled: !!selectedCategory && isSubCategory && currentPage === 1,
});
// Fetch paginated subcategory products (page 2+)
const {
data: paginatedSubcategoryData,
isLoading: subcategoryPaginatedLoading,
} = useAllCategoryProductsPaginated(selectedCategory || undefined, {
enabled: !!selectedCategory && isSubCategory && currentPage > 1,
page: currentPage,
limit: 6,
});
// Fetch paginated category products (for non-subcategories)
const {
data: paginatedCategoryData,
isLoading: categoryPaginatedLoading,
isFetching: categoryPaginatedFetching,
} = useCategoryProducts(selectedCategory?.id?.toString() || "", {
enabled: !!selectedCategory && !isSubCategory,
page: currentPage,
limit: 6,
});
const t = {
filter: "Filters",
from: "From",
to: "To",
reset: "Reset",
}
filter: "Filtreler",
from: "Min",
to: "Max",
reset: "Sıfırla",
total: "Toplam",
items: "ürün",
subCategories: "Alt Kategoriler",
composition: "Sıralama",
neverMind: "Varsayılan",
From_cheap_to_expensive: "Ucuzdan Pahalıya",
From_expensive_to_cheap: "Pahalıdan Ucuza",
brands: "Markalar",
noResults: "Ürün bulunamadı",
};
if (!slug) {
notFound()
notFound();
}
const filters: Filter[] = [
{
uuid: "1",
title: "Category",
type: "TREE",
items: {
key: "category",
value: 1,
name: "All",
slug: slug,
selected: true,
children: [
{ key: "category", value: 2, name: "Electronics", slug: "electronics", selected: false },
{ key: "category", value: 3, name: "Clothing", slug: "clothing", selected: false },
],
},
},
{
uuid: "2",
title: "Brand",
type: "SELECTABLE",
items: [
{ key: "brand", value: 10, name: "Brand A", image: "/brand-a.png", selected: false },
{ key: "brand", value: 11, name: "Brand B", image: "/brand-b.png", selected: false },
],
},
{
uuid: "3",
title: "Price",
type: "VOLUME",
items: {} as FilterItem,
},
{
uuid: "4",
title: "Color",
type: "COLOR",
items: [
{ key: "color", value: 100, name: "Red", hex: "#FF0000", selected: false },
{ key: "color", value: 101, name: "Blue", hex: "#0000FF", selected: false },
],
},
{
uuid: "5",
title: "Tags",
type: "TAB",
items: [
{ key: "tag", value: 200, name: "New Arrival", selected: false },
{ key: "tag", value: 201, name: "Sale", selected: false },
],
},
]
// Helper function to find category by ID
const findCategoryById = (
categories: Category[] | undefined,
id: number
): Category | null => {
if (!categories) return null;
for (const category of categories) {
if (category.id === id) return category;
if (category.children) {
const found = findCategoryById(category.children, id);
if (found) return found;
}
}
return null;
};
// Helper to check if product already exists in list
const isProductInList = (list: Product[], newProduct: Product) => {
return list.some((product) => product.id === newProduct.id);
};
// Setup subcategories when category changes
useEffect(() => {
if (selectedCategory) {
// Reset states
setAllProducts([]);
setHasMore(true);
setCurrentPage(1);
// Set subcategories
if (selectedCategory.children && selectedCategory.children.length > 0) {
setHasSubcategories(true);
setSubcategoriesToShow(selectedCategory.children);
} else {
setHasSubcategories(false);
setSubcategoriesToShow([]);
}
}
}, [selectedCategory?.id]);
// Handle first page products for subcategories
useEffect(() => {
if (
selectedCategory &&
isSubCategory &&
subcategoryProducts.length > 0 &&
currentPage === 1
) {
console.log("Setting subcategory products:", subcategoryProducts.length);
setAllProducts(subcategoryProducts);
setHasMore(true);
}
}, [selectedCategory, subcategoryProducts, currentPage, isSubCategory]);
// Handle paginated category products (non-subcategories)
useEffect(() => {
if (paginatedCategoryData && selectedCategory && !isSubCategory) {
console.log("Paginated category data:", paginatedCategoryData);
if (paginatedCategoryData.data && paginatedCategoryData.data.length > 0) {
setAllProducts((prevProducts) => {
if (currentPage === 1) {
return [...paginatedCategoryData.data];
}
const newProducts = paginatedCategoryData.data.filter(
(newProduct: Product) => !isProductInList(prevProducts, newProduct)
);
return [...prevProducts, ...newProducts];
});
setHasMore(!!paginatedCategoryData.pagination?.next_page_url);
} else if (currentPage === 1) {
setAllProducts([]);
setHasMore(false);
}
}
}, [paginatedCategoryData, currentPage, selectedCategory, isSubCategory]);
// Handle paginated subcategory products
useEffect(() => {
if (
paginatedSubcategoryData &&
selectedCategory &&
isSubCategory &&
currentPage > 1
) {
console.log("Paginated subcategory data:", paginatedSubcategoryData);
if (
paginatedSubcategoryData.data &&
paginatedSubcategoryData.data.length > 0
) {
setAllProducts((prevProducts) => {
const newProducts = paginatedSubcategoryData.data.filter(
(newProduct: Product) => !isProductInList(prevProducts, newProduct)
);
return [...prevProducts, ...newProducts];
});
setHasMore(paginatedSubcategoryData.pagination?.hasMorePages || false);
} else {
setHasMore(false);
}
}
}, [paginatedSubcategoryData, currentPage, selectedCategory, isSubCategory]);
const loadMoreData = useCallback(() => {
if (!hasMore || categoryPaginatedFetching || subcategoryPaginatedLoading)
return;
console.log("Loading more, page:", currentPage + 1);
setCurrentPage((prevPage) => prevPage + 1);
}, [
hasMore,
categoryPaginatedFetching,
subcategoryPaginatedLoading,
currentPage,
]);
const isLoading =
categoriesLoading ||
(subcategoryLoading && currentPage === 1) ||
(categoryPaginatedLoading && currentPage === 1);
const products = useMemo(() => {
let productsList = [...allProducts];
if (priceSort === "lowToHigh") {
return [...productsList].sort(
(a, b) =>
parseFloat(a.price_amount || "0") - parseFloat(b.price_amount || "0")
);
} else if (priceSort === "highToLow") {
return [...productsList].sort(
(a, b) =>
parseFloat(b.price_amount || "0") - parseFloat(a.price_amount || "0")
);
}
return productsList;
}, [priceSort, allProducts]);
const totalItems = useMemo(() => {
if (
paginatedCategoryData?.pagination &&
!isSubCategory &&
selectedCategory
) {
return paginatedCategoryData.pagination.total || products.length || 0;
}
return products.length || 0;
}, [paginatedCategoryData, products, isSubCategory, selectedCategory]);
const handlePriceSortChange = (
sortType: "none" | "lowToHigh" | "highToLow"
) => {
setPriceSort(sortType);
};
const handleSubCategorySelect = (subCategory: Category) => {
setAllProducts([]);
setCurrentPage(1);
setHasMore(true);
setPriceSort("none");
router.push(`/${locale}/category/${subCategory.slug}`, { scroll: false });
};
const handleCategoryClick = (category: Category) => {
setAllProducts([]);
setCurrentPage(1);
setHasMore(true);
router.push(`/${locale}/category/${category.slug}`);
};
const renderBreadcrumbs = () => {
if (!categoriesData || !selectedCategory) return null;
const breadcrumbs: Category[] = [];
let currentCategory = selectedCategory;
let parentId = currentCategory.parent_id;
breadcrumbs.unshift(currentCategory);
while (parentId) {
const parentCategory = findCategoryById(categoriesData, parentId);
if (parentCategory) {
breadcrumbs.unshift(parentCategory);
parentId = parentCategory.parent_id;
} else {
break;
}
}
return (
<div className="flex items-center gap-2 mb-4 text-sm">
{breadcrumbs.map((category, index) => (
<div key={category.id} className="flex items-center gap-2">
<button
onClick={() => handleCategoryClick(category)}
className="hover:text-primary transition-colors"
>
{category.name}
</button>
{index < breadcrumbs.length - 1 && <span>/</span>}
</div>
))}
</div>
);
};
const pageTitle = selectedCategory?.name || "Kategori";
const handleFilterChange = (key: string, value: number) => {
setSelectedFilters((prev) => {
const newFilters = { ...prev }
const newFilters = { ...prev };
if (!newFilters[key]) {
newFilters[key] = new Set()
newFilters[key] = new Set();
}
if (newFilters[key].has(value)) {
newFilters[key].delete(value)
newFilters[key].delete(value);
} else {
newFilters[key].add(value)
newFilters[key].add(value);
}
return newFilters
})
updateURLParams(key, Array.from(selectedFilters[key] || []))
}
return newFilters;
});
};
const handlePriceChange = (values: number[]) => {
setPriceRange([values[0], values[1]])
updateURLParams("price_min", values[0])
updateURLParams("price_max", values[1])
}
setPriceRange([values[0], values[1]]);
};
const handlePriceInputChange = (type: "from" | "to", value: string) => {
const numValue = parseInt(value) || 0
const numValue = parseInt(value) || 0;
if (type === "from") {
setPriceRange([numValue, priceRange[1]])
updateURLParams("price_min", numValue)
setPriceRange([numValue, priceRange[1]]);
} else {
setPriceRange([priceRange[0], numValue])
updateURLParams("price_max", numValue)
setPriceRange([priceRange[0], numValue]);
}
}
const updateURLParams = (key: string, value: number | number[]) => {
const params = new URLSearchParams(searchParams.toString())
if (Array.isArray(value)) {
params.delete(key)
value.forEach((v) => params.append(key, v.toString()))
} else {
params.set(key, value.toString())
}
router.push(`/${locale}/category/${slug}?${params.toString()}`, { scroll: false })
}
};
const resetFilters = () => {
setSelectedFilters({
brand: new Set(),
color: new Set(),
tag: new Set(),
})
setPriceRange([0, 10000])
router.push(`/${locale}/category/${slug}`)
}
});
setPriceRange([0, 10000]);
setPriceSort("none");
};
const FiltersContent = () => (
<div className="space-y-6">
{filters.map((filter) => {
switch (filter.type) {
case "TREE":
return (
<CategoryFilter
key={filter.uuid}
data={filter.items as FilterItem}
title={filter.title}
locale={locale}
/>
)
case "SELECTABLE":
return (
<BrandFilter
key={filter.uuid}
data={filter.items as FilterItem[]}
title={filter.title}
selectedValues={selectedFilters.brand}
onFilterChange={handleFilterChange}
/>
)
case "VOLUME":
return (
<PriceFilter
key={filter.uuid}
title={filter.title}
priceRange={priceRange}
onPriceChange={handlePriceChange}
onInputChange={handlePriceInputChange}
translations={{ from: t.from, to: t.to }}
/>
)
case "COLOR":
return (
<ColorFilter
key={filter.uuid}
data={filter.items as FilterItem[]}
title={filter.title}
selectedValues={selectedFilters.color}
onFilterChange={handleFilterChange}
/>
)
case "TAB":
return (
<TagFilter
key={filter.uuid}
data={filter.items as FilterItem[]}
title={filter.title}
selectedValues={selectedFilters.tag}
onFilterChange={handleFilterChange}
/>
)
default:
return null
}
})}
<Button variant="outline" className="w-full rounded-xl bg-transparent" onClick={resetFilters}>
{hasSubcategories && subcategoriesToShow.length > 0 && (
<div>
<h3 className="text-lg font-semibold mb-3">{t.subCategories}</h3>
<div className="space-y-1">
{subcategoriesToShow.map((subCategory) => (
<button
key={subCategory.id}
onClick={() => handleSubCategorySelect(subCategory)}
className={`w-full text-left py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors ${
slug === subCategory.slug
? "text-primary font-medium bg-gray-50"
: ""
}`}
>
{subCategory.name}
</button>
))}
</div>
</div>
)}
<div>
<h3 className="text-lg font-semibold mb-3">{t.composition}</h3>
<div className="space-y-2">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="sort"
checked={priceSort === "none"}
onChange={() => handlePriceSortChange("none")}
className="w-4 h-4"
/>
<span>{t.neverMind}</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="sort"
checked={priceSort === "lowToHigh"}
onChange={() => handlePriceSortChange("lowToHigh")}
className="w-4 h-4"
/>
<span>{t.From_cheap_to_expensive}</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="sort"
checked={priceSort === "highToLow"}
onChange={() => handlePriceSortChange("highToLow")}
className="w-4 h-4"
/>
<span>{t.From_expensive_to_cheap}</span>
</label>
</div>
</div>
<PriceFilter
title="Fiyat"
priceRange={priceRange}
onPriceChange={handlePriceChange}
onInputChange={handlePriceInputChange}
translations={{ from: t.from, to: t.to }}
/>
<Button
variant="outline"
className="w-full rounded-xl bg-transparent"
onClick={resetFilters}
>
{t.reset}
</Button>
</div>
)
);
if (isLoading) return <div>Loading...</div>;
if (!selectedCategory && !categoriesLoading) {
return <div className="text-center py-8">Kategori bulunamadı</div>;
}
console.log(
"Current products:",
products.length,
"Has more:",
hasMore,
"Page:",
currentPage
);
return (
<div className="flex gap-4">
{/* Desktop Filters - LEFT SIDE */}
<div className="hidden sm:block w-[280px] flex-shrink-0 border-r pr-4">
<ScrollArea className="h-[calc(100vh-120px)]">
<FiltersContent />
</ScrollArea>
</div>
<div className="flex flex-col gap-4">
{selectedCategory && renderBreadcrumbs()}
<h2 className="text-3xl font-bold">{pageTitle}</h2>
<p className="text-gray-600">
{t.total}: {totalItems} {t.items}
</p>
{/* Content - RIGHT SIDE */}
<div className="flex-1">
<CategoryPageContent slug={slug} filters={selectedFilters} priceRange={priceRange} />
<div className="flex gap-4">
{/* Desktop Filters - LEFT SIDE */}
<div className="hidden sm:block w-[280px] flex-shrink-0 border-r pr-4">
<ScrollArea className="h-[calc(100vh-200px)]">
<FiltersContent />
</ScrollArea>
</div>
{/* Content - RIGHT SIDE */}
<div className="flex-1">
{products.length > 0 ? (
<InfiniteScroll
dataLength={products.length}
next={loadMoreData}
hasMore={hasMore}
scrollThreshold={0.8}
style={{ overflow: "visible" }}
loader={
<div className="flex justify-center py-4">
<div>Loading...</div>
</div>
}
>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{products.map((product) => (
<ProductCard
key={product.id}
id={product.id}
name={product.name}
price={
product.price_amount
? parseFloat(product.price_amount)
: null
}
struct_price_text={`${product.price_amount} TMT`}
images={[product.media?.[0]?.images_400x400]}
is_favorite={false}
/>
))}
</div>
</InfiniteScroll>
) : (
<div className="text-center py-8 text-gray-500">{t.noResults}</div>
)}
</div>
</div>
{/* Mobile Filter Sheet */}
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetTrigger asChild>
<Button className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg" size="lg">
<Button
className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
size="lg"
>
{t.filter}
<SlidersHorizontal className="h-5 w-5" />
</Button>
@@ -269,7 +584,7 @@ export default function CategoryPageClient({ params }: CategoryPageClientProps)
className="absolute top-4 right-4 rounded-md ring-offset-background transition-opacity hover:opacity-100"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
<span className="sr-only">Kapat</span>
</button>
</SheetHeader>
<ScrollArea className="h-[calc(100vh-80px)] p-4">
@@ -278,96 +593,7 @@ export default function CategoryPageClient({ params }: CategoryPageClientProps)
</SheetContent>
</Sheet>
</div>
)
}
function CategoryFilter({
data,
title,
locale
}: {
data: FilterItem
title: string
locale: string
}) {
return (
<div>
<h3 className="text-lg font-semibold mb-3">{title}</h3>
<div className="space-y-1">
<Link
href={`/${locale}/category/${data.slug}?category_id=${data.value}`}
className={`flex items-center gap-2 py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors ${
data.selected ? "text-primary font-medium" : ""
}`}
>
<ChevronLeft className="h-4 w-4" />
{data.name}
</Link>
{data.children && data.children.length > 0 && (
<div className="ml-6 space-y-1">
{data.children.map((child) => (
<Link
key={child.value}
href={`/${locale}/category/${child.slug}?category_id=${child.value}`}
className={`block py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors ${
child.selected ? "text-primary font-medium" : ""
}`}
>
{child.name}
</Link>
))}
</div>
)}
</div>
</div>
)
}
function BrandFilter({
data,
title,
selectedValues,
onFilterChange,
}: {
data: FilterItem[]
title: string
selectedValues: Set<number>
onFilterChange: (key: string, value: number) => void
}) {
return (
<div>
<h3 className="text-lg font-semibold mb-3">{title}</h3>
<ScrollArea className="max-h-[410px]">
<div className="space-y-1">
{data.map((item) => {
const isSelected = selectedValues.has(item.value)
return (
<button
key={item.value}
onClick={() => onFilterChange(item.key, item.value)}
className={`w-full flex items-center gap-3 py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors group ${
isSelected ? "text-primary" : ""
}`}
>
{item.image && (
<div
className={`flex items-center justify-center w-[50px] h-[50px] bg-gray-50 rounded-lg border-2 transition-colors ${
isSelected ? "border-primary" : "border-transparent group-hover:border-primary"
}`}
>
<div className="relative w-8 h-8">
<Image src={item.image || "/placeholder.svg"} alt={item.name} fill className="object-contain" />
</div>
</div>
)}
<span className="text-left">{item.name}</span>
</button>
)
})}
</div>
</ScrollArea>
</div>
)
);
}
function PriceFilter({
@@ -377,11 +603,11 @@ function PriceFilter({
onInputChange,
translations,
}: {
title: string
priceRange: [number, number]
onPriceChange: (values: number[]) => void
onInputChange: (type: "from" | "to", value: string) => void
translations: { from: string; to: string }
title: string;
priceRange: [number, number];
onPriceChange: (values: number[]) => void;
onInputChange: (type: "from" | "to", value: string) => void;
translations: { from: string; to: string };
}) {
return (
<div>
@@ -413,78 +639,15 @@ function PriceFilter({
/>
</div>
</div>
<Slider min={0} max={99999} step={100} value={priceRange} onValueChange={onPriceChange} className="mt-2" />
<Slider
min={0}
max={99999}
step={100}
value={priceRange}
onValueChange={onPriceChange}
className="mt-2"
/>
</div>
</div>
)
);
}
function TagFilter({
data,
title,
selectedValues,
onFilterChange,
}: {
data: FilterItem[]
title: string
selectedValues: Set<number>
onFilterChange: (key: string, value: number) => void
}) {
return (
<div>
<h3 className="text-lg font-semibold mb-3">{title}</h3>
<div className="space-y-2">
{data.map((item) => {
const isSelected = selectedValues.has(item.value)
return (
<div key={item.value} className="flex items-center space-x-2">
<Checkbox
id={`tag-${item.value}`}
checked={isSelected}
onCheckedChange={() => onFilterChange(item.key, item.value)}
/>
<Label htmlFor={`tag-${item.value}`} className="text-sm font-normal cursor-pointer">
{item.name}
</Label>
</div>
)
})}
</div>
</div>
)
}
function ColorFilter({
data,
title,
selectedValues,
onFilterChange,
}: {
data: FilterItem[]
title: string
selectedValues: Set<number>
onFilterChange: (key: string, value: number) => void
}) {
return (
<div>
<h3 className="text-lg font-semibold mb-3">{title}</h3>
<div className="grid grid-cols-5 gap-2">
{data.map((item) => {
const isSelected = selectedValues.has(item.value)
return (
<button
key={item.value}
onClick={() => onFilterChange(item.key, item.value)}
className={`w-[36px] h-[36px] rounded-lg border-2 p-1 transition-all hover:scale-110 ${
isSelected ? "border-primary shadow-md" : "border-gray-200"
}`}
title={item.name}
>
<div className="w-full h-full rounded-md border-2 border-gray-200" style={{ backgroundColor: item.hex }} />
</button>
)
})}
</div>
</div>
)
}

View File

@@ -1,27 +1,74 @@
"use client"
import { useFavorites, useAddToCart, useRemoveFromFavorites } from "@/lib/hooks"
import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Heart, ShoppingCart } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import type { Product } from "@/lib/types/api"
"use client";
import {
useFavorites,
useAddToCart,
useRemoveFromFavorites,
} from "@/lib/hooks";
import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { Heart, ShoppingCart } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { useToast } from "@/hooks/use-toast";
import type { Favorite } from "@/lib/types/api";
export default function FavoritesPage() {
const [isHovered, setIsHovered] = useState<number | null>(null)
const [isHovered, setIsHovered] = useState<number | null>(null);
const { toast } = useToast();
const { data: favorites, isLoading, isError } = useFavorites()
const { mutate: removeFromFavorites } = useRemoveFromFavorites()
const { mutate: addToCart } = useAddToCart()
const { data: favorites, isLoading, isError } = useFavorites();
const { mutate: removeFromFavorites, isPending: isRemoving } =
useRemoveFromFavorites();
const { mutate: addToCart, isPending: isAddingToCart } = useAddToCart();
const t = {
favorites: "Избранные",
addToCart: "В корзину",
emptyFavorites: "У вас пока нет избранных товаров",
}
removedFromFavorites: "Товар удален из избранного",
addedToCart: "Товар добавлен в корзину",
error: "Произошла ошибка",
};
const handleRemoveFromFavorites = (productId: number) => {
removeFromFavorites(productId, {
onSuccess: () => {
toast({
title: t.removedFromFavorites,
});
},
onError: (error) => {
toast({
title: t.error,
description: error.message,
variant: "destructive",
});
},
});
};
const handleAddToCart = (productId: number) => {
addToCart(
{ productId },
{
onSuccess: () => {
toast({
title: t.addedToCart,
});
},
onError: (error) => {
toast({
title: t.error,
description: error.message,
variant: "destructive",
});
},
}
);
};
if (isLoading) {
return (
@@ -33,7 +80,7 @@ export default function FavoritesPage() {
))}
</div>
</div>
)
);
}
if (isError || !favorites || favorites.length === 0) {
@@ -44,38 +91,58 @@ export default function FavoritesPage() {
<p className="text-2xl text-gray-400">{t.emptyFavorites}</p>
</div>
</div>
)
);
}
return (
<div className="container mx-auto px-4 py-8 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.favorites}</h1>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
{favorites.map((favorite) => (
{favorites.map((favorite: Favorite) => (
<ProductCard
key={favorite.id}
productId={favorite.product_id}
key={favorite.created_at}
productId={favorite.product.id}
product={favorite.product}
onRemove={() => removeFromFavorites(favorite.product_id)}
onAddToCart={() => addToCart({ productId: favorite.product_id })}
onRemove={() => handleRemoveFromFavorites(favorite.product.id)}
onAddToCart={() => handleAddToCart(favorite.product.id)}
onHover={setIsHovered}
isHovered={isHovered === favorite.product_id}
isHovered={isHovered === favorite.product.id}
isRemoving={isRemoving}
isAddingToCart={isAddingToCart}
translations={t}
/>
))}
</div>
</div>
)
);
}
interface Product {
id: number;
name: string;
slug: string;
price_amount: string;
old_price_amount?: string | null;
media: Array<{
thumbnail: string;
images_400x400: string;
images_720x720: string;
images_800x800: string;
images_1200x1200: string;
}>;
stock: number;
}
interface ProductCardProps {
productId: number
product?: Product
onRemove: () => void
onAddToCart: () => void
onHover: (id: number | null) => void
isHovered: boolean
translations: { addToCart: string }
productId: number;
product: Product;
onRemove: () => void;
onAddToCart: () => void;
onHover: (id: number | null) => void;
isHovered: boolean;
isRemoving: boolean;
isAddingToCart: boolean;
translations: { addToCart: string };
}
function ProductCard({
@@ -85,70 +152,91 @@ function ProductCard({
onAddToCart,
onHover,
isHovered,
isRemoving,
isAddingToCart,
translations,
}: ProductCardProps) {
if (!product) return null
if (!product) return null;
// Получаем первое изображение из media
const imageUrl =
product.media?.[0]?.images_800x800 ||
product.media?.[0]?.thumbnail ||
"/placeholder.svg";
// Форматируем цену
const price = product.old_price_amount
? `${parseFloat(product.price_amount).toFixed(2)} TMT`
: `${parseFloat(product.price_amount).toFixed(2)} TMT`;
const oldPrice = product.old_price_amount
? `${parseFloat(product.old_price_amount).toFixed(2)} TMT`
: null;
return (
<Card
className="group overflow-hidden rounded-xl transition-shadow hover:shadow-lg relative"
className="group overflow-hidden rounded-xl transition-shadow hover:shadow-lg relative border-none"
onMouseEnter={() => onHover(productId)}
onMouseLeave={() => onHover(null)}
>
<Link href={`/product/${product.slug || productId}`} className="block">
<div className="relative aspect-square bg-gray-50">
{/* Labels */}
{product.labels && product.labels.length > 0 && (
<div className="absolute top-2 left-2 z-10 flex flex-col gap-1">
{product.labels.map((label) => (
<Badge
key={label.text}
className="text-white text-[10px] font-bold uppercase px-2 py-0.5"
style={{ backgroundColor: label.bg_color }}
>
{label.text}
</Badge>
))}
</div>
)}
{/* Favorite Button */}
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onRemove()
e.preventDefault();
e.stopPropagation();
onRemove();
}}
className="absolute top-2 right-2 z-10 bg-white rounded-full p-2 shadow-md hover:scale-110 transition-transform"
disabled={isRemoving}
className="absolute top-2 right-2 z-10 bg-white rounded-full p-2 shadow-md hover:scale-110 transition-transform disabled:opacity-50 disabled:cursor-not-allowed"
>
<Heart className="h-5 w-5 fill-red-500 text-red-500" />
</button>
{/* Product Image */}
<Image
src={product.image || product.images?.[0] || "/placeholder.svg"}
src={imageUrl}
alt={product.name}
fill
sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, (max-width: 1024px) 25vw, 20vw"
className="object-contain p-4 group-hover:scale-105 transition-transform"
priority={false}
/>
{/* Out of Stock Badge */}
{product.stock === 0 && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
<Badge variant="secondary" className="text-sm">
Нет в наличии
</Badge>
</div>
)}
</div>
{/* Product Info */}
<div className="p-3">
<h3 className="font-medium text-sm line-clamp-2 mb-2 min-h-[40px]">{product.name}</h3>
<h3 className="font-medium text-sm line-clamp-2 mb-2 min-h-[40px]">
{product.name}
</h3>
<div className="space-y-1">
<p className="text-lg font-bold">{product.struct_price_text || `$${product.price}`}</p>
{oldPrice && (
<p className="text-sm text-gray-400 line-through">{oldPrice}</p>
)}
<p className="text-lg font-bold text-blue-600">{price}</p>
</div>
</div>
</Link>
{/* Add to Cart Button */}
{isHovered && (
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-white to-transparent">
{/* Add to Cart Button - показывается при hover */}
{isHovered && product.stock > 0 && (
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-white via-white to-transparent">
<Button
onClick={(e) => {
e.preventDefault()
onAddToCart()
e.preventDefault();
onAddToCart();
}}
disabled={isAddingToCart}
className="w-full rounded-xl gap-2"
size="sm"
>
@@ -158,5 +246,5 @@ function ProductCard({
</div>
)}
</Card>
)
);
}

View File

@@ -15,6 +15,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { useToast } from "@/hooks/use-toast"
import { useOrders, useCancelOrder } from "@/lib/hooks"
import type { Order } from "@/lib/types/api"
@@ -25,51 +26,101 @@ interface OrdersPageProps {
export default function OrdersPageClient({ locale }: OrdersPageProps) {
const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false)
const [orderToCancel, setOrderToCancel] = useState<Order | null>(null)
const { toast } = useToast()
const { data: orders, isLoading, isError } = useOrders()
const { data: orders, isLoading, isError, error } = useOrders()
const { mutate: cancelOrder, isPending: isCancellingOrder } = useCancelOrder()
const t = {
orders: "Заказы",
myOrders: "Мои заказы",
active: "Активные",
completed: "Завершенные",
activeOrders: "Активные заказы",
completedOrders: "Завершенные заказы",
cancelOrder: "Отменить заказ",
keepOrder: "Оставить заказ",
areYouSure: "Вы уверены?",
cancelConfirmation: "Вы уверены, что хотите отменить этот заказ? Это действие нельзя отменить.",
cancelling: "Отмена...",
orderNumber: "Заказ №",
ordered: "Заказано",
completed: "Завершено",
estimatedDelivery: "Ожид. доставка",
quantity: "Кол-во",
total: "Итого",
noOrders: "У вас пока нет заказов",
noActiveOrders: "У вас нет активных заказов",
noCompletedOrders: "У вас нет завершенных заказов",
loadError: "Не удалось загрузить заказы. Пожалуйста, попробуйте позже.",
orderCancelled: "Заказ отменен",
orderCancelledDescription: "Ваш заказ был успешно отменен",
error: "Ошибка",
cannotCancelShipped: "Нельзя отменить заказ, который уже отправлен или доставлен",
}
const handleCancelOrder = (order: Order) => {
// Check if order can be cancelled
if (order.status === "shipped" || order.status === "delivered") {
toast({
title: t.error,
description: t.cannotCancelShipped,
variant: "destructive",
})
return
}
setOrderToCancel(order)
setIsCancelDialogOpen(true)
}
const confirmCancelOrder = () => {
if (orderToCancel) {
cancelOrder(orderToCancel.id, {
onSuccess: () => {
setIsCancelDialogOpen(false)
setOrderToCancel(null)
},
})
}
if (!orderToCancel) return
cancelOrder(orderToCancel.id, {
onSuccess: () => {
toast({
title: t.orderCancelled,
description: t.orderCancelledDescription,
})
setIsCancelDialogOpen(false)
setOrderToCancel(null)
},
onError: (error: any) => {
toast({
title: t.error,
description: error.message || "Не удалось отменить заказ",
variant: "destructive",
})
},
})
}
const getStatusBadge = (status: Order["status"]) => {
switch (status) {
case "pending":
return <Badge variant="outline">{status}</Badge>
case "processing":
return <Badge variant="secondary">{status}</Badge>
case "shipped":
return <Badge variant="default">{status}</Badge>
case "delivered":
return <Badge className="bg-green-600">{status}</Badge>
case "cancelled":
return <Badge variant="destructive">{status}</Badge>
default:
return <Badge>{status}</Badge>
const statusMap: Record<string, { label: string; variant: string; className?: string }> = {
pending: { label: "Ожидание", variant: "outline" },
processing: { label: "Обработка", variant: "secondary" },
shipped: { label: "Отправлен", variant: "default" },
delivered: { label: "Доставлен", variant: "default", className: "bg-green-600" },
cancelled: { label: "Отменен", variant: "destructive" },
}
const statusInfo = statusMap[status] || { label: status, variant: "default" }
return (
<Badge variant={statusInfo.variant as any} className={statusInfo.className}>
{statusInfo.label}
</Badge>
)
}
const activeOrders = orders?.filter((o) => ["pending", "processing", "shipped"].includes(o.status)) || []
const completedOrders = orders?.filter((o) => ["delivered", "cancelled"].includes(o.status)) || []
return (
<div className="container mx-auto p-4">
<h1 className="text-3xl font-bold mb-6">My Orders</h1>
{isLoading ? (
if (isLoading) {
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<div className="space-y-4">
<Skeleton className="h-10 w-40" />
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
@@ -78,150 +129,110 @@ export default function OrdersPageClient({ locale }: OrdersPageProps) {
))}
</div>
</div>
) : isError ? (
</div>
)
}
if (isError) {
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<div className="bg-red-50 p-4 rounded-lg border border-red-200">
<p className="text-red-600">Failed to load orders. Please try again later.</p>
<p className="text-red-600">{t.loadError}</p>
{error && <p className="text-sm text-red-500 mt-2">{error.message}</p>}
</div>
) : !orders || orders.length === 0 ? (
<p className="text-gray-500">You have no orders yet.</p>
) : (
<Tabs defaultValue="active" className="w-full">
<TabsList className="mb-6">
<TabsTrigger value="active">Active Orders ({activeOrders.length})</TabsTrigger>
<TabsTrigger value="completed">Completed Orders ({completedOrders.length})</TabsTrigger>
</TabsList>
</div>
)
}
<TabsContent value="active">
{activeOrders.length === 0 ? (
<p className="text-gray-500">You have no active orders.</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{activeOrders.map((order) => (
<Card key={order.id} className="p-4 flex flex-col justify-between">
<div>
<div className="flex justify-between items-center mb-3">
<h3 className="text-lg font-semibold">Order #{order.id}</h3>
{getStatusBadge(order.status)}
</div>
<div className="mb-3">
<p className="text-sm text-gray-600">
Ordered: {new Date(order.created_at).toLocaleDateString()}
</p>
{order.estimated_delivery && (
<p className="text-sm text-gray-600">Est. Delivery: {order.estimated_delivery}</p>
)}
</div>
<div className="space-y-2 mb-3">
{order.items?.map((item) => (
<div key={item.id} className="flex items-start gap-3">
{item.product?.image && (
<Image
src={item.product.image || "/placeholder.svg"}
alt={item.product.name}
width={50}
height={50}
className="rounded"
/>
)}
<div className="flex-1">
<p className="text-sm font-medium">{item.product?.name}</p>
<p className="text-xs text-gray-500">Qty: {item.quantity}</p>
</div>
</div>
))}
</div>
<div className="border-t pt-3">
<div className="flex justify-between font-semibold">
<span>Total</span>
<span>{order.total_formatted || `$${order.total}`}</span>
</div>
</div>
</div>
<div className="mt-4">
<Button
variant="destructive"
onClick={() => handleCancelOrder(order)}
disabled={isCancellingOrder || order.status === "shipped" || order.status === "delivered"}
>
Cancel Order
</Button>
</div>
</Card>
))}
</div>
)}
</TabsContent>
if (!orders || orders.length === 0) {
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<div className="flex items-center justify-center min-h-[60vh]">
<p className="text-2xl text-gray-400">{t.noOrders}</p>
</div>
</div>
)
}
<TabsContent value="completed">
{completedOrders.length === 0 ? (
<p className="text-gray-500">You have no completed orders.</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{completedOrders.map((order) => (
<Card key={order.id} className="p-4">
<div>
<div className="flex justify-between items-center mb-3">
<h3 className="text-lg font-semibold">Order #{order.id}</h3>
{getStatusBadge(order.status)}
</div>
<div className="mb-3">
<p className="text-sm text-gray-600">
Ordered: {new Date(order.created_at).toLocaleDateString()}
</p>
{order.updated_at && (
<p className="text-sm text-gray-600">
Completed: {new Date(order.updated_at).toLocaleDateString()}
</p>
)}
</div>
<div className="space-y-2 mb-3">
{order.items?.map((item) => (
<div key={item.id} className="flex items-start gap-3">
{item.product?.image && (
<Image
src={item.product.image || "/placeholder.svg"}
alt={item.product.name}
width={50}
height={50}
className="rounded"
/>
)}
<div className="flex-1">
<p className="text-sm font-medium">{item.product?.name}</p>
<p className="text-xs text-gray-500">Qty: {item.quantity}</p>
</div>
</div>
))}
</div>
<div className="border-t pt-3">
<div className="flex justify-between font-semibold">
<span>Total</span>
<span>{order.total_formatted || `$${order.total}`}</span>
</div>
</div>
</div>
</Card>
))}
</div>
)}
</TabsContent>
</Tabs>
)}
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<Tabs defaultValue="active" className="w-full">
<TabsList className="mb-6">
<TabsTrigger value="active">
{t.activeOrders} ({activeOrders.length})
</TabsTrigger>
<TabsTrigger value="completed">
{t.completedOrders} ({completedOrders.length})
</TabsTrigger>
</TabsList>
<TabsContent value="active">
{activeOrders.length === 0 ? (
<div className="flex items-center justify-center min-h-[40vh]">
<p className="text-xl text-gray-400">{t.noActiveOrders}</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{activeOrders.map((order) => (
<OrderCard
key={order.id}
order={order}
onCancel={handleCancelOrder}
isCancelling={isCancellingOrder}
getStatusBadge={getStatusBadge}
translations={t}
showCancelButton
/>
))}
</div>
)}
</TabsContent>
<TabsContent value="completed">
{completedOrders.length === 0 ? (
<div className="flex items-center justify-center min-h-[40vh]">
<p className="text-xl text-gray-400">{t.noCompletedOrders}</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{completedOrders.map((order) => (
<OrderCard
key={order.id}
order={order}
onCancel={handleCancelOrder}
isCancelling={isCancellingOrder}
getStatusBadge={getStatusBadge}
translations={t}
showCancelButton={false}
/>
))}
</div>
)}
</TabsContent>
</Tabs>
<Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Cancel Order #{orderToCancel?.id}</DialogTitle>
<DialogDescription>
Are you sure you want to cancel this order? This action cannot be undone.
</DialogDescription>
<DialogTitle>
{t.cancelOrder} #{orderToCancel?.id}
</DialogTitle>
<DialogDescription>{t.cancelConfirmation}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setIsCancelDialogOpen(false)}>
Keep Order
<Button
variant="outline"
onClick={() => setIsCancelDialogOpen(false)}
disabled={isCancellingOrder}
>
{t.keepOrder}
</Button>
<Button variant="destructive" onClick={confirmCancelOrder} disabled={isCancellingOrder}>
{isCancellingOrder ? "Cancelling..." : "Cancel Order"}
{isCancellingOrder ? t.cancelling : t.cancelOrder}
</Button>
</DialogFooter>
</DialogContent>
@@ -229,3 +240,95 @@ export default function OrdersPageClient({ locale }: OrdersPageProps) {
</div>
)
}
interface OrderCardProps {
order: Order
onCancel: (order: Order) => void
isCancelling: boolean
getStatusBadge: (status: Order["status"]) => React.ReactNode
translations: any
showCancelButton: boolean
}
function OrderCard({
order,
onCancel,
isCancelling,
getStatusBadge,
translations: t,
showCancelButton,
}: OrderCardProps) {
const canCancel =
showCancelButton && order.status !== "shipped" && order.status !== "delivered" && order.status !== "cancelled"
return (
<Card className="p-4 flex flex-col justify-between">
<div>
<div className="flex justify-between items-center mb-3">
<h3 className="text-lg font-semibold">
{t.orderNumber}{order.id}
</h3>
{getStatusBadge(order.status)}
</div>
<div className="mb-3 space-y-1">
<p className="text-sm text-gray-600">
{t.ordered}: {new Date(order.created_at).toLocaleDateString()}
</p>
{order.estimated_delivery && (
<p className="text-sm text-gray-600">
{t.estimatedDelivery}: {order.estimated_delivery}
</p>
)}
{!showCancelButton && order.updated_at && (
<p className="text-sm text-gray-600">
{t.completed}: {new Date(order.updated_at).toLocaleDateString()}
</p>
)}
</div>
<div className="space-y-2 mb-3 max-h-48 overflow-y-auto">
{order.items?.map((item) => (
<div key={item.id} className="flex items-start gap-3">
{item.product?.image && (
<Image
src={item.product.image || "/placeholder.svg"}
alt={item.product.name}
width={50}
height={50}
className="rounded object-cover"
/>
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium line-clamp-2">{item.product?.name}</p>
<p className="text-xs text-gray-500">
{t.quantity}: {item.quantity}
</p>
</div>
</div>
))}
</div>
<div className="border-t pt-3">
<div className="flex justify-between font-semibold">
<span>{t.total}</span>
<span>{order.total_formatted || `$${order.total}`}</span>
</div>
</div>
</div>
{canCancel && (
<div className="mt-4">
<Button
variant="destructive"
onClick={() => onCancel(order)}
disabled={isCancelling}
className="w-full"
>
{t.cancelOrder}
</Button>
</div>
)}
</Card>
)
}

View File

@@ -7,73 +7,105 @@ import { Minus, Plus, Heart, ShoppingCart, Store } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Separator } from "@/components/ui/separator"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import placeholder from "@/public/jb.webp"
import { useProduct, useCategories } from "@/lib/hooks"
import { Skeleton } from "@/components/ui/skeleton"
import { useProductsBySlug } from "@/lib/hooks/useProducts"
import { useAddToCart, useUpdateCartItemQuantity, useCart } from "@/lib/hooks/useCart"
import { toast } from "sonner"
interface ProductDetailProps {
slug: string
}
const ProductPageContent = ({ slug }: ProductDetailProps) => {
const [isClient, setIsClient] = useState(false)
const [selectedImage, setSelectedImage] = useState(0)
const [quantity, setQuantity] = useState(1)
const [isFavorite, setIsFavorite] = useState(false)
const [isInCart, setIsInCart] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const { data: product, isLoading: productLoading, error } = useProduct(slug)
const { data: categoriesData } = useCategories()
if (!isClient) {
typeof window !== "undefined" && setIsClient(true)
}
// Get product data
const { data: product, isLoading: productLoading, error } = useProductsBySlug(slug)
// Get cart data to check if product is already in cart
const { data: cartData } = useCart()
// Cart mutations
const addToCartMutation = useAddToCart()
const updateCartMutation = useUpdateCartItemQuantity()
const t = {
addToCart: "Add to Cart",
goToCart: "Go to Cart",
price: "Price:",
aboutProduct: "About Product",
brand: "Brand",
model: "Model",
description: "Product Description",
recommended: "Recommended Products",
store: "Store",
writeToStore: "Write to Store",
color: "Color:",
addToCart: "Sebede goş",
goToCart: "Sebede git",
price: "Bahasy:",
aboutProduct: "Haryt barada",
brand: "Marka",
stock: "Mukdary",
description: "Düşündiriş",
store: "Dükan",
writeToStore: "Dükana ýaz",
color: "Reňk:",
category: "Kategoriýa:",
barcode: "Barkod:",
addedToCart: "Sebede goşuldy",
updatedCart: "Sebe täzelendi",
error: "Ýalňyşlyk ýüze çykdy",
}
// Check if product is in cart
const cartItem = cartData?.data?.find((item: any) => item.product?.id === product?.id)
const isInCart = !!cartItem
const handleAddToCart = async () => {
setIsLoading(true)
if (!product?.id) return
try {
// TODO: implement cart API call
await new Promise((resolve) => setTimeout(resolve, 500))
setIsInCart(true)
} finally {
setIsLoading(false)
await addToCartMutation.mutateAsync({
productId: product.id,
quantity: quantity,
})
toast.success(t.addedToCart, {
description: `${product.name} sebede goşuldy`,
})
} catch (error) {
console.error("Add to cart error:", error)
toast.error(t.error, {
description: "Haryt sebede goşup bolmady",
})
}
}
const handleQuantityChange = async (newQuantity: number) => {
if (newQuantity < 1) return
setIsLoading(true)
try {
setQuantity(newQuantity)
// TODO: implement cart quantity update API call
await new Promise((resolve) => setTimeout(resolve, 300))
} finally {
setIsLoading(false)
if (newQuantity < 1 || !product?.id) return
if (newQuantity > product.stock) return
setQuantity(newQuantity)
// If product is already in cart, update it
if (isInCart) {
try {
await updateCartMutation.mutateAsync({
productId: product.id,
quantity: newQuantity,
})
toast.success(t.updatedCart, {
description: `Mukdar: ${newQuantity}`,
})
} catch (error) {
console.error("Update cart error:", error)
toast.error(t.error, {
description: "Mukdar täzelenip bolmady",
})
}
}
}
const handleToggleFavorite = () => {
setIsFavorite(!isFavorite)
// TODO: implement favorites API call
// TODO: Implement favorites API
}
// Loading state
if (productLoading) {
return (
<div className="container mx-auto px-4 py-8">
@@ -95,14 +127,21 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
)
}
// Error state
if (error || !product) {
return (
<div className="container mx-auto px-4 py-8 text-center">
<h2 className="text-2xl font-bold text-red-600">Product not found</h2>
<h2 className="text-2xl font-bold text-red-600">Haryt tapylmady</h2>
<p className="text-gray-500 mt-2">Bu haryt ýok ýa-da aýryldy</p>
</div>
)
}
// Extract image URLs from media array
const imageUrls = product.media?.map(m => m.images_800x800 || m.images_720x720 || m.thumbnail) || []
const isLoading = addToCartMutation.isPending || updateCartMutation.isPending
return (
<div className="container mx-auto px-4 py-8">
<div className="flex flex-col lg:flex-row gap-8">
@@ -110,42 +149,37 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
<div className="flex-1 max-w-2xl">
<div className="relative">
<div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-gray-50">
{product.labels && product.labels.length > 0 && (
<div className="absolute top-0 right-0 z-10 flex flex-col gap-1">
{product.labels.map((label) => (
<Badge
key={label.text}
className="rounded-l-md rounded-r-none text-white text-xs font-bold uppercase"
style={{ backgroundColor: label.bg_color }}
>
{label.text}
</Badge>
))}
{imageUrls.length > 0 ? (
<Image
src={imageUrls[selectedImage]}
alt={product.name}
fill
className="object-contain"
priority
/>
) : (
<div className="flex items-center justify-center h-full text-gray-400">
Surat ýok
</div>
)}
<Image
src={product.images?.[selectedImage] || product.image || placeholder}
alt={product.name}
fill
className="object-contain"
priority
/>
</div>
{/* Thumbnail Images */}
{product.images && product.images.length > 1 && (
{imageUrls.length > 1 && (
<div className="mt-4 flex gap-2 overflow-x-auto pb-2">
{product.images.map((image, index) => (
{imageUrls.map((image, index) => (
<button
key={index}
onClick={() => setSelectedImage(index)}
className={`relative w-16 h-16 rounded overflow-hidden border ${
selectedImage === index ? "border-black" : "border-transparent"
className={`relative w-16 h-16 flex-shrink-0 rounded 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 || "/placeholder.svg"}
alt={`${product.name} thumbnail ${index + 1}`}
src={image}
alt={`${product.name} ${index + 1}`}
fill
className="object-cover"
/>
@@ -160,60 +194,121 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
<div className="flex-1 space-y-6">
<div>
<h1 className="text-3xl font-bold mb-2">{product.name}</h1>
{product.category && (
<div className="flex gap-2 flex-wrap">
<span className="text-sm text-gray-500">Category: {product.category}</span>
{product.categories && product.categories.length > 0 && (
<div className="flex gap-2 flex-wrap mt-2">
{product.categories.map((cat, idx) => (
<span
key={idx}
className="text-sm px-3 py-1 bg-gray-100 rounded-full text-gray-600"
>
{cat.name}
</span>
))}
</div>
)}
</div>
{/* Product Info Table */}
<Card className="p-4 rounded-xl">
<Card className="p-4 rounded-xl border-gray-200">
<h3 className="text-xl font-semibold mb-4">{t.aboutProduct}</h3>
<div className="space-y-3">
{product.brand && (
{product.brand?.name && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t.brand}</span>
<span className="font-medium">{product.brand}</span>
<span className="font-medium">{product.brand.name}</span>
</div>
<Separator />
</>
)}
{product.stock !== undefined && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">Stock</span>
<span className="font-medium">{product.stock}</span>
<span className="text-gray-500">{t.stock}</span>
<span className={`font-medium ${product.stock === 0 ? 'text-red-500' : 'text-green-600'}`}>
{product.stock === 0 ? 'Ýok' : product.stock}
</span>
</div>
<Separator />
</>
)}
{product.barcode && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t.barcode}</span>
<span className="font-mono text-sm">{product.barcode}</span>
</div>
<Separator />
</>
)}
{product.colour && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t.color}</span>
<span className="font-medium">{product.colour}</span>
</div>
<Separator />
</>
)}
{product.properties && product.properties.length > 0 && (
<>
{product.properties.map((prop, idx) => (
prop.value && (
<div key={idx}>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{prop.name}</span>
<span className="font-medium">{prop.value}</span>
</div>
{idx < product.properties.length - 1 && <Separator />}
</div>
)
))}
</>
)}
</div>
</Card>
{/* Description */}
{product.description && (
<div>
<Card className="p-4 rounded-xl border-gray-200">
<h3 className="text-xl font-semibold mb-3">{t.description}</h3>
<p className="text-gray-700 leading-relaxed">{product.description}</p>
</div>
<div
className="text-gray-700 leading-relaxed prose prose-sm max-w-none"
dangerouslySetInnerHTML={{ __html: product.description }}
/>
</Card>
)}
</div>
{/* Price & Actions Sidebar */}
<div className="lg:w-[420px] space-y-4">
<Card className="p-6 rounded-xl shadow-lg">
<div className="flex justify-between items-center mb-6">
<div className="lg:w-[380px] space-y-4">
<Card className="p-6 rounded-xl shadow-lg sticky top-4">
<div className="flex justify-between items-start mb-6">
<span className="text-lg text-gray-500">{t.price}</span>
<span className="text-3xl font-bold">${product.price}</span>
<div className="flex flex-col items-end">
<span className="text-3xl font-bold text-primary">
{product.price_amount} TMT
</span>
{product.old_price_amount && parseFloat(product.old_price_amount) > 0 && (
<span className="text-lg text-gray-400 line-through">
{product.old_price_amount} TMT
</span>
)}
</div>
</div>
<div className="space-y-4">
<div className="space-y-3">
{isInCart ? (
<div className="space-y-3">
<>
<Link href="/cart">
<Button size="lg" className="w-full rounded-xl text-lg font-bold bg-green-600 hover:bg-green-700">
<Button
size="lg"
className="w-full rounded-xl text-lg font-bold bg-green-600 hover:bg-green-700"
>
<ShoppingCart className="mr-2 h-5 w-5" />
{t.goToCart}
</Button>
@@ -225,31 +320,33 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
size="icon"
onClick={() => handleQuantityChange(quantity - 1)}
disabled={quantity === 1 || isLoading}
className="rounded-xl bg-blue-50 flex-shrink-0"
className="rounded-xl h-12 w-12"
>
<Minus className="h-5 w-5" />
</Button>
<div className="flex-1 text-center font-semibold text-lg">{quantity}</div>
<div className="flex-1 text-center font-semibold text-xl border rounded-xl h-12 flex items-center justify-center">
{quantity}
</div>
<Button
variant="outline"
size="icon"
onClick={() => handleQuantityChange(quantity + 1)}
disabled={isLoading}
className="rounded-xl bg-blue-50 flex-shrink-0"
disabled={isLoading || quantity >= product.stock}
className="rounded-xl h-12 w-12"
>
<Plus className="h-5 w-5" />
</Button>
</div>
</div>
</>
) : (
<Button
size="lg"
onClick={handleAddToCart}
disabled={isLoading}
disabled={isLoading || product.stock === 0}
className="w-full rounded-xl text-lg font-bold"
>
<ShoppingCart className="mr-2 h-5 w-5" />
{t.addToCart}
{isLoading ? "Goşulýar..." : product.stock === 0 ? "Haryt ýok" : t.addToCart}
</Button>
)}
@@ -257,36 +354,48 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
variant="outline"
size="lg"
onClick={handleToggleFavorite}
className={`w-full rounded-xl ${
isFavorite ? "bg-red-50 border-red-200 hover:bg-red-100" : "bg-blue-50"
className={`w-full rounded-xl transition-all ${
isFavorite
? "bg-red-50 border-red-300 hover:bg-red-100"
: "hover:bg-gray-50"
}`}
>
<Heart className={`h-6 w-6 ${isFavorite ? "fill-red-500 text-red-500" : ""}`} />
<Heart
className={`h-6 w-6 transition-all ${
isFavorite ? "fill-red-500 text-red-500" : "text-gray-600"
}`}
/>
</Button>
</div>
</Card>
{/* Seller Card */}
<Card className="p-6 rounded-xl">
<div className="flex items-center gap-4 mb-4">
<Avatar className="w-14 h-14">
<AvatarFallback>
<Store className="h-6 w-6" />
</AvatarFallback>
</Avatar>
<div>
<p className="text-sm text-gray-500">{t.store}</p>
<h4 className="text-xl font-bold hover:text-primary cursor-pointer">Official Store</h4>
{/* Store/Channel Card */}
{product.channel && product.channel.length > 0 && (
<Card className="p-6 rounded-xl">
<div className="flex items-center gap-4 mb-4">
<Avatar className="w-14 h-14 bg-primary/10">
<AvatarFallback className="bg-transparent">
<Store className="h-6 w-6 text-primary" />
</AvatarFallback>
</Avatar>
<div>
<p className="text-sm text-gray-500">{t.store}</p>
<h4 className="text-lg font-bold">{product.channel[0].name}</h4>
</div>
</div>
</div>
<Button variant="outline" size="lg" disabled className="w-full rounded-xl bg-transparent">
{t.writeToStore}
</Button>
</Card>
<Button
variant="outline"
size="lg"
className="w-full rounded-xl"
>
{t.writeToStore}
</Button>
</Card>
)}
</div>
</div>
</div>
)
}
export default ProductPageContent
export default ProductPageContent