connect some api

This commit is contained in:
Jelaletdin12
2025-11-22 20:59:28 +05:00
parent 4fe0fb3d4e
commit 2857d34f4d
24 changed files with 1233 additions and 893 deletions

View File

@@ -1,7 +1,7 @@
"use client";
import { useEffect, useState, useMemo, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { SlidersHorizontal, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -15,13 +15,13 @@ import {
SheetTrigger,
} from "@/components/ui/sheet";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Checkbox } from "@/components/ui/checkbox";
import InfiniteScroll from "react-infinite-scroll-component";
import ProductCard from "@/components/ProductCard";
import ProductCard from "@/features/home/components/ProductCard";
import {
useCategories,
useAllCategoryProducts,
useAllCategoryProductsPaginated,
useCategoryProducts,
useCategoryFilters,
useFilteredCategoryProducts,
} from "@/features/category/hooks/useCategories";
import { notFound } from "next/navigation";
import { useTranslations } from "next-intl";
@@ -36,15 +36,12 @@ export default function CategoryPageClient({
}: CategoryPageClientProps) {
const { slug, locale } = params;
const router = useRouter();
const searchParams = useSearchParams();
const [isOpen, setIsOpen] = useState(false);
const t = useTranslations();
// Fetch all categories first
const { data: categoriesData, isLoading: categoriesLoading } =
useCategories();
// Find category from slug
const selectedCategory = useMemo(() => {
if (!categoriesData || !slug) return null;
@@ -62,95 +59,167 @@ export default function CategoryPageClient({
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 [selectedBrands, setSelectedBrands] = useState<Set<number>>(new Set());
const [selectedFilterCategories, setSelectedFilterCategories] = useState<
Set<number>
>(new Set());
// Selected filters state
const [selectedFilters, setSelectedFilters] = useState<
Record<string, Set<number>>
>({
brand: new Set(),
color: new Set(),
tag: new Set(),
});
// Fetch filters
const { data: filtersData, isLoading: filtersLoading } = useCategoryFilters(
selectedCategory?.id,
{ enabled: !!selectedCategory }
);
// 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;
// Build filter params
const filterParams = useMemo(() => {
const params: any = {
page: currentPage,
limit: 6,
};
return checkIsSubCategory(categoriesData, selectedCategory.id);
}, [categoriesData, selectedCategory]);
if (selectedBrands.size > 0) {
params.brands = Array.from(selectedBrands);
}
// Fetch initial products for subcategories (first page only)
const { data: subcategoryProducts = [], isLoading: subcategoryLoading } =
useAllCategoryProducts(selectedCategory || undefined, {
enabled: !!selectedCategory && isSubCategory && currentPage === 1,
if (selectedFilterCategories.size > 0) {
params.categories = Array.from(selectedFilterCategories);
}
if (priceRange[0] > 0) {
params.min_price = priceRange[0];
}
if (priceRange[1] < 10000) {
params.max_price = priceRange[1];
}
return params;
}, [currentPage, selectedBrands, selectedFilterCategories, priceRange]);
// Fetch filtered products
const {
data: productsData,
isLoading: productsLoading,
isFetching,
} = useFilteredCategoryProducts(
selectedCategory?.id?.toString() || "",
filterParams,
{ enabled: !!selectedCategory }
);
// Reset on category change
useEffect(() => {
if (selectedCategory) {
setAllProducts([]);
setCurrentPage(1);
setSelectedBrands(new Set());
setSelectedFilterCategories(new Set());
setPriceRange([0, 10000]);
setPriceSort("none");
}
}, [selectedCategory?.id]);
// Update products list
useEffect(() => {
if (productsData?.data) {
setAllProducts((prev) => {
if (currentPage === 1) {
return productsData.data;
}
const existingIds = new Set(prev.map((p) => p.id));
const newProducts = productsData.data.filter(
(p: Product) => !existingIds.has(p.id)
);
return [...prev, ...newProducts];
});
}
}, [productsData, currentPage]);
const hasMore = useMemo(() => {
return !!productsData?.pagination?.next_page_url;
}, [productsData]);
const loadMoreData = useCallback(() => {
if (!hasMore || isFetching) return;
setCurrentPage((prev) => prev + 1);
}, [hasMore, isFetching]);
const sortedProducts = useMemo(() => {
const products = [...allProducts];
if (priceSort === "lowToHigh") {
return products.sort(
(a, b) =>
parseFloat(a.price_amount || "0") - parseFloat(b.price_amount || "0")
);
}
if (priceSort === "highToLow") {
return products.sort(
(a, b) =>
parseFloat(b.price_amount || "0") - parseFloat(a.price_amount || "0")
);
}
return products;
}, [allProducts, priceSort]);
const handleBrandToggle = useCallback((brandId: number) => {
setSelectedBrands((prev) => {
const newSet = new Set(prev);
if (newSet.has(brandId)) {
newSet.delete(brandId);
} else {
newSet.add(brandId);
}
return newSet;
});
setCurrentPage(1);
setAllProducts([]);
}, []);
// Fetch paginated subcategory products (page 2+)
const {
data: paginatedSubcategoryData,
isLoading: subcategoryPaginatedLoading,
} = useAllCategoryProductsPaginated(selectedCategory || undefined, {
enabled: !!selectedCategory && isSubCategory && currentPage > 1,
page: currentPage,
limit: 6,
});
const handleCategoryToggle = useCallback((categoryId: number) => {
setSelectedFilterCategories((prev) => {
const newSet = new Set(prev);
if (newSet.has(categoryId)) {
newSet.delete(categoryId);
} else {
newSet.add(categoryId);
}
return newSet;
});
setCurrentPage(1);
setAllProducts([]);
}, []);
// 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 handlePriceChange = useCallback((values: number[]) => {
setPriceRange([values[0], values[1]]);
setCurrentPage(1);
setAllProducts([]);
}, []);
if (!slug) {
notFound();
}
const handlePriceSortChange = useCallback(
(sortType: "none" | "lowToHigh" | "highToLow") => {
setPriceSort(sortType);
},
[]
);
const resetFilters = useCallback(() => {
setSelectedBrands(new Set());
setSelectedFilterCategories(new Set());
setPriceRange([0, 10000]);
setPriceSort("none");
setCurrentPage(1);
setAllProducts([]);
}, []);
// Helper function to find category by ID
const findCategoryById = useCallback(
(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) {
@@ -163,177 +232,6 @@ export default function CategoryPageClient({
[]
);
// Helper to check if product already exists in list
const isProductInList = useCallback(
(list: Product[], newProduct: Product) => {
return list.some((product) => product.id === newProduct.id);
},
[]
);
// Setup subcategories when category changes
useEffect(() => {
if (selectedCategory) {
setAllProducts([]);
setHasMore(true);
setCurrentPage(1);
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
) {
setAllProducts(subcategoryProducts);
setHasMore(true);
}
}, [selectedCategory, subcategoryProducts, currentPage, isSubCategory]);
// Handle paginated category products (non-subcategories)
useEffect(() => {
if (paginatedCategoryData && selectedCategory && !isSubCategory) {
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,
isProductInList,
]);
// Handle paginated subcategory products
useEffect(() => {
if (
paginatedSubcategoryData &&
selectedCategory &&
isSubCategory &&
currentPage > 1
) {
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,
isProductInList,
]);
const loadMoreData = useCallback(() => {
if (!hasMore || categoryPaginatedFetching || subcategoryPaginatedLoading) {
return;
}
setCurrentPage((prevPage) => prevPage + 1);
}, [hasMore, categoryPaginatedFetching, subcategoryPaginatedLoading]);
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 = useCallback(
(sortType: "none" | "lowToHigh" | "highToLow") => {
setPriceSort(sortType);
},
[]
);
const handleSubCategorySelect = useCallback(
(subCategory: Category) => {
setAllProducts([]);
setCurrentPage(1);
setHasMore(true);
setPriceSort("none");
router.push(`/${locale}/category/${subCategory.slug}`, { scroll: false });
},
[locale, router]
);
const handleCategoryClick = useCallback(
(category: Category) => {
setAllProducts([]);
setCurrentPage(1);
setHasMore(true);
router.push(`/${locale}/category/${category.slug}`);
},
[locale, router]
);
const renderBreadcrumbs = useCallback(() => {
if (!categoriesData || !selectedCategory) return null;
@@ -358,7 +256,9 @@ export default function CategoryPageClient({
{breadcrumbs.map((category, index) => (
<div key={category.id} className="flex items-center gap-2">
<button
onClick={() => handleCategoryClick(category)}
onClick={() =>
router.push(`/${locale}/category/${category.slug}`)
}
className="hover:text-primary transition-colors"
>
{category.name}
@@ -368,72 +268,46 @@ export default function CategoryPageClient({
))}
</div>
);
}, [categoriesData, selectedCategory, findCategoryById, handleCategoryClick]);
const pageTitle = selectedCategory?.name || t("category");
const handleFilterChange = useCallback((key: string, value: number) => {
setSelectedFilters((prev) => {
const newFilters = { ...prev };
if (!newFilters[key]) {
newFilters[key] = new Set();
}
if (newFilters[key].has(value)) {
newFilters[key].delete(value);
} else {
newFilters[key].add(value);
}
return newFilters;
});
}, []);
const handlePriceChange = useCallback((values: number[]) => {
setPriceRange([values[0], values[1]]);
}, []);
const handlePriceInputChange = useCallback(
(type: "from" | "to", value: string) => {
const numValue = parseInt(value) || 0;
if (type === "from") {
setPriceRange((prev) => [numValue, prev[1]]);
} else {
setPriceRange((prev) => [prev[0], numValue]);
}
},
[]
);
const resetFilters = useCallback(() => {
setSelectedFilters({
brand: new Set(),
color: new Set(),
tag: new Set(),
});
setPriceRange([0, 10000]);
setPriceSort("none");
}, []);
}, [categoriesData, selectedCategory, findCategoryById, locale, router]);
const FiltersContent = useCallback(
() => (
<div className="space-y-6">
{hasSubcategories && subcategoriesToShow.length > 0 && (
{filtersData?.categories && filtersData.categories.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"
: ""
}`}
<h3 className="text-lg font-semibold mb-3">{t("categories")}</h3>
<div className="space-y-2">
{filtersData.categories.map((category) => (
<label
key={category.id}
className="flex items-center gap-2 cursor-pointer"
>
{subCategory.name}
</button>
<Checkbox
checked={selectedFilterCategories.has(category.id)}
onCheckedChange={() => handleCategoryToggle(category.id)}
/>
<span className="text-sm">{category.name}</span>
</label>
))}
</div>
</div>
)}
{filtersData?.brands && filtersData.brands.length > 0 && (
<div>
<h3 className="text-lg font-semibold mb-3">{t("brands")}</h3>
<div className="space-y-2">
{filtersData.brands.map((brand) => (
<label
key={brand.id}
className="flex items-center gap-2 cursor-pointer"
>
<Checkbox
checked={selectedBrands.has(brand.id)}
onCheckedChange={() => handleBrandToggle(brand.id)}
/>
<span className="text-sm">{brand.name}</span>
</label>
))}
</div>
</div>
@@ -479,13 +353,12 @@ export default function CategoryPageClient({
title={t("price")}
priceRange={priceRange}
onPriceChange={handlePriceChange}
onInputChange={handlePriceInputChange}
translations={{ from: t("price_from"), to: t("price_to") }}
/>
<Button
variant="outline"
className="w-full rounded-xl bg-transparent"
className="w-full rounded-xl"
onClick={resetFilters}
>
{t("reset")}
@@ -493,47 +366,46 @@ export default function CategoryPageClient({
</div>
),
[
hasSubcategories,
subcategoriesToShow,
slug,
filtersData,
selectedFilterCategories,
selectedBrands,
priceSort,
priceRange,
t,
handleSubCategorySelect,
handleCategoryToggle,
handleBrandToggle,
handlePriceSortChange,
handlePriceChange,
handlePriceInputChange,
resetFilters,
]
);
if (isLoading) return <div>{t("common.loading")}</div>;
if (!selectedCategory && !categoriesLoading) {
if (categoriesLoading) return <div>{t("common.loading")}</div>;
if (!selectedCategory)
return <div className="text-center py-8">{t("category_not_found")}</div>;
}
const totalItems =
productsData?.pagination?.total || sortedProducts.length || 0;
return (
<div className="flex flex-col gap-4">
{selectedCategory && renderBreadcrumbs()}
<h2 className="text-3xl font-bold">{pageTitle}</h2>
{renderBreadcrumbs()}
<h2 className="text-3xl font-bold">{selectedCategory.name}</h2>
<p className="text-gray-600">
{t("total")}: {totalItems} {t("products")}
</p>
<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 ? (
{sortedProducts.length > 0 ? (
<InfiniteScroll
dataLength={products.length}
dataLength={sortedProducts.length}
next={loadMoreData}
hasMore={hasMore}
scrollThreshold={0.8}
@@ -545,7 +417,7 @@ export default function CategoryPageClient({
}
>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{products.map((product) => (
{sortedProducts.map((product) => (
<ProductCard
key={product.id}
id={product.id}
@@ -570,7 +442,6 @@ export default function CategoryPageClient({
</div>
</div>
{/* Mobile Filter Sheet */}
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetTrigger asChild>
<Button
@@ -605,13 +476,11 @@ function PriceFilter({
title,
priceRange,
onPriceChange,
onInputChange,
translations,
}: {
title: string;
priceRange: [number, number];
onPriceChange: (values: number[]) => void;
onInputChange: (type: "from" | "to", value: string) => void;
translations: { from: string; to: string };
}) {
return (
@@ -627,7 +496,9 @@ function PriceFilter({
id="price-from"
type="number"
value={priceRange[0]}
onChange={(e) => onInputChange("from", e.target.value)}
onChange={(e) =>
onPriceChange([parseInt(e.target.value) || 0, priceRange[1]])
}
className="rounded-lg"
/>
</div>
@@ -639,7 +510,12 @@ function PriceFilter({
id="price-to"
type="number"
value={priceRange[1]}
onChange={(e) => onInputChange("to", e.target.value)}
onChange={(e) =>
onPriceChange([
priceRange[0],
parseInt(e.target.value) || 10000,
])
}
className="rounded-lg"
/>
</div>

View File

@@ -1,6 +1,6 @@
import { useQuery } from "@tanstack/react-query"
import { apiClient } from "@/lib/api"
import type { Category, Product, PaginatedResponse } from "@/lib/types/api"
import type { Category, Product, PaginatedResponse, FiltersResponse, ProductFilters } from "@/lib/types/api"
// Get all categories as tree
export function useCategories(options?: { enabled?: boolean }) {
@@ -92,6 +92,70 @@ export function useAllCategoryProducts(
})
}
export function useCategoryFilters(
categoryId: number | string | undefined,
options?: { enabled?: boolean }
) {
return useQuery({
queryKey: ["category-filters", categoryId],
queryFn: async () => {
const response = await apiClient.get<FiltersResponse>(
"/filters",
{
params: { category_id: categoryId },
}
)
return response.data.data
},
enabled: options?.enabled !== false && !!categoryId,
staleTime: 1000 * 60 * 15,
})
}
// Get filtered category products
export function useFilteredCategoryProducts(
categoryId: number | string,
filters: ProductFilters,
options?: { enabled?: boolean }
) {
return useQuery({
queryKey: ["category", categoryId, "filtered-products", filters],
queryFn: async () => {
const params: Record<string, any> = {
page: filters.page || 1,
limit: filters.limit || 6,
}
if (filters.brands && filters.brands.length > 0) {
params.brands = filters.brands.join(',')
}
if (filters.categories && filters.categories.length > 0) {
params.categories = filters.categories.join(',')
}
if (filters.min_price !== undefined) {
params.min_price = filters.min_price
}
if (filters.max_price !== undefined) {
params.max_price = filters.max_price
}
const response = await apiClient.get<PaginatedResponse<Product>>(
`/categories/${categoryId}/products`,
{ params }
)
return {
data: response.data.data || [],
pagination: response.data.pagination || {}
}
},
enabled: options?.enabled !== false && !!categoryId,
})
}
// Get products from category and children WITH pagination (mimics RTK getAllCategoryProductsPaginated)
export function useAllCategoryProductsPaginated(
category: Category | undefined,

View File

@@ -49,7 +49,7 @@ export default function HomePage() {
const hasMore = collections ? visibleCount < collections.length : false;
return (
<div className="px-4 md:px-8 lg:px-12 pt-8 pb-12 space-y-8">
<div className="px-2 md:px-4 lg:px-4 pt-4 pb-12 space-y-8 max-w-[1504px] mx-auto">
{!carouselsLoading && carouselItems.length > 0 && (
<HeroCarousel items={carouselItems} />
)}

View File

@@ -0,0 +1,232 @@
"use client";
import { useState, MouseEvent, useEffect, useRef } from "react";
import { Heart } from "lucide-react";
import { toast } from "sonner";
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
type CarouselApi,
} from "@/components/ui/carousel";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
type ProductCardProps = {
id: number;
name: string;
price: number | null;
struct_price_text: string;
discount?: number | null;
discount_text?: string | null;
images: string[];
is_favorite: boolean;
labels?: { text: string; bg_color: string }[];
price_color?: string;
height?: number;
width?: number;
button?: boolean;
};
export default function ProductCard({
id,
name,
price,
struct_price_text,
discount,
discount_text,
images,
is_favorite,
labels = [],
price_color = "#005bff",
height = 360,
width = 280,
button = true,
}: ProductCardProps) {
const [favorite, setFavorite] = useState(is_favorite);
const [api, setApi] = useState<CarouselApi>();
const [current, setCurrent] = useState(0);
const autoplayRef = useRef<NodeJS.Timeout | null>(null);
const hasMultipleImages = images.length > 1;
// Track carousel current slide
useEffect(() => {
if (!api) return;
setCurrent(api.selectedScrollSnap());
api.on("select", () => {
setCurrent(api.selectedScrollSnap());
});
}, [api]);
// Auto-play functionality - 3 seconds
useEffect(() => {
if (!api || !hasMultipleImages) return;
const startAutoplay = () => {
autoplayRef.current = setInterval(() => {
if (api.canScrollNext()) {
api.scrollNext();
} else {
api.scrollTo(0);
}
}, 3000);
};
const stopAutoplay = () => {
if (autoplayRef.current) {
clearInterval(autoplayRef.current);
autoplayRef.current = null;
}
};
startAutoplay();
return () => stopAutoplay();
}, [api, hasMultipleImages]);
const handleFavorite = async (e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
e.stopPropagation();
const newFavoriteState = !favorite;
setFavorite(newFavoriteState);
if (newFavoriteState) {
toast.success("Товар добавлен в избранное");
} else {
toast.success("Товар удален из избранного");
}
};
const handleCardClick = (e: MouseEvent<HTMLAnchorElement>) => {
const target = e.target as HTMLElement;
if (
target.closest('button') ||
target.closest('[data-carousel-control="true"]')
) {
e.preventDefault();
}
};
const handleNavClick = (e: MouseEvent, action: () => void) => {
e.preventDefault();
e.stopPropagation();
action();
};
return (
<a
href={`/product/${id}`}
className="no-underline block"
onClick={handleCardClick}
>
<Card
className="relative gap-2 border-none shadow-none p-0 w-full overflow-hidden rounded-2xl hover:shadow-md transition-all cursor-pointer"
style={{ height, maxWidth: width }}
>
{/* Image Section with Carousel */}
<div className="relative w-full h-[260px] group">
<Carousel
opts={{
align: "start",
loop: true,
watchDrag: false, // Disable drag/swipe on desktop
}}
setApi={setApi}
className="w-full h-full"
>
<CarouselContent className="h-[260px] ml-0">
{images.map((image, index) => (
<CarouselItem key={index} className="h-[260px] pl-0">
<div className="h-full flex items-center justify-center p-2">
<img
src={image}
alt={`${name} - ${index + 1}`}
className="max-w-full max-h-full object-contain"
draggable="false"
/>
</div>
</CarouselItem>
))}
</CarouselContent>
{/* Navigation Arrows - Only show if multiple images */}
{hasMultipleImages && (
<>
<CarouselPrevious
data-carousel-control="true"
className="absolute left-2 opacity-0 group-hover:opacity-100 transition-opacity z-20"
onClick={(e) => handleNavClick(e, () => api?.scrollPrev())}
/>
<CarouselNext
data-carousel-control="true"
className="absolute right-2 opacity-0 group-hover:opacity-100 transition-opacity z-20"
onClick={(e) => handleNavClick(e, () => api?.scrollNext())}
/>
</>
)}
</Carousel>
{/* Favorite Button */}
<button
onClick={handleFavorite}
className="absolute top-3 right-3 z-10 rounded-full bg-white/80 p-2 hover:bg-white transition-all"
>
{favorite ? (
<Heart className="w-5 h-5 text-red-500 fill-red-500" />
) : (
<Heart className="w-5 h-5 text-gray-700" />
)}
</button>
{/* Image Indicators */}
{hasMultipleImages && (
<div className="absolute bottom-2 left-1/2 -translate-x-1/2 z-10 flex gap-1.5">
{images.map((_, index) => (
<button
key={index}
data-carousel-control="true"
onClick={(e) => handleNavClick(e, () => api?.scrollTo(index))}
className={`h-1.5 rounded-full transition-all ${
index === current ? "w-6 bg-white" : "w-1.5 bg-white/60"
}`}
/>
))}
</div>
)}
{/* Labels */}
{labels?.length > 0 && (
<div className="absolute top-2 left-2 flex flex-col gap-1 z-10">
{labels.map((label, idx) => (
<Badge
key={idx}
className="text-white text-[10px] font-bold uppercase rounded-r-md"
style={{ backgroundColor: label.bg_color }}
>
{label.text}
</Badge>
))}
</div>
)}
</div>
{/* Content */}
<CardContent className="p-0 space-y-1">
<p
className="text-sm font-semibold mx-2"
style={{ color: price_color }}
>
{struct_price_text}
</p>
<p className="text-gray-800 text-sm truncate mx-2">{name}</p>
</CardContent>
</Card>
</a>
);
}

View File

@@ -2,7 +2,7 @@
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ChevronRight } from "lucide-react";
import ProductCard from "@/components/ProductCard";
import ProductCard from "@/features/home/components/ProductCard";
import { Skeleton } from "@/components/ui/skeleton";
import { useCollectionProducts } from "@/lib/hooks";
import type { Collection } from "@/lib/types/api";
@@ -22,7 +22,6 @@ export default function CollectionSection({ collection, locale }: Props) {
isError,
} = useCollectionProducts(collection.id, { enabled: shouldRender });
// Determine if section should render based on products
useEffect(() => {
if (!isLoading && productsData) {
const hasProducts = productsData.data && productsData.data.length > 0;
@@ -30,7 +29,6 @@ export default function CollectionSection({ collection, locale }: Props) {
}
}, [isLoading, productsData]);
// Don't render if no products after loading
if (!isLoading && (!productsData?.data || productsData.data.length === 0)) {
return null;
}
@@ -39,7 +37,6 @@ export default function CollectionSection({ collection, locale }: Props) {
router.push(`/${locale}/collections/${collection.id}`);
};
// Show skeleton while loading
if (isLoading) {
return (
<section className="bg-white rounded-2xl shadow-sm p-6">
@@ -56,16 +53,14 @@ export default function CollectionSection({ collection, locale }: Props) {
);
}
// Show error state
if (isError) {
return null; // Silently skip errored collections
return null;
}
// Slice to show only first 4 products
const displayProducts = productsData?.data.slice(0, 4) || [];
const displayProducts = productsData?.data.slice(0, 10) || [];
return (
<section className="bg-white rounded-2xl shadow-sm p-6">
<section className="bg-white rounded-2xl shadow-sm ">
<div
className="flex items-center justify-between mb-4 cursor-pointer group"
onClick={handleTitleClick}
@@ -78,14 +73,15 @@ export default function CollectionSection({ collection, locale }: Props) {
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4">
{displayProducts.map((product) => {
// Extract first media image or use placeholder
const firstImage =
product.media?.[0]?.images_800x800 ||
product.media?.[0]?.images_720x720 ||
product.media?.[0]?.thumbnail ||
"/placeholder-product.jpg";
// 🔥 TÜM RESİMLERİ AL - Burada değişiklik!
const allImages = product.media?.map(
(media) =>
media.images_800x800 ||
media.images_720x720 ||
media.images_400x400 ||
media.thumbnail
).filter(Boolean) || ["/placeholder-product.jpg"];
// Format price
const formattedPrice = product.price_amount
? `${parseFloat(product.price_amount).toFixed(2)} TMT`
: "Price not available";
@@ -99,7 +95,7 @@ export default function CollectionSection({ collection, locale }: Props) {
product.price_amount ? parseFloat(product.price_amount) : null
}
struct_price_text={formattedPrice}
images={[firstImage]}
images={allImages} // 🔥 Array olarak tüm resimler
is_favorite={false}
labels={[]}
price_color="#111"
@@ -112,4 +108,4 @@ export default function CollectionSection({ collection, locale }: Props) {
</div>
</section>
);
}
}

View File

@@ -0,0 +1,47 @@
"use client"
import { useMutation } from "@tanstack/react-query"
import { apiClient } from "@/lib/api"
interface OpenStoreData {
firstName: string
lastName: string
email: string
phone: string
patentFile: File
}
interface OpenStoreResponse {
success: boolean
message: string
data?: any
}
const API_ENDPOINTS = {
openStore: "forms/newsletter-subscription",
}
export function useOpenStore() {
return useMutation<OpenStoreResponse, Error, OpenStoreData>({
mutationFn: async (data: OpenStoreData) => {
const formData = new FormData()
formData.append("firstname", data.firstName)
formData.append("lastname", data.lastName)
formData.append("email", data.email)
formData.append("phone", data.phone)
formData.append("file", data.patentFile)
const response = await apiClient.post<OpenStoreResponse>(
API_ENDPOINTS.openStore,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
)
return response.data
},
})
}

View File

@@ -17,7 +17,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { useProductsBySlug } from "@/features/products/hooks/useProducts";
import { useAddToCart, useUpdateCartItemQuantity, useCart } from "@/features/cart/hooks/useCart";
import { useAddToCart, useUpdateCartItemQuantity, useRemoveFromCart, useCart } from "@/features/cart/hooks/useCart";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
@@ -50,11 +50,13 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
const retryTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const syncToServerRef = useRef<((quantity: number) => void) | null>(null);
const retrySyncRef = useRef<((quantity: number) => void) | null>(null);
const autoplayTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
const { data: product, isLoading: productLoading, error } = useProductsBySlug(slug);
const { data: cartData, refetch: refetchCart } = useCart();
const addToCartMutation = useAddToCart();
const updateCartMutation = useUpdateCartItemQuantity();
const removeFromCartMutation = useRemoveFromCart();
const cartItem = useMemo(() =>
cartData?.data?.find((item: any) => item.product?.id === product?.id),
@@ -64,6 +66,46 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
const availableStock = product?.stock || 0;
const imageUrls = useMemo(() =>
product?.media?.map(m => m.images_800x800 || m.images_720x720 || m.thumbnail) || [],
[product]
);
// Auto-play carousel every 3 seconds
useEffect(() => {
if (imageUrls.length <= 1) return;
const startAutoplay = () => {
autoplayTimerRef.current = setInterval(() => {
setSelectedImage(prev => (prev + 1) % imageUrls.length);
}, 3000);
};
startAutoplay();
return () => {
if (autoplayTimerRef.current) {
clearInterval(autoplayTimerRef.current);
}
};
}, [imageUrls.length]);
// Reset autoplay timer when user manually selects image
const handleImageSelect = useCallback((index: number) => {
setSelectedImage(index);
// Reset autoplay timer
if (autoplayTimerRef.current) {
clearInterval(autoplayTimerRef.current);
}
if (imageUrls.length > 1) {
autoplayTimerRef.current = setInterval(() => {
setSelectedImage(prev => (prev + 1) % imageUrls.length);
}, 3000);
}
}, [imageUrls.length]);
useEffect(() => {
if (cartItem?.product_quantity) {
setLocalQuantity(cartItem.product_quantity);
@@ -145,7 +187,11 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
setSyncError(false);
try {
if (isInCart) {
// If quantity is 0, remove from cart
if (quantity === 0) {
await removeFromCartMutation.mutateAsync(product.id);
toast.success(t("removed_from_cart"));
} else if (isInCart) {
await updateCartMutation.mutateAsync({
productId: product.id,
quantity: quantity,
@@ -162,7 +208,6 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
retryCountRef.current = 0;
clearPendingUpdate();
// Refetch cart to update UI state immediately
await refetchCart();
if (pendingQuantityRef.current !== null) {
@@ -181,7 +226,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
retrySyncRef.current?.(quantity);
}
}, [product?.id, isInCart, updateCartMutation, addToCartMutation, cartItem, clearPendingUpdate, refetchCart]);
}, [product?.id, isInCart, updateCartMutation, addToCartMutation, removeFromCartMutation, cartItem, clearPendingUpdate, refetchCart, t]);
syncToServerRef.current = syncToServer;
@@ -239,13 +284,13 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
return () => {
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
if (retryTimerRef.current) clearTimeout(retryTimerRef.current);
if (autoplayTimerRef.current) clearInterval(autoplayTimerRef.current);
};
}, []);
const handleAddToCart = useCallback(async () => {
if (!product?.id) return;
// Set syncing state immediately for UI feedback
setIsSyncing(true);
try {
@@ -254,7 +299,6 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
quantity: localQuantity,
});
// Refetch cart immediately to update isInCart state
await refetchCart();
setIsSyncing(false);
@@ -281,7 +325,8 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
}, [localQuantity, availableStock]);
const handleQuantityDecrease = useCallback(() => {
if (localQuantity <= 1) return;
// Allow decreasing to 0 to remove from cart
if (localQuantity <= 0) return;
setLocalQuantity(prev => prev - 1);
}, [localQuantity]);
@@ -290,11 +335,6 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
setIsFavorite(!isFavorite);
}, [isFavorite]);
const imageUrls = useMemo(() =>
product?.media?.map(m => m.images_800x800 || m.images_720x720 || m.thumbnail) || [],
[product]
);
const loadingSkeleton = useMemo(() => (
<div className="container mx-auto px-4 py-8">
<div className="flex flex-col lg:flex-row gap-8">
@@ -354,7 +394,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
{imageUrls.map((image, index) => (
<button
key={index}
onClick={() => setSelectedImage(index)}
onClick={() => handleImageSelect(index)}
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"
@@ -499,7 +539,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
variant="outline"
size="icon"
onClick={handleQuantityDecrease}
disabled={localQuantity === 1 || isSyncing}
disabled={isSyncing}
className={`rounded-xl h-12 w-12 ${isSyncing ? 'opacity-70' : ''}`}
>
<Minus className="h-5 w-5" />