"use client"; import { Box, Heading, VStack, Text, Card, HStack, Badge, Button, Input, SimpleGrid, Spinner, Icon } from "@chakra-ui/react"; import { LuTrendingUp, LuSearch, LuSparkles, LuRefreshCw, LuArrowRight, LuGlobe, LuHash, LuZoomIn } from "react-icons/lu"; import { toaster } from "@/components/ui/feedback/toaster"; import { useState } from "react"; import { useSession } from "next-auth/react"; import { useRouter } from "@/i18n/navigation"; interface Trend { id: string; title: string; description?: string; score: number; volume?: number; source: string; keywords: string[]; relatedTopics: string[]; url?: string; } export default function TrendsPage() { const { data: session } = useSession(); const router = useRouter(); const [niche, setNiche] = useState(""); const [trends, setTrends] = useState([]); const [isScanning, setIsScanning] = useState(false); const [isDeepScanning, setIsDeepScanning] = useState(false); const [selectedTrend, setSelectedTrend] = useState(null); const [scanCount, setScanCount] = useState(0); const [translatingId, setTranslatingId] = useState(null); const [translatedContent, setTranslatedContent] = useState>({}); const handleScanTrends = async () => { if (!niche.trim()) { toaster.create({ title: "Please enter a niche or topic", type: "warning" }); return; } setIsScanning(true); try { const headers: HeadersInit = { 'Content-Type': 'application/json' }; if (session?.accessToken) { headers['Authorization'] = `Bearer ${session.accessToken}`; } const res = await fetch('/api/backend/trends/scan', { method: 'POST', headers, body: JSON.stringify({ keywords: [niche], country: 'TR', }), }); if (res.ok) { const response = await res.json(); // Backend wraps response in { success, status, message, data } const trendsData = response.data || response.trends || response; const trendsArray = Array.isArray(trendsData) ? trendsData : []; setTrends(trendsArray); setScanCount(1); toaster.create({ title: `${trendsArray.length} trend bulundu`, type: trendsArray.length > 0 ? "success" : "info" }); } else { throw new Error('Failed to scan trends'); } } catch (error) { console.error('Scan error:', error); toaster.create({ title: "Failed to scan trends", type: "error" }); } finally { setIsScanning(false); } }; // DEEPER RESEARCH - Prepends new results and uses all languages const handleDeepResearch = async () => { if (!niche.trim()) { toaster.create({ title: "Please enter a niche or topic first", type: "warning" }); return; } setIsDeepScanning(true); try { const headers: HeadersInit = { 'Content-Type': 'application/json' }; if (session?.accessToken) { headers['Authorization'] = `Bearer ${session.accessToken}`; } // Use different keywords for deeper research const deepKeywords = [ niche, `${niche} trends`, `${niche} news`, `latest ${niche}`, ]; const res = await fetch('/api/backend/trends/scan', { method: 'POST', headers, body: JSON.stringify({ keywords: deepKeywords, country: 'TR', allLanguages: true, // Fetch global trends }), }); if (res.ok) { const response = await res.json(); const trendsData = response.data || response.trends || response; const newTrends = Array.isArray(trendsData) ? trendsData : []; // Prepend new trends, filter duplicates by title const existingTitles = new Set(trends.map(t => t.title.toLowerCase())); const uniqueNewTrends = newTrends.filter( (t: Trend) => !existingTitles.has(t.title.toLowerCase()) ); setTrends(prev => [...uniqueNewTrends, ...prev]); setScanCount(prev => prev + 1); toaster.create({ title: `${uniqueNewTrends.length} yeni trend eklendi (Üste eklendi)`, description: `Toplam: ${trends.length + uniqueNewTrends.length} trend`, type: uniqueNewTrends.length > 0 ? "success" : "info" }); } else { throw new Error('Failed to deep scan'); } } catch (error) { console.error('Deep scan error:', error); toaster.create({ title: "Derin araştırma başarısız", type: "error" }); } finally { setIsDeepScanning(false); } }; const handleTranslate = async (trend: Trend) => { if (translatedContent[trend.id]) return; setTranslatingId(trend.id); try { const headers: HeadersInit = { 'Content-Type': 'application/json' }; if (session?.accessToken) { headers['Authorization'] = `Bearer ${session.accessToken}`; } // Translate title and description together for efficiency const textToTranslate = `${trend.title}\n---\n${trend.description || ""}`; const res = await fetch('/api/backend/trends/translate', { method: 'POST', headers, body: JSON.stringify({ text: textToTranslate, targetLanguage: 'Turkish', }), }); if (res.ok) { const responseData = await res.json(); // Handle potential 'data' wrapping from NestJS interceptors const data = responseData.data || responseData; const translatedText = data.translatedText; if (translatedText && typeof translatedText === 'string') { const [newTitle, ...descParts] = translatedText.split('\n---\n'); setTranslatedContent(prev => ({ ...prev, [trend.id]: { title: newTitle.trim(), description: descParts.join('\n---\n').trim(), } })); } else { throw new Error('Invalid translation response'); } } } catch (error) { console.error('Translation error:', error); toaster.create({ title: "Çeviri başarısız", type: "error" }); } finally { setTranslatingId(null); } }; const handleCreateContent = (trend: Trend) => { // Navigate to generate page with pre-filled trend data const params = new URLSearchParams(); params.set('topic', trend.title); if (trend.description) { params.set('description', trend.description); } if (trend.keywords && trend.keywords.length > 0) { params.set('keywords', JSON.stringify(trend.keywords)); } if (trend.source) { params.set('source', trend.source); } router.push(`/generate?${params.toString()}`); }; return ( {/* Header */} Trend Araştırması Güncel trendleri keşfet ve içerik oluştur {/* Search Box */} setNiche(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleScanTrends()} flex={1} /> Google Trends, Twitter, Reddit ve haber kaynaklarından güncel trendleri tarar {/* Deeper Research Button - Shows after initial scan */} {trends.length > 0 && ( {trends.length} trend bulundu (Tarama #{scanCount}) )} {/* Results */} {trends.length > 0 && ( {trends.map((trend) => ( setSelectedTrend(trend)} _hover={{ shadow: "md" }} > {Math.round(trend.score)} {trend.source} {translatedContent[trend.id]?.title || trend.title} {(translatedContent[trend.id]?.description || trend.description) && ( {translatedContent[trend.id]?.description || trend.description} )} {translatedContent[trend.id] && ( AI Çeviri )} {trend.keywords.length > 0 && ( {trend.keywords.slice(0, 3).map((kw, i) => ( {kw} ))} )} {trend.url && ( )} {!translatedContent[trend.id] && trend.relatedTopics?.some(t => ['EN', 'DE'].includes(t)) && ( )} ))} )} {/* Empty State */} {!isScanning && trends.length === 0 && ( Henüz trend taraması yapılmadı.
Bir niş veya konu girerek başlayın.
)}
); }