dressed_for_succes_store/frontend old/pages/index.tsx
2025-03-11 22:42:30 +07:00

148 lines
5.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { motion } from 'framer-motion';
import Head from 'next/head';
import Image from 'next/image';
import { useState, useEffect } from 'react';
import Header from '../components/Header';
import Hero from '../components/Hero';
import CookieNotification from '../components/CookieNotification';
import TabSelector from '../components/TabSelector';
import NewArrivals from '../components/NewArrivals';
import Collections from '../components/Collections';
import PopularCategories from '../components/PopularCategories';
import fs from 'fs';
import path from 'path';
import { Heart } from 'lucide-react';
import Footer from '../components/Footer';
import { Product, products as allProducts } from '../data/products';
import { Collection, collections as allCollections } from '../data/collections';
import { Category, categories as allCategories } from '../data/categories';
// Типы для свойств компонента
interface HomeProps {
heroImages: string[];
products: Product[];
collections: Collection[];
categories: Category[];
}
export default function Home({ heroImages, products, collections, categories }: HomeProps) {
// Состояние для отслеживания наведения на карточки товаров
const [hoveredProduct, setHoveredProduct] = useState<number | null>(null);
// Состояние для отслеживания избранных товаров
const [favorites, setFavorites] = useState<number[]>([]);
// Состояние для отслеживания активного таба
const [activeTab, setActiveTab] = useState(0);
// Состояние для отслеживания прокрутки страницы
const [scrolled, setScrolled] = useState(false);
// Эффект для отслеживания прокрутки
useEffect(() => {
const handleScroll = () => {
const isScrolled = window.scrollY > 50;
if (isScrolled !== scrolled) {
setScrolled(isScrolled);
}
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [scrolled]);
// Функция для добавления/удаления товара из избранного
const toggleFavorite = (id: number, e: React.MouseEvent) => {
e.stopPropagation();
setFavorites(prev =>
prev.includes(id)
? prev.filter(itemId => itemId !== id)
: [...prev, id]
);
};
// Функция для обработки изменения активного таба
const handleTabChange = (index: number) => {
setActiveTab(index);
};
// Рендерим контент в зависимости от активного таба
const renderTabContent = () => {
switch (activeTab) {
case 0:
return <NewArrivals products={products} />;
case 1:
return <Collections collections={collections} />;
case 2:
return <PopularCategories categories={categories} />;
default:
return <NewArrivals products={products} />;
}
};
return (
<div className="min-h-screen bg-white font-['Arimo']">
<Head>
<title>Brand Store | Элегантная мода</title>
<link rel="icon" href="/favicon.ico" />
<link href="https://fonts.googleapis.com/css2?family=Arimo:wght@400;500;600;700&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600;700&display=swap" rel="stylesheet" />
</Head>
<Header />
<main>
{/* Секция с HERO элементом */}
<Hero images={heroImages} />
{/* Табы для выбора категорий */}
<TabSelector onTabChange={handleTabChange} />
{/* Контент в зависимости от выбранного таба */}
{renderTabContent()}
</main>
<Footer />
<CookieNotification />
</div>
);
}
// Функция для получения данных на стороне сервера
export async function getStaticProps() {
// Получение изображений для слайдера из папки hero_photos
const heroImagesDirectory = path.join(process.cwd(), 'public/hero_photos');
let heroImages = [];
try {
const fileNames = fs.readdirSync(heroImagesDirectory);
// Фильтруем только изображения
const imageExtensions = ['.jpg', '.jpeg', '.png', '.webp', '.gif'];
const imageFiles = fileNames.filter(file =>
imageExtensions.some(ext => file.toLowerCase().endsWith(ext))
);
if (imageFiles.length > 0) {
heroImages = imageFiles.map(fileName => `/hero_photos/${fileName}`);
} else {
// Если нет изображений, используем изображения из папки photos
heroImages = ['/photos/head_photo.png'];
}
} catch (error) {
console.error('Error reading hero_photos directory:', error);
// Если папка не существует или пуста, используем изображение из папки photos
heroImages = ['/photos/head_photo.png'];
}
return {
props: {
heroImages,
products: allProducts,
collections: allCollections,
categories: allCategories
},
// Перегенерация страницы каждые 10 минут
revalidate: 600,
};
}