// === VNEWS Frontend v2 - Full Functions === // Added: World Cup highlight tab + Friendly highlights on homepage + 🔥 HOT feed // Updated: HOT feed chỉ hiển thị hashtag chips, click vào hashtag thì hiện tin // Fix: safeJson parsing to handle non-JSON error responses gracefully // Fix: timeout cho rewrite calls, không treo vô hạn // === SAFE JSON PARSE === async function safeJson(resp){ try{ const text=await resp.text(); try{return JSON.parse(text);} catch(e){ // Server returned non-JSON (e.g., HTML error page) console.warn('Non-JSON response:', text.slice(0,200)); return {error: 'Server error', _status: resp.status, _raw: text.slice(0,200)}; } }catch(e){ return {error: 'Network error', _msg: e.message}; } } // === FETCH WITH TIMEOUT === function fetchWithTimeout(url, opts, timeoutMs){ return new Promise((resolve, reject)=>{ const ctrl = new AbortController(); const timer = setTimeout(() => { ctrl.abort(); reject(new Error('timeout')); }, timeoutMs); fetch(url, { ...opts, signal: ctrl.signal }).then(r => { clearTimeout(timer); resolve(r); }).catch(e => { clearTimeout(timer); reject(e); }); }); } // === LOAD HOME === async function loadHome(){ const[featured,sh,wall,hlLeagues,ai,wcData]=await Promise.all([ fetch('/api/livescore/featured').then(r=>safeJson(r)).catch(()=>null), fetch('/api/shorts').then(r=>safeJson(r)).catch(()=>[]), fetch('/api/ai_wall').then(r=>safeJson(r)).catch(()=>({posts:[]})), fetch('/api/highlights/leagues').then(r=>safeJson(r)).catch(()=>({})), fetch('/api/genk_ai').then(r=>safeJson(r)).catch(()=>[]), fetch('/api/wc2026').then(r=>safeJson(r)).catch(()=>null) ]); _hlLeagueData=hlLeagues; _wc2026Data=wcData; _shortsData=interleaveShorts(sh||[]); let h=''; if(featured&&featured.home){const sc=featured.status==='live'?'':'upcoming';const st=featured.status==='live'?`🔴 ${featured.minute||'LIVE'}`:`⏰ ${featured.time}`;h+=``;} h+=`
🤖 AI viết bài
`; h+='
'; h+='
'; h+=`

⚽ Livescore

📅 Hôm nay🔴 Live⏰ Sắp tới✅ Kết quả🏆 NHA🏆 La Liga
Đang tải...
`; h+=`

🏆 World Cup 2026

● LIVE
📰 Tin tức📅 Lịch thi đấu🏆 BXH🎬 Highlight📊 Thống kê
Đang tải World Cup 2026...
`; const wallPosts=(wall&&wall.posts)||[];const aiShorts=wallPosts.filter(p=>p.video); if(aiShorts.length){h+='
🎬 Short AI
';aiShorts.slice(0,20).forEach((p,i)=>{h+=`
${esc(p.title)}
`});h+='
';} if(_shortsData.length){h+='
📱 Shorts Dân trí & SKĐSMới nhất · xen kẽ
';_shortsData.slice(0,30).forEach((a,i)=>{const badge=a.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';h+=`
${a.img?``:''}
${badge} ${esc(a.title)}
`;});h+='
';} if(wallPosts.length){h+='
🧱 Tường AI
';wallPosts.slice(0,20).forEach((p,i)=>{h+=`
${p.img?``:''}
${esc(p.title)}
${esc(p.text)}
`});h+='
';} const HL_CONFIG={"world-cup":{name:"World Cup 2026",emoji:"🌍"},"premier-league":{name:"Premier League",emoji:"🏴"},"champions-league":{name:"Champions League",emoji:"⭐"},"la-liga":{name:"La Liga",emoji:"🇪🇸"},"serie-a":{name:"Serie A",emoji:"🇮🇹"},"bundesliga":{name:"Bundesliga",emoji:"🇩🇪"},"friendly":{name:"Giao hữu",emoji:"🤝"}}; for(const[key,cfg] of Object.entries(HL_CONFIG)){const vids=hlLeagues[key];if(!vids||!vids.length)continue;h+=`
${cfg.emoji} ${cfg.name}
`;vids.slice(0,8).forEach((a,i)=>{h+=`
${a.img?``:''}
${esc(a.title)}
`});h+='
';} if(ai&&ai.length){h+='
🤖 Ứng dụng AI
';ai.slice(0,12).forEach(a=>{h+=`
${a.img?``:''}
${esc(a.title)}
`});h+='
';} document.getElementById('view-home').innerHTML=h; loadLivescore('today');loadHotTopics();loadHotFeed(); if(_wc2026Data)switchWCTab('news'); } let _shortsData=[]; function interleaveShorts(shorts){const dt=shorts.filter(s=>s.channel==='baodantri7941');const sk=shorts.filter(s=>s.channel==='baosuckhoedoisongboyte');const result=[];let i=0,j=0;while(isafeJson(r)).catch(()=>({topics:[]})); _allHotTopics=j.topics||[]; const el=document.getElementById('hot-topics');if(!el)return; el.innerHTML=(_allHotTopics||[]).slice(0,18).map(t=>{ const topicText=t.topic||t.label.replace(/^#/,''); return``; }).join(''); if(_allHotTopics&&_allHotTopics[0]){ const firstTopic=_allHotTopics[0].topic||_allHotTopics[0].label.replace(/^#/,''); setTimeout(()=>searchTopic(firstTopic),800); } } function searchTopic(topic){ if(!topic){topic=document.getElementById('topic-input')?.value.trim();if(!topic){alert('Nhập chủ đề');return;}} document.getElementById('topic-input').value=''; _htTopic=topic;_htPage=0; // Chỉ tìm tin của hashtag được click, không tổng hợp showHashtagSources(topic, 0, ''); } async function showHashtagSources(topic, page, extraTopics){ const box=document.getElementById('hashtag-box');if(!box)return; let topicLabel=esc(topic); if(page===0)box.innerHTML=`

