'use client'; import { Globe2Icon } from 'lucide-react'; import { useEffect, useState } from 'react'; import { toast } from 'sonner'; import { cn } from '@/lib/utils'; import SmallNewsCard from '@/components/Discover/SmallNewsCard'; import MajorNewsCard from '@/components/Discover/MajorNewsCard'; export interface Discover { title: string; content: string; url: string; thumbnail: string; } const topics: { key: string; display: string }[] = [ { display: 'Tech & Science', key: 'tech', }, { display: 'Finance', key: 'finance', }, { display: 'Art & Culture', key: 'art', }, { display: 'Sports', key: 'sports', }, { display: 'Entertainment', key: 'entertainment', }, ]; const Page = () => { const [discover, setDiscover] = useState(null); const [loading, setLoading] = useState(true); const [activeTopic, setActiveTopic] = useState(topics[0].key); const fetchArticles = async (topic: string) => { setLoading(true); try { const res = await fetch(`/api/discover?topic=${topic}`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); const data = await res.json(); if (!res.ok) { throw new Error(data.message); } data.blogs = data.blogs.filter((blog: Discover) => blog.thumbnail); setDiscover(data.blogs); } catch (err: any) { console.error('Error fetching data:', err.message); toast.error('Error fetching data'); } finally { setLoading(false); } }; useEffect(() => { fetchArticles(activeTopic); }, [activeTopic]); return ( <>

Discover

{topics.map((t, i) => (
setActiveTopic(t.key)} > {t.display}
))}
{loading ? (
) : (
{discover?.map((item, i) => ( ))}
{discover && discover.length > 0 && (() => { const sections = []; let index = 0; while (index < discover.length) { if (sections.length > 0) { sections.push(
, ); } if (index < discover.length) { sections.push( , ); index++; } if (index < discover.length) { sections.push(
, ); } if (index < discover.length) { const smallCards = discover.slice(index, index + 3); sections.push(
{smallCards.map((item, i) => ( ))}
, ); index += 3; } if (index < discover.length) { sections.push(
, ); } if (index < discover.length - 1) { const twoMajorCards = discover.slice(index, index + 2); twoMajorCards.forEach((item, i) => { sections.push( , ); if (i === 0) { sections.push(
, ); } }); index += 2; } else if (index < discover.length) { sections.push( , ); index++; } if (index < discover.length) { sections.push(
, ); } if (index < discover.length) { const smallCards = discover.slice(index, index + 3); sections.push(
{smallCards.map((item, i) => ( ))}
, ); index += 3; } } return sections; })()}
)}
); }; export default Page;