'use client'; import { Search, Sliders, ChevronLeft, ChevronRight } from 'lucide-react'; import { useEffect, useState, useRef } 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', 'Weather', 'Entertainment', 'Art and Culture', 'Science', 'Health', 'Travel' ]; const Page = () => { const [discover, setDiscover] = useState(null); const [loading, setLoading] = useState(true); 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 // Temporary state for the preferences modal const [tempPreferences, setTempPreferences] = useState([]); const [tempLanguages, setTempLanguages] = useState([]); 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' }); }; // 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 } }; loadUserPreferences(); }, []); // 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'); } }; // Fetch data based on active category, user preferences, and language useEffect(() => { const fetchData = async () => { setLoading(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 { setLoading(false); } }; fetchData(); }, [activeCategory, userPreferences, preferredLanguages]); return loading ? (
) : ( <>

Discover

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

{/* Personalization Modal */} {/* Initialize temp preferences when modal opens */} {showPreferences && (() => { // Initialize temp preferences when modal opens if (tempPreferences.length === 0) { setTempPreferences([...userPreferences]); } if (tempLanguages.length === 0) { setTempLanguages([...preferredLanguages]); } 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)`}

); })()}
{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)}...

))}
); }; export default Page;