🔍 ${topicLabel}

Đang tìm nguồn tin...
`; try{ let url=`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${page}`; if(extraTopics) url+=`&extra_topics=${encodeURIComponent(extraTopics)}`; const r=await fetch(url);const j=await safeJson(r); if(j.error){box.innerHTML=`

🔍 ${esc(topic)}

Lỗi: ${esc(j.error)}
`;return;} const sources=j.sources||[]; if(!sources.length&&page===0){box.innerHTML=`

🔍 ${topicLabel}

Không tìm được bài viết liên quan
`;return;} let h=''; if(page===0){ h=`

🔍 ${topicLabel}

`; h+=`
${j.total} bài từ nhiều nguồn
`; h+=`
`; } sources.forEach((s,i)=>{const idx=page*8+i;h+=`
${esc(s.title)}
${esc(s.via||'')}
`;}); if(page===0){h+=`
`;if(j.has_more)h+=``;h+=`
`;box.innerHTML=h;}else{document.getElementById('ht-list')?.insertAdjacentHTML('beforeend',h);const btn=document.getElementById('ht-more');if(btn){if(!j.has_more)btn.remove();else{btn.disabled=false;btn.textContent='Tải thêm ▼';}}} sources.forEach((s,i)=>{const idx=page*8+i;if(!s.url)return;fetch('/api/article?url='+encodeURIComponent(s.url)).then(r=>safeJson(r)).then(d=>{if(d&&(d.og_image||d.img)){const el=document.getElementById('ht-img-'+idx);if(el)el.innerHTML=``;}}).catch(()=>{});}); }catch(e){box.innerHTML=`

🔍 ${esc(topic)}

