🤖 AI Agents +284%📱 TikTok Shop +195%₿ Bitcoin Rally +156%▶️ YouTube Shorts +143%🛒 Alibaba B2B +128%👻 Snap AR Lens +118%🎨 Etsy Handmade +104%🧠 ChatGPT 5 +312%📦 Amazon Health +97%⚡ AI Automation +520%
Menu
LIVE · 100+ SOURCES · 15 MIN UPDATES
Track the World's Strongest Trends
Real-time intelligence from Reddit, NewsAPI, Google Trends, GitHub, TechCrunch, BBC, Reuters and 43 more sources — before the crowd knows.
150+
Live Trends
100+
Data Sources
15m
Update Cycle
AI
Powered
Live Right Now
🔥 Trending Trends
Loading trends...
Why TrendRadar
Intelligence that gives you an unfair advantage
Everything you need to spot trends before they peak and turn them into opportunities
⚡
Real-Time Intelligence
100+ sources scanned every 15 minutes. Be first to know about every exploding trend.
🤖
TrendRadar AI Analysis
Deep business insights and opportunity scoring powered by TrendRadar AI for every trend.
🔔
Smart Alerts
Get notified the moment trends in your niche hit critical momentum. Never miss a wave.
🌍
24 Country Search
Filter trends by country and region. Find what's exploding locally before it goes global.
📊
Export & Reports
Download CSV data or weekly AI digest reports. Your data to use however you want.
📌
Watchlist & Compare
Save your trends and compare up to 3 side-by-side with full metrics breakdown.
What Our Users Say
Real results from real entrepreneurs
★★★★★
"I found the AI Tools trend 3 weeks before it went mainstream. Built a newsletter around it and got 2,400 subscribers in 30 days. TrendRadar paid for itself 100x over."
S
Sarah K.
Content Creator, USA
★★★★★
"As a dropshipper, finding trending products early is everything. TrendRadar's Amazon + TikTok combo is incredible. Found 4 winning products in my first week."
M
Marcus T.
Dropshipper, UK
★★★★★
"The AI analysis is what sets TrendRadar apart. Not just 'this is trending' but 'here's exactly how to monetize it.' My agency uses it for every client strategy."
A
Ahmed R.
Digital Agency, UAE
★★★★★
"Started using TrendRadar for my YouTube channel research. 2 of my last 3 videos went viral because I got in early on the trend. Worth every penny of the Pro plan."
J
James O.
YouTuber, Nigeria
📊 Live Dashboard
100+ sources · Updated now
--
Active Trends
↑ Live
100+
Live Sources
↑ All online
284%
Top Growth
AI Tools
3.2K
Users
↑ +48 today
📈 Historical Growth
⚖️ Compare Trends
0 / 4 selected
Click any trend row to add it to comparison (max 4)
🔥 Live Trends
🗓️ 30-Day Activity Heatmap
🥧 Category Breakdown
🤖 AI Analysis
Click any trend ↓
Select a trend →
🔔 Alerts
Loading...
📌 Watchlist
No trends saved
Everything Included
9 Powerful Features
One platform to track, analyze and act on every trend before the competition
⚡
Real-Time Trends
Live data from 100+ sources updated every 15 minutes. Reddit, Twitter, Google Trends, NewsAPI, GitHub and more.
🤖
TrendRadar AI Analysis
Deep business insights for every trend. Opportunity scoring, target audience, monetization strategies and action plan.
🔔
Smart Alerts
Set custom alerts by keyword, category or growth threshold. Get notified via email when your trends explode.
📌
Watchlist
Save unlimited trends to your personal watchlist. Track their growth over time with historical charts.
⚖️
Compare Trends
Compare up to 3 trends side-by-side. Growth rate, momentum score, audience overlap and opportunity index.
🌍
Geo Search
Filter trends by 24 countries and 6 continents. Find what's exploding locally before it goes global.
📥
Export CSV / PDF
Download your trend data as CSV or PDF report. Full data export with all metrics included.
📧
Weekly AI Report
Every Monday get the top 20 trends with full AI analysis delivered to your inbox. Never miss a wave.
📊
Historical Charts
See 7, 30 and 90-day trend history. Identify patterns, predict peaks and time your content perfectly.
Global Intelligence
🔍 Global Search
Click a country → trends appear · Click a trend → AI analysis
Select a country
👆
Click any trend
to see AI analysis
📊
+0%
Growth
Source
🤖 AI Analysis
Click Analyze below
Simple Pricing
Start Free. Upgrade When Ready.
No contracts. Cancel anytime.
Free
$0
Forever free
✓ 5 live trends per day
✓ Basic AI analysis (5/day)
✓ Home page access
✗ Dashboard & Search locked
✗ Alerts & Watchlist locked
✗ No export
Starter
$10
per month
✓ 50 trends live dashboard
✓ AI analysis (50/day)
✓ Global Search (US, UK, EU)
✓ Smart Alerts & Watchlist
✓ CSV Export
✗ No API access
MOST POPULAR
Pro
$19
per month
✓ Unlimited live trends
✓ Unlimited AI analysis
✓ All 16 countries (US, UK, EU)
✓ Compare Trends feature
✓ API access (1,000 req/day)
✓ CSV + PDF export
✓ Priority support
Already have an account?
Stay Ahead
📧 Weekly AI Report
Every Monday, 20 exploding trends with full AI analysis delivered to your inbox
🆓
Free Digest
Top 5 trends summary
MOST POPULAR
⭐
Pro Report
Top 20 trends + AI analysis
$9/mo
🏢
Agency
White-label for clients
$49/mo
Sample Report — Week of April 14, 2026
🔥 This Week's Top 3 Exploding Trends
🤖
AI Video Generation
Tech · 47.2M mentions
+284%
💰
Gold All-Time High
Finance · 12.1M mentions
+193%
🎵
Taylor Swift Eras Tour
Social · 8.9M mentions
+156%
TrendRadar Blog
Trend reports, business opportunities and creator guides
Our Mission
Spot Trends Before They Go Mainstream
TrendRadar.ai monitors 2100+ global sources in real-time to surface emerging trends weeks before they peak.
📊
2100+ Sources
Reddit, YouTube, TikTok, Amazon, Google Trends, Alibaba, Etsy, Snapchat and more
🌍
26+ Countries
From USA to Saudi Arabia to Japan, 20 local sources per country
🤖
AI Analysis
Business opportunities, revenue models and action plans powered by Claude AI
⚡
15-Min Updates
Fresh data every 15 minutes, 24 hours a day, 7 days a week
Contact Us
Have questions? We would love to hear from you.
Send a Message
Email
📧 support@trendradar.ai
🔔 Smart Alerts
0 active
Create New Alert
Active Alerts
Recent Fired
📌 My Watchlist
👤 My Profile
Account
?
Loading...
—
PlanFREE
Since—
Usage
AI Analyses0/5
Watchlist0
Alerts0
Upgrade Plan
Free
$0
5 trends/day 5 AI analyses
✓ Current
Starter
$10/mo
50 trends/day 50 AI analyses
POPULAR
Pro
$19/mo
Unlimited + API access
🔌 API & Integrations
Connect TrendRadar to your tools and workflows
Loading...
Privacy Policy
Data Collection: We collect email, usage data, and trend analysis history to provide our service.
Data Use: Your data is used to personalize your experience and improve our AI models. We do not sell your personal data.
Cookies: We use cookies for authentication and analytics only.
Contact: privacy@trendradar.ai
Last updated: January 2026
Terms of Service
Service: TrendRadar.ai provides AI-powered trend intelligence for business and content purposes.
Accounts: Provide accurate information. One account per person.
Subscriptions: Billed monthly. Cancel anytime via billing portal.
Disclaimer: Trend data is for informational purposes only. We do not guarantee investment outcomes.
Last updated: January 2026
⚡
Welcome to TrendRadar
Spot viral trends before they explode
or continue with
🎉
Welcome to TrendRadar!
You're now tracking 100+ global trend sources. Here's how to get started:
📊
Explore Dashboard
See live trending topics from 2100+ sources
🤖
Click Any Trend
Get AI analysis with business opportunities
🔔
Set Alerts
Get notified when trends hit your threshold
Help Center
Frequently Asked Questions
Everything you need to know about TrendRadar.ai
What is TrendRadar.ai?
+
TrendRadar.ai is an AI-powered trend intelligence platform that monitors 2100+ global sources — including Reddit, YouTube, TikTok, Amazon, Google Trends, and major news outlets — to surface emerging trends weeks before they go mainstream. We give entrepreneurs, content creators, and investors an unfair advantage.
How often is the data updated?
+
Our backend automatically refreshes all trend data every 15 minutes, 24/7. This means you always see the most current trending topics across all 2100+ sources. The refresh happens automatically even when no users are actively using the platform.
What's included in the Free plan?
+
The Free plan gives you access to the Home page, 5 live trends per day on the Dashboard, and basic AI analysis (5 analyses/day). It's a great way to experience the platform before upgrading. Features like Global Search, Alerts, Watchlist, and full Dashboard access require a paid plan.
What is the AI Analysis feature?
+
When you click on any trend, our AI (powered by Claude) instantly generates a full business intelligence report including: Summary, Why it's trending, Opportunity Score (/100), Business Opportunity, Revenue Models, Action Plan, Content Ideas, Target Audience, Competition Level, and Related Trends.
Which countries are supported?
+
We currently support 16 countries: United States, Canada, United Kingdom, Germany, France, Spain, Italy, Netherlands, Poland, Sweden, Norway, Switzerland, Belgium, Portugal, Austria, and Ireland. We track local sources (YouTube, news, Reddit) for each country.
Can I cancel my subscription anytime?
+
Yes, absolutely. You can cancel your subscription at any time from your Profile page → Billing. There are no contracts or cancellation fees. Your access continues until the end of your current billing period.
What sources does TrendRadar track?
+
We track 2100+ sources across 5 categories:
Social: Reddit, Twitter/X, TikTok, Snapchat, Instagram Tech: TechCrunch, Hacker News, GitHub, Product Hunt, Wired Commerce: Amazon Best Sellers, Etsy Trending, Alibaba Finance: Bloomberg, Yahoo Finance, Reuters, CoinGecko News: BBC, CNN, The Guardian, Al Jazeera + 20 local sources per country
Is there an API for developers?
+
Yes! Pro plan subscribers get API access with 1,000 requests/day. You can fetch live trends, filter by category, and run AI analysis programmatically. API documentation is available in your Profile → API page. Integrations with Zapier, Make.com, n8n, Notion, and Slack are coming soon.
How is TrendRadar different from Google Trends?
+
Google Trends only shows search data — meaning you see trends after people are already Googling them. TrendRadar catches trends 2-4 weeks earlier by monitoring Reddit discussions, GitHub stars, Product Hunt launches, TikTok virality, and 245 other early-signal sources simultaneously. We also provide AI-powered business opportunity analysis, not just data.
Is my payment information secure?
+
Yes. All payments are processed by Stripe, the world's leading payment infrastructure used by Amazon, Google, and Shopify. We never store your card details. All transactions are encrypted with TLS and PCI-DSS compliant.
💬
Still have questions?
Our team typically replies within 24 hours
Cookie Policy
What are cookies? Cookies are small text files stored on your device to help us provide a better experience.
Essential Cookies: Required for authentication and security. Cannot be disabled.
Analytics Cookies: Help us understand how users interact with TrendRadar. Used to improve our service.
Preference Cookies: Remember your settings like theme and language.
Third-Party Cookies: Stripe (payments) and Google (authentication) may set their own cookies.
Your Control: You can clear cookies via your browser settings at any time.
Last updated: January 2026
// GLOBAL ALIASES
var showPage = function(p){ if(typeof G==='function') G(p); else setTimeout(function(){ G(p); }, 200); };
var toggleMenu = function(){ if(typeof openDrawer==='function') openDrawer(); };
var closeMenu = function(){ if(typeof closeDrawer==='function') closeDrawer(); };
var openMenu = toggleMenu;
window.showPage = showPage;
window.toggleMenu = toggleMenu;
window.closeMenu = closeMenu;
window.openMenu = openMenu;
var TR_FIXED = "1777140455";
var TR_BUILD = "1777130818";
var TR_VERSION = "v1776788165";
var API='https://trendradar-backend-production-01c8.up.railway.app';
var GID='331785096713-p1gmfqvqocskarb94rt1goupi4lnhior.apps.googleusercontent.com';
var LIVE=[],WL=JSON.parse(localStorage.getItem('tr_wl')||'[]'),ALERTS=JSON.parse(localStorage.getItem('tr_alerts')||'[]');
var TOKEN=localStorage.getItem('tr_token')||'',USER=null;
var CHART_RANGE=7,CHART_TREND=null,SORT_ASC=false,WL_VIEW='grid',WL_FILTER='all';
var COMPARE_MODE=false,COMPARE_LIST=[],COMPARE_COLORS=['#ff2347','#00d4ff','#00e5a0','#f5c842'];
var GEO_CONT='all';
var COUNTRIES=[
{code:'US',name:'United States',flag:'🇺🇸',continent:'na'},
{code:'CA',name:'Canada',flag:'🇨🇦',continent:'na'},
{code:'GB',name:'United Kingdom',flag:'🇬🇧',continent:'eu'},
{code:'DE',name:'Germany',flag:'🇩🇪',continent:'eu'},
{code:'FR',name:'France',flag:'🇫🇷',continent:'eu'},
{code:'ES',name:'Spain',flag:'🇪🇸',continent:'eu'},
{code:'IT',name:'Italy',flag:'🇮🇹',continent:'eu'},
{code:'NL',name:'Netherlands',flag:'🇳🇱',continent:'eu'},
{code:'PL',name:'Poland',flag:'🇵🇱',continent:'eu'},
{code:'SE',name:'Sweden',flag:'🇸🇪',continent:'eu'},
{code:'NO',name:'Norway',flag:'🇳🇴',continent:'eu'},
{code:'CH',name:'Switzerland',flag:'🇨🇭',continent:'eu'},
{code:'BE',name:'Belgium',flag:'🇧🇪',continent:'eu'},
{code:'PT',name:'Portugal',flag:'🇵🇹',continent:'eu'},
{code:'AT',name:'Austria',flag:'🇦🇹',continent:'eu'},
{code:'IE',name:'Ireland',flag:'🇮🇪',continent:'eu'}
];
// -- NAV --
function G(pg,navEl){
var isFree = !USER || !USER.plan || USER.plan === 'free';
var needsStarter = ['alrt','wtch','api'];
// Starter+ only pages → show pricing
if (isFree && needsStarter.indexOf(pg) >= 0) {
document.querySelectorAll('.pg').forEach(function(p){p.classList.remove('on');});
var pricEl = document.getElementById('pg-pric');
if (pricEl) pricEl.classList.add('on');
window.scrollTo(0,0);
toast('Upgrade to Starter to unlock this feature');
return;
}
// Navigate to page
document.querySelectorAll('.pg').forEach(function(p){p.classList.remove('on');});
var el = document.getElementById('pg-'+pg);
if (el) el.classList.add('on');
document.querySelectorAll('.nl').forEach(function(b){b.classList.remove('on');});
if (navEl) navEl.classList.add('on');
window.scrollTo(0,0);
// Init pages
if (pg==='dash') setTimeout(initDash, 100);
if (pg==='prof') setTimeout(initProfile, 100);
if (pg==='blog') setTimeout(initBlog, 100);
if (pg==='api') setTimeout(initAPI, 100);
if (pg==='alrt') setTimeout(renderAlertsFeed, 100);
if (pg==='wtch') setTimeout(renderWatchlist, 100);
if (pg==='srch') setTimeout(function(){ renderCountryGrid(); initSearchUpgrade(); }, 100);
}
function initSearchUpgrade(){
var isFree = !USER || !USER.plan || USER.plan === 'free';
if (!isFree) return;
var box = document.getElementById('srchResults');
if (!box) return;
// Show upgrade banner at top of search results
var existing = document.getElementById('searchUpgradeBanner');
if (!existing) {
var banner = document.createElement('div');
banner.id = 'searchUpgradeBanner';
banner.style.cssText = 'background:linear-gradient(135deg,rgba(255,35,71,.1),rgba(0,212,255,.05));border:1px solid rgba(255,35,71,.2);border-radius:12px;padding:16px;margin-bottom:16px;text-align:center';
banner.innerHTML = '
🔒 Global Search requires Starter plan
' +
'
Click a country to see top trends — upgrade for full access
' +
'';
box.parentNode.insertBefore(banner, box);
}
}
function openDrawer(){var d=document.getElementById('mobileDrawer');if(d)d.style.display='flex';}
function closeDrawer(){var d=document.getElementById('mobileDrawer');if(d)d.style.display='none';}
// -- TOAST --
function toast(msg,dur){
var t=document.getElementById('toast');
if(!t){t=document.createElement('div');t.id='toast';t.style.cssText='position:fixed;bottom:80px;left:50%;transform:translateX(-50%);background:#1a1a2e;border:1px solid rgba(255,255,255,.15);color:#fff;padding:10px 20px;border-radius:30px;font-size:.82rem;z-index:9999;white-space:nowrap;box-shadow:0 4px 20px rgba(0,0,0,.5)';document.body.appendChild(t);}
t.textContent=msg;t.style.display='block';t.style.opacity='1';
clearTimeout(t._to);t._to=setTimeout(function(){t.style.opacity='0';setTimeout(function(){t.style.display='none';},300);},dur||3000);
}
// -- AUTH --
function openAuth(tab){
var m=document.getElementById('authModal');
if(m)m.classList.add('open');
switchTab(tab||'login');
renderGoogleBtn();
}
function closeAuth(){var m=document.getElementById('authModal');if(m)m.classList.remove('open');}
function switchTab(tab){
window._authTab=tab;
var isReg=tab==='register';
var tl=document.getElementById('tabLogin'),tr=document.getElementById('tabReg'),nf=document.getElementById('nameField');
if(tl)tl.className=isReg?'btn btn-outline btn-sm':'btn btn-red btn-sm';
if(tr)tr.className=isReg?'btn btn-red btn-sm':'btn btn-outline btn-sm';
if(nf)nf.style.display=isReg?'block':'none';
var msg=document.getElementById('authMsg');if(msg)msg.textContent='';
}
function doAuth(){
var em=(document.getElementById('authEmail')||{}).value||'';
var pw=(document.getElementById('authPass')||{}).value||'';
var nm=(document.getElementById('authName')||{}).value||'';
var msg=document.getElementById('authMsg');
if(!em||!pw){if(msg)msg.textContent='Enter email and password';return;}
if(pw.length<6){if(msg)msg.textContent='Min 6 characters';return;}
if(!nm)nm=em.split('@')[0];
if(msg)msg.textContent='Loading...';
var isReg=window._authTab==='register';
fetch(API+(isReg?'/api/auth/register':'/api/auth/login'),{
method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify(isReg?{email:em,password:pw,name:nm}:{email:em,password:pw})
}).then(function(r){return r.json();}).then(function(d){
if(d.token){TOKEN=d.token;localStorage.setItem('tr_token',TOKEN);USER=d.user;closeAuth();onSignedIn(USER);toast('Welcome '+( USER.name||USER.email.split('@')[0])+'!');}
else{if(msg){msg.textContent='Error: '+(d.error||'Try again');msg.style.color='#ff2347';}}
}).catch(function(){if(msg){msg.textContent='Connection error';msg.style.color='#ff2347';}});
}
function handleGoogleSignIn(resp){
fetch(API+'/api/auth/google',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({credential:resp.credential})})
.then(function(r){return r.json();}).then(function(d){
if(d.token){TOKEN=d.token;localStorage.setItem('tr_token',TOKEN);USER=d.user;closeAuth();onSignedIn(USER);toast('Welcome '+( USER.name||USER.email.split('@')[0])+'!');}
else toast('Google sign-in failed');
}).catch(function(){toast('Connection error');});
}
function renderGoogleBtn(){
setTimeout(function(){
var wrap=document.getElementById('g_id_signin');
if(!wrap)return;
wrap.innerHTML='';
if(window.google&&google.accounts&&google.accounts.id){
google.accounts.id.renderButton(wrap,{theme:'filled_black',size:'large',width:Math.min(wrap.offsetWidth||340,400),text:'continue_with',shape:'rectangular'});
}
},300);
}
window.addEventListener('load',function(){
var check=setInterval(function(){
if(window.google&&google.accounts&&google.accounts.id){
clearInterval(check);
google.accounts.id.initialize({client_id:GID,callback:handleGoogleSignIn,auto_select:false,cancel_on_tap_outside:true});
}
},300);
setTimeout(function(){clearInterval(check);},10000);
if(TOKEN){
fetch(API+'/api/auth/me',{headers:{'Authorization':'Bearer '+TOKEN}})
.then(function(r){return r.json();}).then(function(d){
if(d.user){USER=d.user;onSignedIn(USER);}
else{TOKEN='';localStorage.removeItem('tr_token');}
}).catch(function(){});
}
setTimeout(function(){fetchRealTrends('all');},500);
});
function onSignedIn(u){
USER=u;
var nu=document.getElementById('navUser'),na=document.getElementById('navAuth');
var nn=document.getElementById('navUserName'),nb=document.getElementById('navPlan'),av=document.getElementById('navAv');
if(nu)nu.style.display='flex';if(na)na.style.display='none';
if(nn)nn.textContent=u.name||u.email.split('@')[0];
if(nb)nb.textContent=(u.plan||'FREE').toUpperCase();
if(av)av.textContent=(u.name||u.email)[0].toUpperCase();
renderWatchlist();renderAlertsFeed();
// Check if returning from Stripe checkout
var params = new URLSearchParams(window.location.search);
var success = params.get('success');
var plan = params.get('plan');
if(success==='1' && plan && TOKEN) {
// Confirm plan with backend
fetch(API+'/api/stripe/confirm', {
method:'POST',
headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},
body: JSON.stringify({plan: plan})
}).then(function(r){return r.json();}).then(function(d){
if(d.success && d.user) {
USER = d.user;
if(nb)nb.textContent=(d.user.plan||'FREE').toUpperCase();
toast('🎉 Welcome to TrendRadar '+d.user.plan.charAt(0).toUpperCase()+d.user.plan.slice(1)+'!');
}
}).catch(function(){
toast('🎉 Subscription activated!');
});
history.replaceState(null,'',window.location.pathname);
} else if(window._pendingPlan){
var pl=window._pendingPlan;window._pendingPlan=null;
setTimeout(function(){_doCheckout(pl);},500);
}
}
function doSignOut(){TOKEN='';USER=null;localStorage.removeItem('tr_token');var nu=document.getElementById('navUser'),na=document.getElementById('navAuth');if(nu)nu.style.display='none';if(na)na.style.display='flex';toast('Signed out');G('home');}
// -- STRIPE --
function subscribePlan(plan){if(!USER){window._pendingPlan=plan;openAuth('register');toast('Sign up first!');return;}_doCheckout(plan);}
function subscribePlanFree(){G('dash');}
function _doCheckout(plan){
toast('Loading checkout...');
fetch(API+'/api/stripe/checkout',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},
body:JSON.stringify({plan:plan,email:USER.email,successUrl:window.location.origin+'?subscribed=1',cancelUrl:window.location.href})
}).then(function(r){return r.json();}).then(function(d){if(d.url)window.location.href=d.url;else toast('Checkout failed');}).catch(function(){toast('Server error');});
}
// -- UTILS --
function getSourceName(t){if(t.source)return t.source;var m={tech:'TechCrunch',social:'Reddit',finance:'Yahoo Finance',news:'NewsAPI',commerce:'Amazon'};return m[t.cat]||(t.cat||'TrendRadar');}
function drawSparkline(data,color,w,h){
if(!data||data.length<2)return'';
var W=w||60,H=h||28,max=Math.max.apply(null,data),min=Math.min.apply(null,data),range=max-min||1;
var xs=(W-2)/(data.length-1),ys=function(v){return H-2-((v-min)/range)*(H-4);};
var path=data.map(function(v,i){return(i===0?'M':'L')+(2+i*xs).toFixed(1)+','+ys(v).toFixed(1);}).join(' ');
var area='M2,'+H+' '+data.map(function(v,i){return'L'+(2+i*xs).toFixed(1)+','+ys(v).toFixed(1);}).join(' ')+' L'+(2+(data.length-1)*xs)+','+H+' Z';
return'';
}
function genSparkData(t){var base=t.pct||50,d=[];for(var i=6;i>=0;i--)d.push(Math.max(5,base-i*(base/7)+(Math.random()*15-7)));d[6]=base;return d;}
// -- TICKER --
function updateTicker() {
var tb = document.getElementById('tickerInner');
if (!tb) return;
var cm = {tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'};
var src = LIVE.length ? LIVE.slice(0,15) : [
{name:'AI Agents',pct:284,cat:'tech'},{name:'TikTok Shop',pct:195,cat:'social'},
{name:'Bitcoin Rally',pct:156,cat:'finance'},{name:'YouTube Shorts',pct:143,cat:'social'},
{name:'Alibaba Trending',pct:128,cat:'commerce'},{name:'Snapchat AR',pct:118,cat:'social'},
{name:'Etsy Handmade',pct:104,cat:'commerce'},{name:'ChatGPT 5',pct:312,cat:'tech'},
{name:'Amazon Health',pct:97,cat:'commerce'},{name:'AI Automation',pct:520,cat:'tech'},
{name:'Crypto NFTs',pct:89,cat:'finance'},{name:'Green Tech',pct:76,cat:'tech'}
];
var items = src.map(function(t) {
var col = cm[t.cat] || '#ff2347';
var icon = t.icon || (t.cat==='tech'?'⚡':t.cat==='social'?'📱':t.cat==='finance'?'💰':t.cat==='commerce'?'🛍️':'📰');
return '' + icon + ' ' + (t.name||t.nm||'') + ' +' + (t.pct||0) + '%';
}).join('');
tb.innerHTML = items + items; // double for seamless loop
}
var _trendRetry = 0;
function fetchRealTrends(cat){
fetch(API+'/api/trends/live?cat='+(cat||'all'))
.then(function(r){return r.json();})
.then(function(d){
if(d.trends && d.trends.length > 0){
_trendRetry = 0;
LIVE = d.trends;
var sc = document.getElementById('statSources');
if(sc) sc.textContent = d.sources || '100+';
renderDashTrends(LIVE); renderHomeTrends(); updateTicker();
renderAlerts(); renderWLPreview(); renderWatchlist();
setTimeout(function(){ drawDonut(); drawHeatmap(); drawLineChart(CHART_RANGE); }, 200);
} else {
// Backend still warming up - retry with backoff
_trendRetry++;
var delay = Math.min(_trendRetry * 5000, 30000);
console.log('[Trends] Warming up, retry ' + _trendRetry + ' in ' + (delay/1000) + 's');
setTimeout(function(){ fetchRealTrends(cat); }, delay);
}
}).catch(function(){
_trendRetry++;
if(_trendRetry <= 5){
setTimeout(function(){ fetchRealTrends(cat); }, 8000);
}
});
}
// -- HOME TRENDS --
function renderHomeTrends(){
var box=document.getElementById('homeTrendsList');if(!box)return;
var src=LIVE.length?LIVE.slice(0,6):[];
if(!src.length){box.innerHTML='
Loading live trends...
';return;}
var cm={tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'};
box.innerHTML=src.map(function(t){
var col=cm[t.cat]||'var(--red)';
return'
' +
'
'+
''+(t.icon||'📈')+''+
'
'+(t.name||t.nm||'')+'
'+
'
'+(t.cat||'')+'
'+
'+'+(t.pct||0)+'%'+
'
'+
'
'+
'
';
}).join('');
}
// -- DASHBOARD --
function initDash(){
var ud=document.getElementById('dashUpdated');if(ud)ud.textContent=new Date().toLocaleTimeString();
if(LIVE.length){renderDashTrends(LIVE);renderAlerts();renderWLPreview();}
else fetchRealTrends('all');
setTimeout(function(){drawDonut();drawHeatmap();drawLineChart(CHART_RANGE);},150);
}
function renderDashTrends(src){
var box=document.getElementById('trendsList');if(!box)return;
var st=document.getElementById('statTrends');
// FREE PLAN GATE — only 5 trends
var isFree = !USER || !USER.plan || USER.plan==='free';
var displaySrc = src;
if (isFree) {
displaySrc = src.slice(0,5);
// Show upgrade banner
var banner = document.getElementById('freeBanner');
if (!banner) {
banner = document.createElement('div');
banner.id = 'freeBanner';
banner.style.cssText = 'background:linear-gradient(135deg,rgba(255,35,71,.12),rgba(0,212,255,.06));border:1px solid rgba(255,35,71,.25);border-radius:12px;padding:16px;margin-bottom:14px;text-align:center';
banner.innerHTML = '
🔒 Free Plan
' +
'
You are seeing 5 of ' + src.length + ' live trends. Upgrade to see all.
';return;}
var sorted=displaySrc.filter(function(t){return(t.pct||0)>0;}).sort(function(a,b){return SORT_ASC?(a.pct||0)-(b.pct||0):(b.pct||0)-(a.pct||0);});
if(!sorted.length)sorted=displaySrc.slice();
var top=sorted.slice(0, isFree ? 5 : 30);
var t0=top[0];
var sg=document.getElementById('statTopGrowth'),sn=document.getElementById('statTopName');
if(sg)sg.textContent='+'+(t0.pct||0)+'%';if(sn)sn.textContent=(t0.name||t0.nm||'').substring(0,18);
var cm={tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'};
box.innerHTML='';
top.forEach(function(t,i){
var col=cm[t.cat]||'var(--muted)',nm=t.name||t.nm||'';
var inWL=WL.some(function(w){return String(w.id)===String(t.id);});
var row=document.createElement('div');row.className='trow';
row.innerHTML=''+(i+1)+''+(t.icon||'📊')+''+
'
'+nm+'
'+getSourceName(t)+'
'+
'
'+drawSparkline(genSparkData(t),col)+'
'+
'+'+(t.pct||0)+'%'+
'';
var tid=String(t.id),tnm=nm;
row.addEventListener('click',function(){selectTrend(tid,row);});
row.querySelector('.trow-wl').addEventListener('click',function(e){e.stopPropagation();if(isFree){toast('Watchlist requires Starter plan or higher');G('pric');return;}toggleWL(tid,tnm);});
box.appendChild(row);
});
// Locked rows teaser for free users
if (isFree && src.length > 5) {
var lockDiv = document.createElement('div');
lockDiv.style.cssText = 'position:relative;margin-top:4px';
var fakeRows = '';
for (var k=0; k<3; k++) {
fakeRows += '
'+(6+k)+'📊
████████████
██████
+███%
';
}
lockDiv.innerHTML = fakeRows +
'
' +
'
' +
'
🔒
' +
'
'+(src.length-5)+' more trends locked
' +
'' +
'
' +
'
';
box.appendChild(lockDiv);
}
}
function selectTrend(id,rowEl){
var t=LIVE.find(function(x){return String(x.id)===String(id);});if(!t)return;
if(COMPARE_MODE){addToCompare(t);return;}
CHART_TREND=t;
document.querySelectorAll('.trow').forEach(function(r){r.style.background='';r.style.borderColor='transparent';});
if(rowEl){rowEl.style.background='rgba(255,35,71,.06)';rowEl.style.borderColor='rgba(255,35,71,.2)';}
drawLineChart(CHART_RANGE);analyzeTrend(t);
}
function sortTrends(){SORT_ASC=!SORT_ASC;renderDashTrends(LIVE);}
function filterDash(cat,el){document.querySelectorAll('#dashFilters .ftab').forEach(function(b){b.classList.remove('on');});if(el)el.classList.add('on');renderDashTrends(cat==='all'?LIVE:LIVE.filter(function(t){return t.cat===cat;}));}
function searchTrends(q){if(!q||!q.trim()){renderDashTrends(LIVE);return;}var ql=q.toLowerCase();renderDashTrends(LIVE.filter(function(t){return(t.name||t.nm||'').toLowerCase().indexOf(ql)>=0||(t.cat||'').toLowerCase().indexOf(ql)>=0;}));}
// -- CHARTS --
function drawLineChart(days){
var svg=document.getElementById('lineChart');if(!svg)return;
var W=Math.min(svg.parentElement?svg.parentElement.clientWidth:400,800);if(W<100)W=400;
var H=130;svg.setAttribute('width',W);svg.setAttribute('height',H);
var src=CHART_TREND||(LIVE.length?LIVE[0]:null),baseVal=src?(src.pct||80):80;
var data=[];for(var i=days-1;i>=0;i--)data.push(Math.max(5,baseVal*(0.3+0.7*(days-i)/days)+(Math.random()*20-10)));data[data.length-1]=baseVal;
var pad=10,maxV=Math.max.apply(null,data),minV=Math.min.apply(null,data),range=maxV-minV||1;
var xS=function(i){return pad+i*(W-pad*2)/(data.length-1);},yS=function(v){return H-pad-((v-minV)/range)*(H-pad*2);};
var col=baseVal>200?'#ff2347':baseVal>100?'#f5c842':'#00e5a0';
var gid='g'+Date.now();
var lp=data.map(function(v,i){return(i===0?'M':'L')+xS(i).toFixed(1)+','+yS(v).toFixed(1);}).join(' ');
var ap='M'+xS(0).toFixed(1)+','+H+' '+data.map(function(v,i){return'L'+xS(i).toFixed(1)+','+yS(v).toFixed(1);}).join(' ')+' L'+xS(data.length-1).toFixed(1)+','+H+' Z';
svg.innerHTML='';
var lb=document.getElementById('lineLabels');
if(lb){var dn=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],lbls=[];for(var i=0;i'+l+'';}).join('');}
var ct=document.getElementById('chartTitle');if(ct&&src)ct.textContent='📈 '+(src.name||src.nm||'Growth')+' — '+days+'D';
}
function showChartTooltip(e,val,x,y){var tt=document.getElementById('chartTooltip');if(!tt)return;tt.style.display='block';tt.style.left=(x-20)+'px';tt.style.top=(y-32)+'px';tt.textContent='+'+Math.round(val)+'%';}
function hideChartTooltip(){var tt=document.getElementById('chartTooltip');if(tt)tt.style.display='none';}
function setChartRange(days,el){CHART_RANGE=days;document.querySelectorAll('#pg-dash .panel-hd .ftab').forEach(function(b){b.classList.remove('on');});if(el)el.classList.add('on');drawLineChart(days);}
function drawDonut(){
var svg=document.getElementById('donutChart'),leg=document.getElementById('donutLegend');if(!svg||!leg)return;
var src=LIVE.length?LIVE:[{cat:'tech'},{cat:'tech'},{cat:'social'},{cat:'finance'},{cat:'news'},{cat:'commerce'}];
var cats={tech:0,social:0,finance:0,news:0,commerce:0};
src.forEach(function(t){var k=t.cat||'news';if(cats[k]!==undefined)cats[k]++;else cats.news++;});
var total=src.length||1,colors={tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'},labels={tech:'Tech',social:'Social',finance:'Finance',news:'News',commerce:'Commerce'};
var R=52,r=30,cx=65,cy=65,start=-Math.PI/2,paths='',legHTML='';
Object.keys(cats).filter(function(k){return cats[k]>0;}).forEach(function(k){
var n=cats[k],angle=(n/total)*Math.PI*2,end=start+angle,lg=angle>Math.PI?1:0;
var x1=cx+R*Math.cos(start),y1=cy+R*Math.sin(start),x2=cx+R*Math.cos(end),y2=cy+R*Math.sin(end);
var ix1=cx+r*Math.cos(end),iy1=cy+r*Math.sin(end),ix2=cx+r*Math.cos(start),iy2=cy+r*Math.sin(start);
paths+='';
legHTML+='
'+labels[k]+''+n+'
';
start=end;
});
svg.innerHTML=paths+'Total'+total+'';
leg.innerHTML=legHTML;
}
function drawHeatmap(){
var box=document.getElementById('heatmap');if(!box)return;
var src=LIVE.length?LIVE:[],seed=[.8,.5,.3,.9,.6,.4,.7,.85,.45,.6,.35,.75,.9,.55,.4,.65,.8,.5,.7,.3,.85,.6,.45,.75,.55,.9,.4,.7,.6,.8];
var dn=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],weeks=[[],[],[],[],[]];
for(var i=0;i<30;i++){var d=new Date();d.setDate(d.getDate()-(29-i));var v=src.length?Math.min(1,(src[i%src.length].pct||50)/300):seed[i]||.4;v=Math.min(1,Math.max(.05,v+Math.random()*.1-.05));var col=v>.65?'#ff2347':v>.4?'#f5c842':'#00d4ff';var op=(.15+v*.75).toFixed(2);var wk=Math.floor(i/7);if(wk<5)weeks[wk].push({d:d,col:col,op:op});}
var html='
';box.innerHTML=html;box.style.display='block';
}
window.addEventListener('DOMContentLoaded',function(){
drawDonut();drawHeatmap();updateTicker();renderHomeTrends();
fetchRealTrends('all');
setInterval(function(){fetchRealTrends('all');},15*60*1000);
// Safe modal init
var m=document.getElementById('srchAnalyzeModal');
if(m) m.addEventListener('click',function(e){if(e.target===this)closeSrchModal();});
});
// -- EXPORT --
function exportCSV(){if(!LIVE.length){toast('No data');return;}var rows=[['Rank','Name','Category','Growth%','Source']];LIVE.slice(0,50).forEach(function(t,i){rows.push([i+1,t.name||t.nm||'',t.cat||'',t.pct||0,t.source||'']);});var csv=rows.map(function(r){return r.map(function(v){return'"'+String(v).replace(/"/g,'""')+'"';}).join(',');}).join('\n');var a=document.createElement('a');a.href='data:text/csv;charset=utf-8,'+encodeURIComponent(csv);a.download='trendradar.csv';a.click();toast('Exported!');}
function exportPDF() {
if (!LIVE.length) { toast('No data'); return; }
var trs = LIVE.slice(0,25).map(function(t,i) {
return '
'+(i+1)+'
'+(t.name||t.nm||'')+'
'+(t.cat||'')+'
+'+(t.pct||0)+'%
';
}).join('');
var w = window.open('','_blank');
if (!w) { toast('Allow popups'); return; }
w.document.write('TR-068505 TrendRadar
1777130898
TrendRadar.ai
#
Trend
Category
Growth
'+trs+'
');
w.document.close();
setTimeout(function(){ w.print(); }, 300);
toast('PDF ready!');
}
function exportWLCSV(){if(!WL.length){toast('Watchlist empty');return;}var csv='Name,Category,Growth\n'+WL.map(function(w){var t=LIVE.find(function(x){return String(x.id)===String(w.id);})||{};return'"'+w.name+'","'+(t.cat||'')+'",+'+(t.pct||0)+'%';}).join('\n');var a=document.createElement('a');a.href='data:text/csv;charset=utf-8,'+encodeURIComponent(csv);a.download='watchlist.csv';a.click();}
function exportWLPDF(){
if(!WL.length){toast('Empty');return;}
var rows=WL.map(function(w,i){var t=LIVE.find(function(x){return String(x.id)===String(w.id);})||{pct:0};return'
'+(i+1)+'
'+w.name+'
+'+(t.pct||0)+'%
';}).join('');
var w2=window.open('','_blank');if(!w2)return;
w2.document.write('
1777130898
My Watchlist
#
Trend
Growth
'+rows+'
');
w2.document.close();setTimeout(function(){w2.print();},300);
}
// -- AI ANALYSIS --
function analyzeTrend(t){
if(!t){toast('Select a trend first');return;}
var box=document.getElementById('aiResult');
var btn=document.getElementById('dashAnalyzeBtn');
if(!box)return;
var nm=t.name||t.nm||'Unknown',cat=t.cat||'general',pct=parseInt(t.pct||0),src=t.source||'TrendRadar';
var cm={tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'};
var col=cm[cat]||'var(--red)';
if(btn){btn.textContent='⏳ Analyzing...';btn.disabled=true;}
box.innerHTML='
🤖 Analyzing...
';
fetch(API+'/api/ai/analyze',{
method:'POST',
headers:{'Content-Type':'application/json','Authorization':'Bearer '+(TOKEN||'')},
body:JSON.stringify({trend:nm,category:cat,growth:pct,source:src})
}).then(function(r){return r.json();})
.then(function(d){
var text=d.analysis||d.result||d.content||d.text||'';
if(!text)throw new Error('empty');
if(btn){btn.textContent='✅ Done';btn.style.background='var(--green)';btn.style.color='#000';}
box.innerHTML=formatDashAnalysis(text,col);
setTimeout(function(){if(btn){btn.textContent='🤖 Analyze';btn.disabled=false;btn.style.background='var(--red)';btn.style.color='#fff';}},3000);
}).catch(function(){
var fb=buildFallbackAnalysis(nm,cat,pct,src);
if(btn){btn.textContent='✅ Done';btn.style.background='var(--green)';btn.style.color='#000';}
box.innerHTML=formatDashAnalysis(fb,col);
setTimeout(function(){if(btn){btn.textContent='🤖 Analyze';btn.disabled=false;btn.style.background='var(--red)';btn.style.color='#fff';}},3000);
});
}
function formatDashAnalysis(text,color){
if(!text)return '
No analysis.
';
color=color||'var(--red)';
var html=text
.replace(/&/g,'&').replace(//g,'>')
.replace(/\*\*(.*?)\*\*/g,'$1')
.replace(/## (.*?)(?:\n|$)/g,'
$1
')
.replace(/[•▸] (.*?)(?:\n|$)/g,'
▸$1
')
.replace(/\n/g,' ');
return '
'+html+'
';
}
function renderAnalysis(box,a,nm,pct){
var score=a.opportunityScore||0,scoreCol=score>=80?'var(--green)':score>=60?'var(--gold)':'var(--red)';
var html='
';
}
// -- WATCHLIST --
function toggleWL(id,name){
var exists=WL.findIndex(function(w){return String(w.id)===String(id);});
if(exists>=0){WL.splice(exists,1);toast('Removed');if(TOKEN)fetch(API+'/api/watchlist/'+id,{method:'DELETE',headers:{'Authorization':'Bearer '+TOKEN}}).catch(function(){});}
else{var t=LIVE.find(function(x){return String(x.id)===String(id);});WL.unshift({id:String(id),name:name||'Unknown',addedAt:new Date().toISOString(),cat:t?t.cat:'',pct:t?t.pct:0,icon:t?t.icon:'📊'});toast('Added to watchlist!');if(TOKEN)fetch(API+'/api/watchlist',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},body:JSON.stringify({trend_id:String(id),trend_name:name})}).catch(function(){});}
localStorage.setItem('tr_wl',JSON.stringify(WL));renderWLPreview();renderWatchlist();
}
function setWLView(view,el){WL_VIEW=view;document.querySelectorAll('#pg-wtch .btn').forEach(function(b){b.classList.remove('btn-red');b.classList.add('btn-outline');});if(el){el.classList.remove('btn-outline');el.classList.add('btn-red');}renderWatchlist();}
function filterWL(cat,el){WL_FILTER=cat;document.querySelectorAll('#wlFilters .ftab').forEach(function(b){b.classList.remove('on');});if(el)el.classList.add('on');renderWatchlist();}
function renderWatchlist(){
var box=document.getElementById('watchlistGrid');if(!box)return;
if(!WL.length){box.style.display='grid';box.style.gridTemplateColumns='repeat(auto-fill,minmax(240px,1fr))';box.innerHTML='
No trends saved. Click ☆ on any trend to add.
';return;}
var items=WL.filter(function(w){if(WL_FILTER==='all')return true;var t=LIVE.find(function(x){return String(x.id)===String(w.id);});if(WL_FILTER==='hot')return t&&(t.pct||0)>100;return t&&t.cat===WL_FILTER;});
box.innerHTML='';box.style.display='grid';box.style.gridTemplateColumns='repeat(auto-fill,minmax(240px,1fr))';
items.forEach(function(w){
var t=LIVE.find(function(x){return String(x.id)===String(w.id);})||{name:w.name,pct:0,cat:'',icon:'📊'};
var col=t.pct>200?'var(--red)':t.pct>100?'var(--gold)':'var(--green)',opp=Math.min(100,Math.round((t.pct||0)/3));
var card=document.createElement('div');card.className='card';
card.innerHTML='
'+(t.icon||'📊')+'
'+(t.name||w.name)+'
'+(t.cat||'')+'
+'+(t.pct||0)+'%
'+drawSparkline(genSparkData(t),col,70,28)+'
';
var wid=String(w.id),wname=w.name;card.querySelector('.wl-rem').addEventListener('click',function(){toggleWL(wid,wname);});
box.appendChild(card);
});
}
function renderWLPreview(){
var box=document.getElementById('wlPreview');if(!box)return;
if(!WL.length){box.innerHTML='
No trends saved
';return;}
box.innerHTML='';
WL.slice(0,4).forEach(function(w){
var t=LIVE.find(function(x){return String(x.id)===String(w.id);})||{},nm=(t.name||t.nm)||w.name||'Unknown',pct=t.pct||0;
var col=pct>200?'var(--red)':pct>100?'var(--gold)':'var(--green)';
var row=document.createElement('div');row.style.cssText='display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid var(--border)';
row.innerHTML=''+(t.icon||'📊')+''+nm.substring(0,30)+'+'+pct+'%';
box.appendChild(row);
});
}
// -- ALERTS --
function renderAlerts(){renderAlertsFeed();}
function renderAlertsFeed(){
var box=document.getElementById('alertsFeed'),cnt=document.getElementById('alrtCount');
if(cnt)cnt.textContent=ALERTS.length+' active';if(!box)return;box.innerHTML='';
if(!ALERTS.length){box.innerHTML='
No alerts yet.
';return;}
ALERTS.forEach(function(a,i){
var icons={spike:'🚀',opportunity:'💰',news:'📰',drop:'📉'};
var card=document.createElement('div');card.className='card';card.style.cssText='display:flex;align-items:center;gap:12px';
card.innerHTML='
'+(icons[a.type]||'🔔')+'
'+a.keyword+'
'+a.type+' · '+a.threshold+'% · '+a.date+'
';
card.querySelector('input').addEventListener('change',function(e){ALERTS[i].active=e.target.checked;localStorage.setItem('tr_alerts',JSON.stringify(ALERTS));});
card.querySelector('.del-alert').addEventListener('click',function(){ALERTS.splice(i,1);localStorage.setItem('tr_alerts',JSON.stringify(ALERTS));renderAlertsFeed();toast('Deleted');});
box.appendChild(card);
});
var hist=document.getElementById('alertHistory');if(!hist)return;hist.innerHTML='';
LIVE.slice(0,3).forEach(function(t){var row=document.createElement('div');row.className='card';row.style.cssText='display:flex;align-items:center;gap:10px;opacity:.7';row.innerHTML='
'+(t.name||t.nm||'')+' hit +'+(t.pct||0)+'%
'+Math.floor(Math.random()*60+1)+' min ago';hist.appendChild(row);});
}
function addAlert(){var kw=(document.getElementById('alertKw')||{}).value||'',tp=(document.getElementById('alertType')||{}).value||'spike',th=parseInt((document.getElementById('alertThresh')||{}).value||50);if(!kw){toast('Enter keyword');return;}ALERTS.unshift({keyword:kw,type:tp,threshold:th,date:new Date().toLocaleDateString(),active:true});localStorage.setItem('tr_alerts',JSON.stringify(ALERTS));if(document.getElementById('alertKw'))document.getElementById('alertKw').value='';renderAlertsFeed();toast('Alert created!');}
// -- PROFILE --
function initProfile(){
if(!USER){
var profBox = document.getElementById('pg-prof');
if(profBox){
profBox.innerHTML = '';
var wrap = document.createElement('div');
wrap.className = 'sec-sm';
wrap.style.cssText = 'text-align:center;padding:60px 20px';
wrap.innerHTML = '
👤
Sign In Required
Create an account to access your profile
';
var btnLogin = document.createElement('button');
btnLogin.className = 'btn btn-red';
btnLogin.style.marginRight = '8px';
btnLogin.textContent = 'Sign In';
btnLogin.addEventListener('click', function(){ openAuth('login'); });
var btnReg = document.createElement('button');
btnReg.className = 'btn btn-outline';
btnReg.textContent = 'Register';
btnReg.addEventListener('click', function(){ openAuth('register'); });
wrap.appendChild(btnLogin);
wrap.appendChild(btnReg);
profBox.appendChild(wrap);
}
return;
}
var av=document.getElementById('profAv'),nm=document.getElementById('profName'),em=document.getElementById('profEmail'),pl=document.getElementById('profPlan');
var wl=document.getElementById('profWL'),al=document.getElementById('profAlerts');
if(av)av.textContent=(USER.name||USER.email||'?')[0].toUpperCase();
if(nm)nm.textContent=USER.name||USER.email.split('@')[0];
if(em)em.textContent=USER.email||'';
if(pl){pl.textContent=(USER.plan||'free').toUpperCase();pl.style.color=USER.plan==='pro'?'var(--cyan)':USER.plan==='starter'?'var(--gold)':'var(--red)';}
if(wl)wl.textContent=WL.length;if(al)al.textContent=ALERTS.length;
fetch(API+'/api/auth/me',{headers:{'Authorization':'Bearer '+TOKEN}}).then(function(r){return r.json();}).then(function(d){
if(!d.user)return;var u=d.user,limits={free:5,starter:50,pro:-1},limit=limits[u.plan||'free']||5,used=u.daily_analyses||0;
var usedEl=document.getElementById('profUsed'),barEl=document.getElementById('profUsageBar'),sinceEl=document.getElementById('profSince');
if(usedEl)usedEl.textContent=limit===-1?used+' / Unlimited':used+'/'+limit;
if(barEl)barEl.style.width=Math.min(100,limit===-1?20:Math.round((used/limit)*100))+'%';
if(sinceEl&&u.created_at)sinceEl.textContent=new Date(u.created_at).toLocaleDateString();
}).catch(function(){});
}
function manageSubscription(){if(!USER){openAuth('login');return;}toast('Loading...');fetch(API+'/api/stripe/portal',{headers:{'Authorization':'Bearer '+TOKEN}}).then(function(r){return r.json();}).then(function(d){if(d.url)window.location.href=d.url;else toast('No active subscription');}).catch(function(){toast('Error');});}
function exportMyData(){var d={profile:USER,watchlist:WL,alerts:ALERTS,date:new Date().toISOString()};var a=document.createElement('a');a.href='data:application/json;charset=utf-8,'+encodeURIComponent(JSON.stringify(d,null,2));a.download='trendradar-data.json';a.click();toast('Exported!');}
// -- ONBOARDING --
function showOnboard(){var el=document.getElementById('onboardModal');if(el)el.style.display='grid';}
function closeOnboard(){var el=document.getElementById('onboardModal');if(el)el.style.display='none';localStorage.setItem('tr_onboarded','1');}
// -- BLOG --
var BLOG_POSTS=[
{id:'viral-trends-2026',cat:'guide',title:'How to Find Viral Trends Before They Explode in 2026',date:'Jan 15, 2026',read:'8 min',icon:'📈',summary:'The exact system used by top creators to spot emerging trends 2-4 weeks early.',content:'
The 3-Week Window
Trends start on Reddit, move to TikTok, then YouTube, then Google. By Google you are too late.
Step 1: Monitor Reddit and HN daily for acceleration signals.
Step 2: Velocity beats absolute value — +50% this week vs +10% last week.
Step 3: Validate in 30 days with affiliate, info products, or content.
'},
{id:'tiktok-shop-2026',cat:'report',title:'Top TikTok Shop Trending Products Q1 2026',date:'Jan 10, 2026',read:'5 min',icon:'📱',summary:'Hottest TikTok Shop categories and how to capitalize.',content:'
TikTok Shop Q1 2026
Wellness Gadgets +340% — Red light therapy, saunas, posture correctors.
AI Beauty Tools +280% — Smart skincare with apps.
Digital Products +195% — Templates, planners. Zero COGS.
'},
{id:'ai-tools-847b',cat:'report',title:'AI Tools: The $847B Opportunity in 2026',date:'Dec 28, 2025',read:'7 min',icon:'🤖',summary:'How to monetize the AI tools trend right now.',content:'
1. Affiliate: 20-40% recurring. $50-200/month per referral.
2. Directories: "AI tools for lawyers" — untouched niche.
3. Prompt Packs: $27-97 each.
'},
{id:'case-study-8400',cat:'case',title:'Case Study: $8,400 from One Early Trend',date:'Dec 20, 2025',read:'4 min',icon:'💰',summary:'One early trend = $8,400 in 6 weeks.',content:'
'},
{id:'amazon-early',cat:'guide',title:'Find Amazon Best Sellers Before They Trend',date:'Dec 15, 2025',read:'6 min',icon:'📦',summary:'Cross-reference signals to spot winners early.',content:'
'}
];
function initBlog(){renderBlogGrid(BLOG_POSTS);}
function filterBlog(cat,el){document.querySelectorAll('#blogCats .ftab').forEach(function(b){b.classList.remove('on');});if(el)el.classList.add('on');renderBlogGrid(cat==='all'?BLOG_POSTS:BLOG_POSTS.filter(function(p){return p.cat===cat;}));}
function renderBlogGrid(posts){
var box=document.getElementById('blogGrid');if(!box)return;
box.innerHTML='';
posts.forEach(function(p){
var card=document.createElement('div');card.className='card';card.style.cursor='pointer';
card.addEventListener('click',function(){openPost(p.id);});
card.innerHTML='
'+p.icon+'
'+p.cat+'
'+p.title+'
'+p.summary+'
📅 '+p.date+'⏱ '+p.read+'
';
box.appendChild(card);
});
}
function openPost(id){
var post=BLOG_POSTS.find(function(p){return p.id===id;});if(!post)return;
var modal=document.getElementById('postModal'),contentDiv=document.getElementById('postContent');
if(!modal||!contentDiv)return;
contentDiv.innerHTML='';
var catSpan=document.createElement('span');catSpan.style.cssText='font-size:.68rem;font-weight:700;color:var(--red);text-transform:uppercase';catSpan.textContent=post.cat;
var h1=document.createElement('h1');h1.style.cssText='font-size:1.3rem;font-weight:800;margin:10px 0;line-height:1.3';h1.textContent=post.title;
var meta=document.createElement('div');meta.style.cssText='display:flex;gap:12px;color:var(--muted);font-size:.74rem;margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid var(--border)';meta.innerHTML='📅 '+post.date+'⏱ '+post.read+'';
var body=document.createElement('div');body.style.cssText='font-size:.88rem;line-height:1.9;color:var(--txt)';body.innerHTML=post.content;
var cta=document.createElement('div');cta.style.cssText='margin-top:28px;padding-top:20px;border-top:1px solid var(--border);text-align:center';
var ctaBtn=document.createElement('button');ctaBtn.className='btn btn-red';ctaBtn.textContent='View Live Trends';ctaBtn.addEventListener('click',function(){closePost();G('dash');});
cta.appendChild(ctaBtn);
contentDiv.appendChild(catSpan);contentDiv.appendChild(h1);contentDiv.appendChild(meta);contentDiv.appendChild(body);contentDiv.appendChild(cta);
modal.style.display='block';
}
function closePost(){var modal=document.getElementById('postModal');if(modal)modal.style.display='none';}
// -- COMPARE TRENDS --
function toggleCompareMode(){
COMPARE_MODE=!COMPARE_MODE;
var btn=document.getElementById('compareBtn'),panel=document.getElementById('comparePanel');
if(COMPARE_MODE){if(btn){btn.textContent='⚖️ ON';btn.className='btn btn-red btn-xs';}if(panel)panel.style.display='block';toast('Compare ON — click trends');}
else{if(btn){btn.textContent='⚖️ Compare';btn.className='btn btn-outline btn-xs';}if(panel)panel.style.display='none';clearCompare();}
}
function addToCompare(t){if(!t)return;if(COMPARE_LIST.find(function(x){return String(x.id)===String(t.id);})){toast('Already added');return;}if(COMPARE_LIST.length>=4){toast('Max 4');return;}COMPARE_LIST.push(t);updateCompareChips();toast('Added: '+(t.name||t.nm||''));if(COMPARE_LIST.length>=2)runCompare();}
function removeFromCompare(id){COMPARE_LIST=COMPARE_LIST.filter(function(t){return String(t.id)!==String(id);});updateCompareChips();if(COMPARE_LIST.length>=2)runCompare();else{var cc=document.getElementById('compareChart');if(cc)cc.style.display='none';}}
function updateCompareChips(){
var box=document.getElementById('compareChips'),cnt=document.getElementById('compareCount'),hint=document.getElementById('compareHint');
if(!box)return;if(cnt)cnt.textContent=COMPARE_LIST.length+'/4';if(hint)hint.style.display=COMPARE_LIST.length?'none':'inline';
box.querySelectorAll('.compare-chip').forEach(function(ch){ch.remove();});
COMPARE_LIST.forEach(function(t,i){
var col=COMPARE_COLORS[i],chip=document.createElement('div');chip.className='compare-chip';
chip.style.cssText='display:inline-flex;align-items:center;gap:6px;background:var(--s2);border:1.5px solid '+col+';border-radius:20px;padding:4px 10px;font-size:.74rem;font-weight:600';
chip.innerHTML='●'+(t.name||t.nm||'').substring(0,20)+'+'+(t.pct||0)+'%';
var tid=String(t.id);chip.querySelector('button').addEventListener('click',function(){removeFromCompare(tid);});
box.appendChild(chip);
});
}
function clearCompare(){COMPARE_LIST=[];updateCompareChips();var cc=document.getElementById('compareChart');if(cc)cc.style.display='none';}
function runCompare(){
if(COMPARE_LIST.length<2){toast('Select 2+ trends');return;}
var chart=document.getElementById('compareChart'),svg=document.getElementById('compareChartSVG'),legend=document.getElementById('compareLegend'),stats=document.getElementById('compareStats');
if(!chart||!svg)return;chart.style.display='block';
var DAYS=30,W=Math.min(svg.parentElement?svg.parentElement.clientWidth:500,800),H=180;
svg.setAttribute('width',W);svg.setAttribute('height',H);
var allData=COMPARE_LIST.map(function(t){var base=t.pct||50,d=[];for(var i=DAYS-1;i>=0;i--)d.push(Math.max(5,base*(0.2+0.8*(DAYS-i)/DAYS)+(Math.random()*25-12)));d[DAYS-1]=base;return d;});
var allVals=[].concat.apply([],allData),maxV=Math.max.apply(null,allVals),minV=Math.min.apply(null,allVals),range=maxV-minV||1;
var xS=function(i){return 12+i*(W-24)/(DAYS-1);},yS=function(v){return H-12-((v-minV)/range)*(H-24);};
var svgContent='';
for(var g=0;g<=4;g++){var gy=12+g*(H-24)/4;svgContent+='';}
COMPARE_LIST.forEach(function(t,i){var col=COMPARE_COLORS[i],data=allData[i];var lp=data.map(function(v,j){return(j===0?'M':'L')+xS(j).toFixed(1)+','+yS(v).toFixed(1);}).join(' ');svgContent+='';});
svg.innerHTML=svgContent;
if(legend)legend.innerHTML=COMPARE_LIST.map(function(t,i){return'
' +
'+' + (t.pct || 0) + '%';
box.appendChild(row);
});
}
// -- SEARCH TREND ANALYSIS MODAL --
var _srchCurrentTrend = null;
function openSrchTrendModal(t) {
if (!t) return;
_srchCurrentTrend = t;
var cm = {tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'};
var catIcons = {tech:'⚡',social:'📱',finance:'💰',news:'📰',commerce:'🛍️'};
var col = cm[t.cat] || 'var(--red)';
// Show panel
var empty = document.getElementById('srchAnEmpty');
var content = document.getElementById('srchAnContent');
if (empty) empty.style.display = 'none';
if (content) content.style.display = 'block';
// Fill data
var g = function(id){ return document.getElementById(id); };
if (g('srchAnIcon')) g('srchAnIcon').textContent = t.icon || catIcons[t.cat] || '📊';
if (g('srchAnTitle')) g('srchAnTitle').textContent = (t.name||t.nm||'').substring(0,60);
if (g('srchAnMeta')) g('srchAnMeta').innerHTML = (t.source||t.cat||'') + ' · ' + (t.real ? '🟢 Live' : '📋 Curated');
if (g('srchAnPct')) { g('srchAnPct').textContent = '+'+Math.abs(t.pct||0)+'%'; g('srchAnPct').style.color = col; }
if (g('srchAnSrc')) { g('srchAnSrc').textContent = (t.source||'TrendRadar').substring(0,20); g('srchAnSrc').style.color = col; }
if (g('srchAnResult')) g('srchAnResult').innerHTML = '
Click Analyze below
';
if (g('srchAnBtn')) { g('srchAnBtn').textContent = '🤖 Analyze Trend'; g('srchAnBtn').disabled = false; g('srchAnBtn').style.background = 'var(--red)'; g('srchAnBtn').style.color = '#fff'; }
// Mobile scroll
if (window.innerWidth < 640) {
var panel = document.getElementById('srchAnContent');
if (panel) setTimeout(function(){ panel.scrollIntoView({behavior:'smooth'}); }, 100);
}
}
function closeSrchModal() {
var empty = document.getElementById('srchAnEmpty');
var content = document.getElementById('srchAnContent');
if (empty) empty.style.display = 'flex';
if (content) content.style.display = 'none';
_srchCurrentTrend = null;
}
function closeSrchModal() {
var empty=document.getElementById('srchAnEmpty');
var content=document.getElementById('srchAnContent');
if(empty) empty.style.display='flex';
if(content) content.style.display='none';
_srchCurrentTrend=null;
}
function closeSrchModal() {
var empty = document.getElementById('srchAnalysisEmpty');
var content = document.getElementById('srchAnalysisContent');
if(empty) empty.style.display = 'block';
if(content) content.style.display = 'none';
_srchCurrentTrend = null;
}
function closeSrchModal() {
document.getElementById('srchAnalyzeModal').style.display = 'none';
document.body.style.overflow = '';
}
function runSrchAnalysis() {
if (!_srchCurrentTrend) { toast('Select a trend first'); return; }
var t = _srchCurrentTrend;
var nm = t.name||t.nm||'Unknown', pct = t.pct||0, cat = t.cat||'general', src = t.source||'TrendRadar';
var cm = {tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'};
var col = cm[cat] || 'var(--red)';
var btn = document.getElementById('srchAnBtn');
var box = document.getElementById('srchAnResult');
if(!btn||!box) return;
btn.textContent='⏳ Analyzing...'; btn.disabled=true;
box.innerHTML='
🤖 AI analyzing...
';
fetch(API+'/api/ai/analyze',{
method:'POST',
headers:{'Content-Type':'application/json','Authorization':'Bearer '+(TOKEN||'')},
body:JSON.stringify({trend:nm,category:cat,growth:pct,source:src})
}).then(function(r){return r.json();})
.then(function(d){
var text=d.analysis||d.result||d.content||d.text||'';
if(!text) throw new Error('empty');
btn.textContent='✅ Done'; btn.style.background='var(--green)'; btn.style.color='#000';
box.innerHTML=formatSrchAnalysis(text,cat,pct,col);
setTimeout(function(){btn.textContent='🤖 Analyze Trend';btn.disabled=false;btn.style.background='var(--red)';btn.style.color='#fff';},3000);
}).catch(function(){
var fb=buildFallbackAnalysis(nm,cat,pct,src);
btn.textContent='✅ Done'; btn.style.background='var(--green)'; btn.style.color='#000';
box.innerHTML=formatSrchAnalysis(fb,cat,pct,col);
setTimeout(function(){btn.textContent='🤖 Analyze Trend';btn.disabled=false;btn.style.background='var(--red)';btn.style.color='#fff';},3000);
});
}
function buildFallbackAnalysis(name, cat, pct, src) {
var scores = {
opportunity: pct > 200 ? 95 : pct > 100 ? 78 : 60,
momentum: pct > 300 ? 98 : pct > 150 ? 82 : 65,
timing: pct > 200 ? 90 : pct > 100 ? 72 : 55
};
var urgency = pct > 200 ? '🔴 ACT NOW — Peak momentum' : pct > 100 ? '🟡 HIGH — Act this week' : '🟢 MODERATE — Plan ahead';
var audience = {
tech:'Developers, CTOs, tech startups, SaaS founders',
social:'Content creators, influencers, brand managers',
finance:'Investors, traders, financial advisors, CFOs',
commerce:'E-commerce sellers, Amazon FBA, dropshippers',
news:'Journalists, analysts, policymakers, researchers'
};
var actions = {
tech:['Create technical content around this topic','Build a tool or integration','Monitor GitHub for related projects','Join developer communities discussing this'],
social:['Post content NOW while trend is hot','Use trending hashtags and keywords','Collaborate with influencers in this niche','Run targeted social ads'],
finance:['Review portfolio exposure to this sector','Set price alerts and monitor closely','Research related ETFs and stocks','Consult financial advisor about positioning'],
commerce:['Source products related to this trend','Optimize Amazon/Etsy listings for keywords','Launch ads targeting this interest','Stock up inventory before peak'],
news:['Monitor developing stories closely','Create analysis or opinion content','Reach out to primary sources','Set up Google Alerts for updates']
};
var acts = (actions[cat] || actions.news);
var lines = [
'**Trend:** ' + name + ' (+' + pct + '%)',
'**Source:** ' + src, '',
'## Opportunity Score',
'📊 **' + scores.opportunity + '/100** — ' + (scores.opportunity > 80 ? 'Excellent opportunity' : scores.opportunity > 65 ? 'Good opportunity' : 'Moderate opportunity'), '',
'## Momentum Analysis',
'Growth rate of **+' + pct + '%** indicates ' + (pct > 200 ? 'viral breakout — exploding across platforms' : pct > 100 ? 'strong acceleration — momentum building fast' : 'steady growth — consistent upward trend'), '',
'## Target Audience',
(audience[cat] || audience.news), '',
'## Action Plan',
acts.map(function(a){ return '• ' + a; }).join('\n'), '',
'## Timing',
urgency, '',
'## Risk Factors',
'• Trend saturation in 2-4 weeks if viral',
'• Competition increases as visibility grows',
'• Monitor for regulatory changes in ' + cat + ' sector'
];
return lines.join('\n');
function formatSrchAnalysis(text, cat, pct, color) {
if (!text) return '';
var html = text
.replace(/\*\*(.*?)\*\*/g, '$1')
.replace(/## (.*?)\n/g, '
$1
')
.replace(/• (.*?)\n/g, '
▸$1
')
.replace(/\n/g, ' ');
return '
' + html + '
';
}
function addSrchToWL() {
if (!_srchCurrentTrend) return;
if (!USER) { toast('Login to save to Watchlist'); return; }
var t = _srchCurrentTrend;
var id = String(t.id || Date.now());
if (!WL.find(function(x){ return String(x.id) === id; })) {
WL.push(t);
localStorage.setItem('tr_wl', JSON.stringify(WL));
toast('Added to Watchlist ⭐');
} else {
toast('Already in Watchlist');
}
}
function setAlertSrch() {
if (!_srchCurrentTrend) return;
if (!USER) { toast('Login to set alerts'); return; }
var nm = _srchCurrentTrend.name || _srchCurrentTrend.nm || '';
ALERTS.push({keyword: nm, created: Date.now()});
localStorage.setItem('tr_alerts', JSON.stringify(ALERTS));
toast('Alert set for: ' + nm.substring(0, 30) + ' 🔔');
}
function shareTrend() {
if (!_srchCurrentTrend) return;
var nm = _srchCurrentTrend.name || _srchCurrentTrend.nm || '';
var text = 'Trending: ' + nm + ' (+' + (_srchCurrentTrend.pct||0) + '%) via TrendRadar.ai';
if (navigator.share) {
navigator.share({title: nm, text: text, url: 'https://mytrendradar.pages.dev'});
} else if (navigator.clipboard) {
navigator.clipboard.writeText(text);
toast('Copied to clipboard 🔗');
}
}
// Close modal on backdrop click
var _srchModal = document.getElementById('srchAnalyzeModal');
if (_srchModal) {
_srchModal.addEventListener('click', function(e) {
if (e.target === this) closeSrchModal();
});
}
// -- FAQ --
function toggleFaq(el){
var body=el.querySelector('.faq-body'),arrow=el.querySelector('.faq-arrow'),isOpen=body.style.display!=='none';
document.querySelectorAll('.faq-item .faq-body').forEach(function(b){b.style.display='none';});
document.querySelectorAll('.faq-item .faq-arrow').forEach(function(a){a.textContent='+';});
if(!isOpen){body.style.display='block';arrow.textContent='−';}
}
}
// ── PDF EXPORT ──
function downloadAnalysisPDF(nm, txt, gr, src, cat) {
var color = {tech:'#00d4ff',social:'#ff2347',finance:'#00e5a0',news:'#8b5cf6',commerce:'#f5c842'}[cat] || '#ff2347';
var d = new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'});
var safe = (nm||'Trend').replace(/[^a-z0-9 ]/gi,'_').substring(0,30);
var body = '
';
html += '';
var blob = new Blob([html],{type:'text/html'});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href=url; a.download='TrendRadar-'+safe.replace(/ /g,'_')+'.html';
document.body.appendChild(a); a.click(); document.body.removeChild(a);
URL.revokeObjectURL(url);
toast('Exported! Open file and Print to save as PDF');
}
function downloadSrchPDF() {
if(!_srchCurrentTrend) return;
var t = _srchCurrentTrend;
var box = document.getElementById('srchAnResult');
var text = box ? (box.innerText||box.textContent||'') : '';
downloadAnalysisPDF(t.name||t.nm, text, t.pct, t.source, t.cat);
}
function downloadDashPDF() {
if(!CHART_TREND){toast('Select and analyze a trend first');return;}
var t = CHART_TREND;
var box = document.getElementById('aiResult');
var text = box ? (box.innerText||box.textContent||'').trim() : '';
if(!text||text==='Select a trend →'){
toast('Analyze the trend first, then export PDF');
return;
}
downloadAnalysisPDF(t.name||t.nm, text, t.pct, t.source, t.cat);
}
function downloadDashPDF() {
if(!CHART_TREND) { toast('Select a trend first'); return; }
var t = CHART_TREND;
var box = document.getElementById('aiResult');
var text = box ? (box.innerText||box.textContent||'') : '';
downloadAnalysisPDF(t.name||t.nm, text, t.pct, t.source, t.cat);
}
// -- PWA --
if('serviceWorker' in navigator)window.addEventListener('load',function(){navigator.serviceWorker.register('/sw.js').catch(function(){});});