'use client'; import { Search, Sliders, ChevronLeft, ChevronRight } from 'lucide-react'; import { useEffect, useState, useRef, memo } from 'react'; import Link from 'next/link'; import { toast } from 'sonner'; interface Discover { title: string; content: string; url: string; thumbnail: string; } // List of available categories const categories = [ 'For You', 'AI', 'Technology', 'Current News', 'Sports', 'Money', 'Gaming', 'Entertainment', 'Art and Culture', 'Science', 'Health', 'Travel' ]; // Memoized header component that won't re-render when content changes const DiscoverHeader = memo(({ activeCategory, setActiveCategory, setShowPreferences }: { activeCategory: string; setActiveCategory: (category: string) => void; setShowPreferences: (show: boolean) => void; }) => { const categoryContainerRef = useRef(null); // Function to scroll categories horizontally const scrollCategories = (direction: 'left' | 'right') => { const container = categoryContainerRef.current; if (!container) return; const scrollAmount = container.clientWidth * 0.8; const currentScroll = container.scrollLeft; container.scrollTo({ left: direction === 'left' ? Math.max(0, currentScroll - scrollAmount) : currentScroll + scrollAmount, behavior: 'smooth' }); }; return (

Discover

{/* Category Navigation with Buttons */}
{categories.map((category) => ( ))}

); }); DiscoverHeader.displayName = 'DiscoverHeader'; // Memoized content component that handles its own loading state const DiscoverContent = memo(({ activeCategory, userPreferences, preferredLanguages }: { activeCategory: string; userPreferences: string[]; preferredLanguages: string[]; }) => { const [discover, setDiscover] = useState(null); const [contentLoading, setContentLoading] = useState(true); // Fetch data based on active category, user preferences, and language useEffect(() => { const fetchData = async () => { setContentLoading(true); try { let endpoint = `${process.env.NEXT_PUBLIC_API_URL}/discover`; let params = []; if (activeCategory !== 'For You') { params.push(`category=${encodeURIComponent(activeCategory)}`); } else if (userPreferences.length > 0) { params.push(`preferences=${encodeURIComponent(JSON.stringify(userPreferences))}`); } if (preferredLanguages.length > 0) { params.push(`languages=${encodeURIComponent(JSON.stringify(preferredLanguages))}`); } if (params.length > 0) { endpoint += `?${params.join('&')}`; } const res = await fetch(endpoint, { 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 { setContentLoading(false); } }; fetchData(); }, [activeCategory, userPreferences, preferredLanguages]); if (contentLoading) { return (
); } return (
{discover && discover.map((item, i) => ( {/* Using img tag instead of Next.js Image for external URLs */} {item.title}
{item.title.slice(0, 100)}...

{item.content.slice(0, 100)}...

))}
); }); DiscoverContent.displayName = 'DiscoverContent'; // Preferences modal component const PreferencesModal = memo(({ showPreferences, setShowPreferences, userPreferences, setUserPreferences, preferredLanguages, setPreferredLanguages, setActiveCategory }: { showPreferences: boolean; setShowPreferences: (show: boolean) => void; userPreferences: string[]; setUserPreferences: (prefs: string[]) => void; preferredLanguages: string[]; setPreferredLanguages: (langs: string[]) => void; setActiveCategory: (category: string) => void; }) => { const [tempPreferences, setTempPreferences] = useState([]); const [tempLanguages, setTempLanguages] = useState([]); // Initialize temp preferences when modal opens useEffect(() => { if (showPreferences) { setTempPreferences([...userPreferences]); setTempLanguages([...preferredLanguages]); } }, [showPreferences, userPreferences, preferredLanguages]); // Save user preferences const saveUserPreferences = async (preferences: string[], languages: string[]) => { try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/discover/preferences`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ categories: preferences, languages }), }); if (res.ok) { toast.success('Preferences saved successfully'); } else { const data = await res.json(); throw new Error(data.message); } } catch (err: any) { console.error('Error saving preferences:', err.message); toast.error('Error saving preferences'); } }; if (!showPreferences) return null; return (

Personalize Your Feed

Select categories you're interested in:

{categories.filter(c => c !== 'For You').map((category) => ( ))}

Preferred Languages

{[ { code: 'en', name: 'English' }, { code: 'ar', name: 'Arabic' }, { code: 'zh', name: 'Chinese' }, { code: 'fr', name: 'French' }, { code: 'de', name: 'German' }, { code: 'hi', name: 'Hindi' }, { code: 'it', name: 'Italian' }, { code: 'ja', name: 'Japanese' }, { code: 'ko', name: 'Korean' }, { code: 'pt', name: 'Portuguese' }, { code: 'ru', name: 'Russian' }, { code: 'es', name: 'Spanish' }, ].map((language) => ( ))}

{tempLanguages.length === 0 ? "No languages selected will show results in all languages" : `Selected: ${tempLanguages.length} language(s)`}

); }); PreferencesModal.displayName = 'PreferencesModal'; // Main page component const Page = () => { // State for the entire page const [activeCategory, setActiveCategory] = useState('For You'); const [showPreferences, setShowPreferences] = useState(false); const [userPreferences, setUserPreferences] = useState(['AI', 'Technology']); const [preferredLanguages, setPreferredLanguages] = useState(['en']); // Default to English const [initialLoading, setInitialLoading] = useState(true); // Load user preferences on component mount useEffect(() => { const loadUserPreferences = async () => { try { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/discover/preferences`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); if (res.ok) { const data = await res.json(); setUserPreferences(data.categories || ['AI', 'Technology']); setPreferredLanguages(data.languages || ['en']); // Default to English if no languages are set } } catch (err: any) { console.error('Error loading preferences:', err.message); // Use default preferences if loading fails } finally { setInitialLoading(false); } }; loadUserPreferences(); }, []); if (initialLoading) { return (
); } return (
{/* Static header that doesn't re-render when content changes */} {/* Dynamic content that updates independently */} {/* Preferences modal */}
); }; export default Page;