import Features from "@/components/common/Features";
import Hero from "@/components/homes/home-6/Hero";
import CategoryProducts from "@/components/common/CategoryProducts";
import { db } from "@/helpers/api";

import ShopDetailsTab from "@/components/shopDetails/ShopDetailsTab";
import React from "react";
import Link from "next/link";
import DetailsPopup from "@/components/shopDetails/DetailsPopup";
import ShopFullwidth from "@/components/shop/ShopFullwidth";

const { Op } = require("sequelize"); 

async function fetchCategoriesWithProducts() {
	if (!db.initialized) await db.initialize();

	const categories = await db.Categories.findAll({
		where: { parentID: 0 },
		include: [
			{
				model: db.Categories,
				as: "children",
				include: [
					{
						model: db.Categories,
						as: "subChildren",
						required: false,
					},
				],
				required: false,
			},
		],
		raw: false,
	});

	const categoriesWithProducts = await Promise.all(
		categories.map(async (category) => {
			const products = await db.Products.findAll({
				where: { categorySlug: category.slug },
				limit: 12,
			});
			return {
				...category.toJSON(),
				products: products.map((product) => product.toJSON()),
			};
		})
	);

	return categoriesWithProducts;
}

async function fetchProductBySlug(slug) {
	if (!db.initialized) await db.initialize();

	const product = await db.Products.findOne({
		where: { url: slug },
          raw:true, 
	});

	return product ? product : null;
}

async function fetchCategoryBySlug(slug) {
     if (!db.initialized) 
          await db.initialize();

     const categories = await db.Categories.findAll({
          attributes:['name', 'slug', 'description'], 
          where: {
               slug: { [Op.in]: slug }
          },
          raw: true, 
          limit: 3 
     });

     if (categories.length === 0) {
          return false; 
     }

     const categorySlugs = categories.map(cat => cat.slug);

     const whereClause = {};
     if (categorySlugs.length > 0) whereClause.categorySlug = categorySlugs[0];
     if (categorySlugs.length > 1) whereClause.subcategorySlug = categorySlugs[1];
     if (categorySlugs.length > 2) whereClause.thirdCategorySlug = categorySlugs[2];

     const productsByCategory = await db.Products.findAll({
          where: whereClause, 
          raw: true, 
     });

     const returnedData = { 
          categoryName: categories[0].name, 
          categoryDesc: categories[0].description, 
          subcategoryName: categories[1] ? categories[1].name : false, 
          subcategoryDesc: categories[1] ? categories[1].description : false, 
          thirdCategoryName: categories[2] ? categories[2].name : false, 
          thirdCategoryDesc: categories[2] ? categories[2].description : false, 
          productsData: productsByCategory.length > 0 ? productsByCategory : false
     };

     return returnedData.productsData ? returnedData : false;
}

export async function generateMetadata({ params }) {
	const { slug } = params;

	if (!slug) {
		return {
			title: "Homepage - Best Products",
			description: "Welcome to our store. Find the best products here!",
		};
	}

	const product = await fetchProductBySlug(slug);

	if (product) {
          let customDescription = 'Cumpara' + product.name + ' de pe eMagyl.Ro !'; 

          if(customDescription.length > 160) {
               customDescription = customDescription.slice(0, 157) + "..."; 
          } 

          function generateKeywords(text) {
              
               const stopWords = [
                   'cu', 'la', 'si', 'pentru', 'de', 'în', 'un', 'o', 'pe', 'din', 'nu', 'este', 'pana', 'la', 'înainte', 'nu', 'care', 'unui', 'la', 'deci', 'este', 'sa', 'a', 'al', 'le', 'as', 'sau', 'mai'
               ];
           
              
               function cleanText(text) {
                    return text
                         .toLowerCase() 
                         .replace(/[^\w\s]/g, '') 
                         .normalize("NFD").replace(/[\u0300-\u036f]/g, ""); 
               }
           
               const cleanedText = cleanText(text);
           
               const words = cleanedText.split(' ').filter(word => !stopWords.includes(word));
           
           
               const uniqueWords = Array.from(new Set(words)); 
               return uniqueWords.join(', '); 
          }

		return {
			title: product.name.slice(0, 60),
			description: customDescription,
               keywords: generateKeywords(product.name), 
               referrer: 'origin-when-cross-origin',
               authors: 'eMagyl.Ro', 
               creator: 'eMagyl.Ro',
               publisher: 'GlobalScripts.Ro', 
			openGraph: {
                    title: product.name.slice(0, 60),
                    description: customDescription, 
                    images: [product.images?.split('|')[0]], 
			},
               locale: 'ro_US',
               type: 'website',
		};
	}

	return {
		title: "Product Not Found",
		description: "This product does not exist.",
	};
}

export default async function Page({ params }) {
	const { slug } = params;

	if (slug && slug.length > 0) {
		const product = await fetchProductBySlug(slug);
          const isCategory = await fetchCategoryBySlug(slug);
       
		if (product) {

			return (
                    <>
                    
                         <div className='tf-breadcrumb'>
                              <div className='container'>
                                   <div className='tf-breadcrumb-wrap d-flex justify-content-between flex-wrap align-items-center'>
                                        <div className='tf-breadcrumb-list'>
                                             <Link href={`/`} className='text'>
                                                  Acasă
                                             </Link>
                                             <i className='icon icon-arrow-right' />
          
                                             {product.categorySlug && (
                                                  <>
                                                       <span className='text'>
                                                            <Link href={product.categorySlug}>{product.categoryName}</Link>
                                                       </span>
                                                  </>
                                             )}

                                             {product.subcategorySlug && (
                                                  <>
                                                       <i className='icon icon-arrow-right' />

                                                       <span className='text'>
                                                            <Link href={product.categorySlug + '/' + product.subcategorySlug}>{product.subcategoryName}</Link>
                                                       </span>
                                                  </>
                                             )}

                                             {product.thirdCategorySlug && (
                                                  <>
                                                       <span className='text'>
                                                            <Link href={product.categorySlug + '/' + product.subcategorySlug + '/' + product.thirdCategorySlug}>{product.thirdCategoryName}</Link>
                                                       </span>
                                                  </>
                                             )}
                                                  
                                        </div>
                                        
                                   </div>
                              </div>
                         </div>
                         <DetailsPopup product={product} randomUsers={Math.floor(Math.random() * 20) + 1}/>
                         <ShopDetailsTab product={product} />
          
                    
                    </>
               );
		} 
          else if(isCategory) {
               
               return (
                    <>
                         <div className='tf-page-title'>
                              <div className='container-full'>
                                   <div className='heading text-center'>
                                        {isCategory.categoryName.length > 0 && (
                                             isCategory.categoryName
                                        )}

                                        {isCategory.subcategoryName.length > 0 && (
                                             " > " + isCategory.subcategoryName
                                        )}

                                        {isCategory.thirdCategoryName.length > 0 && (
                                             " > " + isCategory.thirdCategoryName
                                        )}

                                   </div>
                                   <p className='text-center text-2 text_black-2 mt_5'>
                                        {isCategory.categoryDesc}
                                   </p>
                              </div>
                         </div>
                         <ShopFullwidth productsData={isCategory.productsData} />
                         
                    </>
               ); 
          }
	} else {
		const categoriesWithProducts = await fetchCategoriesWithProducts();

		return (
			<>
				<Hero />
				{categoriesWithProducts.map((category) => (
					<CategoryProducts key={category.slug} category={category} />
				))}
				<div className='mt-5'></div>
				<Features />
				<div className='mt-5'></div>
			</>
		);
	}
}
 