Lỗi: ${esc(e.message)}
`;} } function loadMoreHashtag(){_htPage++;const btn=document.getElementById('ht-more');if(btn){btn.disabled=true;btn.textContent='Đang tải...';}showHashtagSources(_htTopic,_htPage,'');} async function rewriteHashtag(topic){ const btn=event?.target; if(btn){btn.disabled=true;btn.textContent='Đang xử lý...';} try{ // Timeout 60s cho rewrite const r=await fetchWithTimeout('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})},60000); const j=await safeJson(r); if(!r.ok||j.error)throw new Error(j.error||'Lỗi'); toast('✅ Đã đăng Tường AI!'); if(btn)btn.textContent='✅ Đã đăng!'; }catch(e){ if(e.message==='timeout'){toast('❌ Quá lâu, thử lại');} else{toast('❌ '+e.message);} if(btn){btn.disabled=false;btn.textContent='🤖 Rewrite AI';} } } // ===== 🔥 HOT FEED — chỉ hiển thị danh sách hashtag, click vào hashtag thì hiện tin ===== async function loadHotFeed(){ const box=document.getElementById('hot-feed');if(!box)return; box.innerHTML=`
🔥 HOT Đang tải hashtag...
Đang tải...
`; try{ const ht=await fetch('/api/hot_topics').then(r=>safeJson(r)).catch(()=>({topics:[]})); const allTopics=(ht.topics||[]).slice(0,10); if(!allTopics.length){box.innerHTML='';return;} const topicCount=allTopics.length; const headerLabel=topicCount>1?`🔥 HOT ${topicCount} hashtag trending nhất`:`🔥 HOT Tin hot nhất hôm nay`; const topicChipsHtml=allTopics.map(t=>{ const lbl=t.label||t.topic||''; const tp=t.topic||t.label.replace(/^#/,''); return`${esc(lbl)}`; }).join(''); let h=`
${headerLabel}
${topicChipsHtml}
`; h+=`
`;box.innerHTML=h; }catch(e){box.innerHTML='';} } async function loadLivescore(tab){document.querySelectorAll('.ls-tab').forEach(t=>t.classList.remove('active'));document.querySelector(`.ls-tab[data-tab="${tab}"]`)?.classList.add('active');const el=document.getElementById('ls-content');if(!el)return;el.innerHTML='
Đang tải...
';let ep='/api/livescore/'+tab;if(tab.startsWith('bxh_'))ep='/api/livescore/standings/'+tab.replace('bxh_','');try{const r=await fetch(ep);const d=await safeJson(r);el.innerHTML=d.html&&d.html.length>50?d.html:'
Không có dữ liệu
';bindMatchClicks(el);}catch(e){el.innerHTML='
Lỗi
';}} function bindMatchClicks(el){el.querySelectorAll('.match-detail').forEach(md=>{md.addEventListener('click',function(e){e.preventDefault();const a=this.querySelector('.status a');if(a){const m=(a.getAttribute('href')||'').match(/\/tran-dau\/(\d+)\//);if(m)openMatch(m[1])}})});el.querySelectorAll('a').forEach(a=>a.addEventListener('click',e=>e.preventDefault()))} function openMatch(id){if(!id)return;_currentEventId=id;document.getElementById('match-overlay').classList.add('active');document.body.style.overflow='hidden';loadMatchTab('comm')} function closeMatch(){document.getElementById('match-overlay').classList.remove('active');document.body.style.overflow=''} async function loadMatchTab(tab){document.querySelectorAll('.mo-tab').forEach(t=>t.classList.remove('active'));document.querySelectorAll('.mo-tab').forEach(t=>{if((tab==='comm'&&t.textContent==='Diễn biến')||(tab==='stats'&&t.textContent==='Thống kê'))t.classList.add('active')});const el=document.getElementById('mo-body');el.innerHTML='
Đang tải...
';try{const r=await fetch(tab==='stats'?`/api/match/${_currentEventId}/stats`:`/api/match/${_currentEventId}/commentaries`);const d=await safeJson(r);el.innerHTML=d.html||'
Không có dữ liệu
'}catch(e){el.innerHTML='
Lỗi
'}} async function doInteract(videoId,type){try{const r=await fetch('/api/v2/interact',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,type})});return await safeJson(r);}catch(e){return null;}} async function getInteractions(videoId){try{const r=await fetch('/api/v2/interactions?id='+encodeURIComponent(videoId));return await safeJson(r);}catch(e){return{views:0,likes:0,comments:0};}} async function getComments(videoId){try{const r=await fetch('/api/v2/comments?id='+encodeURIComponent(videoId));const j=await safeJson(r);return j.comments||[];}catch(e){return[];}} async function postComment(videoId,text){try{const r=await fetch('/api/v2/comment',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,text})});const j=await safeJson(r);return j.comments||[];}catch(e){return[];}} function buildTikTokSlide(opts){return`
${opts.vtag}
${opts.badge||''}

${esc(opts.title)}

