// imported in Home.js

import { useState, useEffect } from 'react';
import { CardGroup} from 'react-bootstrap';
import { Link } from 'react-router-dom';
import PreviewProducts from './PreviewProducts';

export default function FeaturedProducts(){

	const [previews, setPreviews]= useState([]);

	useEffect(() =>{

		fetch(`${process.env.REACT_APP_API_URL}/products/allproduct`)
		.then(res => res.json())
		.then(data =>{
			console.log(data);


			const numbers = [];
			const featured = [];

			// to generate random number first we make the Math.floor means will get the closest which is the whole number. it will remove the decimal places.
			// math.random will genrate a decimal numbers from 0-1 
			const generateRandomNums = () =>{
				let randomNum = Math.floor (Math.random() * data.length);

			
				//Checks if the random number has already been added to the numbers array,if not. it adds the random number to the numbers arary. if the random number already exist in the numbers array,it recursively calls itself to generate a new random number.
				if(numbers.indexOf(randomNum) === -1){
					//if it doesnt exist it will push a new random number in our array
					numbers.push(randomNum);
				}else{
					generateRandomNums()
				}
			}
			// for loop - will run until the 5 iteration will generate a 5 featured courses. 
			for(let i=0;i < 5; i++){
				generateRandomNums()

				// for each iteration of the loop, the PreviewProducts components is rendered with the corresponding product data from the data array based on the random number.
				featured.push(
					<PreviewProducts data={data[numbers[i]]}key={data[numbers[i]]._id} breakpoint={2} />
					)
			}

			// After the loop finishes, the setPreview function is called to update the state of the component with the feautured array.

			setPreviews(featured);
	})
},[]);

	return (
		<>
			<h2 className="text-center">Featured Products</h2>
			<CardGroup className="justify-content-center">
				{/* add the previews state here */}
				{previews}
			</CardGroup>

		</>
	)
}