recommendations.js

import React, { useEffect, useState } from 'react';
import useCocoApi from '../../hooks/fetch/request';
import { randomInteger, shuffle } from '../../utility/common';
import ComedianVideos from '../../components/atoms/comedian-videos';

export function useComedianVideos(comedianId, currentVideoId) {
  const [comedianVideos, error] = useCocoApi({
    path: `/use/comedians/${comedianId}`
  });
  if (comedianVideos) {
    // return top 4 videos excluding the current video
    const videos = comedianVideos.videos.filter((video) => video.videoId != currentVideoId).slice(0, 4);
    return {
      basic: comedianVideos.basic,
      videos
    };
  }
  return [];
}

export function WatchComedianRecommendations({ comedianId, currentVideoId }) {
  const { basic, videos } = useComedianVideos(comedianId, currentVideoId);
  if (!videos || videos?.length === 0) return null;

  return (
    <>
      <hr />
      <div className="related-videos">
        <h3 className="title">More of {basic?.name}</h3>
        <ComedianVideos videos={videos} />
      </div>
    </>
  );
}

export function WatchRecommendations({ currentVideoId }) {
  const [data, error] = useCocoApi({
    path: '/use/recommendations'
  });
  const [recommendations, setRecommendations] = useState([]);

  useEffect(() => {
    if (data) {
      const keys = Object.keys(data);
      // NOTE: selecting recommedations from latest, trending and popular
      const key = keys[randomInteger(0, 3)];
      const videos = shuffle(data[key].list);
      const selectedVideos = videos.filter((video) => video.videoId != currentVideoId).slice(0, 10);
      // select top 10 videos from the recommendations
      setRecommendations(selectedVideos);
    }
  }, [data]);

  if (!recommendations || recommendations?.length === 0) return null;

  return (
    <>
      <hr />
      <div className="more-videos">
        <h3 className="title">More Videos</h3>
        <ComedianVideos videos={recommendations} error={error} />
      </div>
    </>
  );
}