${opts.extraBtn||''}
${opts.idx+1}/${opts.total}
Đang tải...
';const cmts=await getComments(videoId);renderInlineComments(panel,videoId,idx,cmts);} function renderInlineComments(panel,videoId,idx,cmts){let h='
💬 Bình luận
';if(cmts.length){cmts.slice(-30).forEach(c=>{h+=`
${c.time||''}${esc(c.text)}
`;});}else{h+='
Chưa có bình luận
';}h+=`
`;panel.innerHTML=h;const list=panel.querySelector('.inline-cmt-list');if(list)list.scrollTop=list.scrollHeight;} async function submitInlineCmt(videoId,idx){const inp=document.getElementById('cmt-input-'+idx);if(!inp)return;const text=inp.value.trim();if(!text)return;inp.value='';inp.disabled=true;const cmts=await postComment(videoId,text);inp.disabled=false;const panel=document.getElementById('cmt-inline-'+idx);if(panel)renderInlineComments(panel,videoId,idx,cmts);const cc=document.getElementById('cc-'+idx);if(cc)cc.textContent=fmtNum(cmts.length);} function initTikTokFeed(){const feed=document.getElementById('tiktok-feed');if(!feed)return;const slides=feed.querySelectorAll('.tiktok-slide');let cur=-1;function act(i){if(i===cur)return;slides.forEach((sl,idx)=>{const v=sl.querySelector('video');const fr=sl.querySelector('iframe');if(idx===i){if(v&&v.dataset.hls&&!v._hls&&typeof Hls!=='undefined'&&Hls.isSupported()){const hls=new Hls();hls.loadSource(v.dataset.hls);hls.attachMedia(v);hls.on(Hls.Events.MANIFEST_PARSED,()=>v.play().catch(()=>{}));v._hls=hls}else if(v)v.play().catch(()=>{});if(fr&&!fr.src&&fr.dataset.ytSrc)fr.src=fr.dataset.ytSrc;const vid=sl.dataset.vid;if(vid&&!sl._viewed){sl._viewed=true;doInteract(vid,'view').then(j=>{if(j){const vc=document.getElementById('vc-'+idx);if(vc)vc.textContent=fmtNum(j.views);}});}}else{if(v){v.pause();if(v._hls){v._hls.destroy();v._hls=null}}if(fr&&fr.src)fr.src=''}});cur=i}let sT;feed.addEventListener('scroll',()=>{clearTimeout(sT);sT=setTimeout(()=>{const rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2;let best=-1,bestD=1e9;slides.forEach((sl,i)=>{const d=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(d=0)act(best)},150)});setTimeout(()=>act(0),400);slides.forEach(sl=>{const v=sl.querySelector('video');if(v)v.addEventListener('click',e=>{e.preventDefault();v.paused?v.play().catch(()=>{}):v.pause()})});const ids=[...slides].map(sl=>sl.dataset.vid||'');loadCounters(ids);} async function openHighlightFeed(league,idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';let articles=(_hlLeagueData||{})[league]||[];if(!articles.length){try{const r=await fetch('/api/highlights/'+league);articles=await safeJson(r);}catch(e){articles=[]}}if(!articles.length){el.innerHTML='
Không có video
';return}const vids=[];const results=await Promise.all(articles.map(async(a,i)=>{try{const r=await fetch('/api/video_url?url='+encodeURIComponent(a.link));const v=await safeJson(r);if(v&&v.src)return{...a,...v,_idx:i}}catch(e){}return null}));results.forEach(r=>{if(r)vids.push(r)});vids.sort((a,b)=>a._idx-b._idx);if(!vids.length){el.innerHTML='
Không tìm thấy video
';return}let ti=vids.findIndex(v=>v._idx===idx);if(ti<0)ti=0;const ordered=ti>0?[...vids.slice(ti),...vids.slice(0,ti)]:vids;let h=`
`;ordered.forEach((v,i)=>{const isYT=v.type==='youtube',isHLS=!isYT&&v.src?.includes('.m3u8'),poster=v.poster?` poster="${v.poster}"`:'';const vtag=isYT?``:isHLS?``:``;const videoId='hl-'+league+'-'+(v.id||v._idx);h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',extraBtn:``});});h+='
';el.innerHTML=h;initTikTokFeed();} async function openYTShortsFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';const arts=_shortsData.length?_shortsData:(await fetch('/api/shorts').then(r=>safeJson(r)).catch(()=>[]));if(!arts.length){el.innerHTML='
Không có shorts
';return}const ordered=startIdx>0?[...arts.slice(startIdx),...arts.slice(0,startIdx)]:arts;let h=`
`;ordered.forEach((v,i)=>{const id=v.id||'';const src=`https://www.youtube.com/embed/${id}?autoplay=1&rel=0&playsinline=1`;const vtag=``;const badge=v.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí';const videoId='yt-'+id;h+=buildTikTokSlide({vtag,title:v.title,badge,badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:'https://youtube.com/watch?v='+id});});h+='
';el.innerHTML=h;initTikTokFeed();} async function openShortAIFeed(startIdx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';const wall=(await fetch('/api/ai_wall').then(r=>safeJson(r)).catch(()=>({posts:[]}))).posts||[];const vids=wall.filter(p=>p.video);if(!vids.length){el.innerHTML='
Chưa có Short AI
';return}const ordered=startIdx>0?[...vids.slice(startIdx),...vids.slice(0,startIdx)]:vids;let h=`
`;ordered.forEach((p,i)=>{const vtag=``;const videoId='ai-'+(p.id||i);h+=buildTikTokSlide({vtag,title:p.title,badge:'AI',badgeClass:'badge-ai',videoId,idx:i,total:ordered.length,shareUrl:SPACE});});h+='
';el.innerHTML=h;initTikTokFeed();} async function readArticle(url){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';try{const r=await fetch('/api/article?url='+encodeURIComponent(url));const data=await safeJson(r);if(data&&!data.error&&data.body&&data.body.length){_currentArticle={url,data};let h=`

${esc(data.title)}

`;if(data.summary)h+=`
${esc(data.summary)}
`;const seen={};data.body.forEach(b=>{if(b.type==='p')h+=`

${b.text}

`;else if(b.type==='img'&&b.src&&!seen[b.src]){seen[b.src]=1;h+=``}else if(b.type==='heading')h+=`

${esc(b.text)}

`});h+=`

🤖 Hỏi AI

`;el.innerHTML=h;window.scrollTo(0,0);return;}}catch(e){}el.innerHTML=`

Không đọc được.

Mở gốc →
`;} async function rewriteArticle(){ const url=_currentArticle?.url;if(!url)return; toast('⏳ Đang rewrite...'); try{ const r=await fetchWithTimeout('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url,context:document.querySelector('.article-view')?.innerText?.slice(0,14000)||''})},60000); const j=await safeJson(r); if(!r.ok||j.error)throw new Error(j.error); toast('✅ Đã đăng Tường AI!'); }catch(e){ if(e.message==='timeout')toast('❌ Quá lâu, thử lại'); else toast('❌ '+e.message); } } async function rewriteUrl(){ const url=document.getElementById('url-input')?.value.trim();if(!url)return alert('Dán URL'); toast('⏳ Đang rewrite...'); try{ const r=await fetchWithTimeout('/api/url_wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})},60000); const j=await safeJson(r); if(!r.ok||j.error)throw new Error(j.error); toast('✅ Đã đăng!');document.getElementById('url-input').value=''; }catch(e){ if(e.message==='timeout')toast('❌ Quá lâu, thử lại'); else toast('❌ '+e.message); } } async function askAI(){const q=document.getElementById('ask-q')?.value.trim();if(!q)return alert('Nhập câu hỏi');const a=document.getElementById('ask-a');a.textContent='Đang hỏi...';try{const r=await fetch('/api/article/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:_currentArticle?.url||'',question:q,context:document.querySelector('.article-view')?.innerText?.slice(0,12000)||''})});const j=await safeJson(r);a.textContent=j.answer||'Không trả lời được';}catch(e){a.textContent='Lỗi: '+e.message}} async function readWallPost(i){const wall=(await fetch('/api/ai_wall').then(r=>safeJson(r)).catch(()=>({posts:[]}))).posts||[];const p=wall[i];if(!p)return;showView('view-article');document.getElementById('view-article').innerHTML=`
AI

${esc(p.title)}

${p.img?``:''}

${esc(p.text)}

${p.video?``:''}
`;window.scrollTo(0,0)} async function loadNewsTab(){const el=document.getElementById('view-cat');el.innerHTML='
Đang tải...
';try{const r=await fetch('/api/homepage');const news=await safeJson(r);if(!news.length){el.innerHTML='
Không có tin
';return}const groups={};news.forEach(a=>{if(!groups[a.group])groups[a.group]=[];groups[a.group].push(a)});let h='';for(const[g,arts] of Object.entries(groups)){h+=`
${g}
`;arts.slice(0,6).forEach(a=>{h+=`
${a.img?``:''}
${esc(a.source||'VnE')}
${esc(a.title)}
`});h+='
'}el.innerHTML=h}catch(e){el.innerHTML='
Lỗi
'}} async function loadCat(id){const el=document.getElementById('view-cat');el.innerHTML='
Đang tải...
';const r=await fetch('/api/category/'+id);const arts=await safeJson(r).catch(()=>[]);if(!arts.length){el.innerHTML='
Không có tin
';return}let h='
';arts.forEach(a=>{h+=`
${a.img?``:''}
${esc(a.source||'')}
${esc(a.title)}
`});h+='
';el.innerHTML=h} fetch('/api/storage_status').then(r=>safeJson(r)).then(j=>{if(!j.persistent){const home=document.getElementById('view-home');if(home){const w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ Persistent Storage chưa bật.';home.prepend(w)}}}).catch(()=>{});