// === VNEWS Frontend v2 - Optimized for speed === // === LOAD HOME - Fast: immediate shell + parallel fetch === function _fetchWithTimeout(url, ms){ return new Promise((resolve,reject)=>{ const ctrl=new AbortController(); const tid=setTimeout(()=>ctrl.abort(),ms); fetch(url,{signal:ctrl.signal}).then(r=>{ clearTimeout(tid); if(!r.ok) return reject(new Error('HTTP '+r.status)); return r.json(); }).then(d=>resolve(d)).catch(e=>{clearTimeout(tid);reject(e);}); }); } async function loadHome(){ const homeEl = document.getElementById('view-home'); if(!homeEl) return; // Build shell IMMEDIATELY — no skeleton, no delay homeEl.innerHTML = '' +'
🤖 AI viết bài
' +'
' +'

⚽ Livescore

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

🏆 World Cup 2026

● LIVE
📰 Tin tức📅 Lịch thi đấu🏆 BXH🎬 Highlight📊 Thống kê
Đang tải World Cup 2026...
' +'
'; const afterEl = homeEl.querySelector('#home-after-wc'); // Start critical loads immediately loadLivescore('today'); loadHotTopics(); // Fetch all data in parallel with shorter timeouts const [featuredData, shortsData, wallData, hlLeagues, aiData, wcData] = await Promise.allSettled([ _fetchWithTimeout('/api/livescore/featured', 5000), _fetchWithTimeout('/api/shorts', 8000), _fetchWithTimeout('/api/wall', 5000), _fetchWithTimeout('/api/highlights/leagues', 10000), _fetchWithTimeout('/api/genk_ai', 8000), _fetchWithTimeout('/api/wc2026', 8000), ]).then(results => results.map(r => r.status === 'fulfilled' ? r.value : null)); // Render featured match if(featuredData && featuredData.home){ const sc=featuredData.status==='live'?'':'upcoming'; const st=featuredData.status==='live'?`🔴 ${featuredData.minute||'LIVE'}`:`⏰ ${featuredData.time}`; const area=document.getElementById('home-featured-area'); if(area) area.innerHTML=``; } // Store globally _shortsData = shortsData || []; _wallPosts = (wallData && wallData.posts) || []; _hlLeagueData = hlLeagues || {}; _wc2026Data = wcData; // Render WC if data arrived if(wcData) switchWCTab('news'); // Render sections into the after-wc area _renderShortsIn(afterEl); _renderWallIn(afterEl); _renderHLIn(afterEl); if(aiData && aiData.length) _renderSlidesIn('ai-articles','Ứng dụng AI','🤖',aiData,afterEl); } function _renderSlidesIn(key, label, emoji, vids, afterEl){ if(!vids||!vids.length||!afterEl) return; const wrap=document.createElement('div'); wrap.className='slider-wrap'; let h=`
${emoji} ${label}
`; const isHL = key==='world-cup'||key==='premier-league'||key==='champions-league'||key==='la-liga'||key==='serie-a'||key==='bundesliga'||key==='friendly'; vids.slice(0,isHL?8:12).forEach((a,i)=>{ if(isHL){ h+=`
${a.img?``:''}
${esc(a.title)}
`; } else { h+=`
${a.img?``:''}
${esc(a.title)}
`; } }); h+='
'; wrap.innerHTML=h; afterEl.parentNode.insertBefore(wrap, afterEl); } function _renderShortsIn(afterEl){ if(!_shortsData||!_shortsData.length||!afterEl) return; const mixed=interleaveShorts(_shortsData); if(!mixed.length) return; const wrap=document.createElement('div'); wrap.className='slider-wrap'; let h=`
📱 Shorts Dân trí & SKĐSMới nhất · xen kẽ
`; mixed.slice(0,30).forEach((a,i)=>{ const badge=a.channel==='baosuckhoedoisongboyte'?'SKĐS':'Dân trí'; h+=`
${a.img?``:''}
${badge} ${esc(a.title)}
`; }); h+='
';wrap.innerHTML=h; afterEl.parentNode.insertBefore(wrap,afterEl); } function _renderWallIn(afterEl){ if(!_wallPosts||!_wallPosts.length||!afterEl) return; const posts=_wallPosts; const aiShorts=posts.filter(p=>p.video); if(aiShorts.length){ const wrap=document.createElement('div'); wrap.className='slider-wrap'; let h='
🎬 Short AI
'; aiShorts.slice(0,20).forEach((p,i)=>{h+=`
${esc(p.title)}
`;}); h+='
';wrap.innerHTML=h; afterEl.parentNode.insertBefore(wrap,afterEl); } const wrap=document.createElement('div'); wrap.className='slider-wrap';wrap.id='ai-wall-wrap'; let h='
🧱 Tường AI
'; posts.slice(0,20).forEach((p,i)=>{h+=makeWallItem(p,i);}); h+='
';wrap.innerHTML=h; afterEl.parentNode.insertBefore(wrap,afterEl); } function _renderHLIn(afterEl){ if(!_hlLeagueData||Object.keys(_hlLeagueData).length===0||!afterEl) return; 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=_hlLeagueData[key]; if(!vids||!vids.length) continue; _renderSlidesIn(key,cfg.name,cfg.emoji,vids,afterEl); } } // === WALL POST HELPERS === function makeWallItem(p,i){ const hasVideo = p.video && p.video.length > 0; const thumbContent = p.img ? `` : (hasVideo ? `` : ''); const videoBadge = hasVideo ? `
🎬
` : ''; const videoBtn = hasVideo ? `` : ``; return `
${thumbContent}${videoBadge}
${esc(p.title)}
${esc((p.text||'').slice(0,180))}
${videoBtn}
`; } async function makeShortVideo(postId, btn, voice, speed){ if(!postId)return; const origText = btn ? btn.textContent : '🎬 Tạo Video'; if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo...';} toast('⏳ Đang tạo video shorts...'); try{ let url = '/api/ai/short/'+encodeURIComponent(postId); const params = []; if(voice) params.push('voice='+encodeURIComponent(voice)); if(speed) params.push('speed='+encodeURIComponent(speed)); if(params.length) url += '?' + params.join('&'); const r = await fetch(url, {method:'POST'}); const j = await r.json(); if(!r.ok || j.error) throw new Error(j.error||'Lỗi tạo video'); toast('✅ Đã tạo video shorts!'); const p = _wallPosts.find(x => String(x.id) === String(postId)); if(p){ p.video = j.video; const itemId = 'wall-item-'+postId; const el = document.getElementById(itemId); if(el){ const idx = _wallPosts.indexOf(p); el.outerHTML = makeWallItem(p, idx); const newEl = document.getElementById(itemId); if(newEl) newEl.className = 'wall-item wall-item-new'; } } refreshShortAISlider(); }catch(e){ toast('❌ '+e.message); if(btn){btn.disabled=false;btn.textContent=origText;} } } function refreshShortAISlider(){ const aiShorts = _wallPosts.filter(p=>p.video); let shortAISection = document.getElementById('short-ai-section'); if(aiShorts.length === 0){ if(shortAISection) shortAISection.remove(); return; } if(shortAISection){ const track = shortAISection.querySelector('.slider-track'); if(track){ let h = ''; aiShorts.slice(0,20).forEach((p,i)=>{ h+=`
${esc(p.title)}
`; }); track.innerHTML = h; } } } function prependWallPost(post){ _wallPosts.unshift(post); const track=document.getElementById('ai-wall-track'); const wrap=document.getElementById('ai-wall-wrap'); const homeEl=document.getElementById('view-home'); if(!track||!wrap){ if(homeEl){ let insertBefore=homeEl.querySelector('.slider-wrap'); const newWrap=document.createElement('div'); newWrap.className='slider-wrap'; newWrap.id='ai-wall-wrap'; newWrap.innerHTML=`
🧱 Tường AI
${makeWallItem(post,0)}
`; if(insertBefore) homeEl.insertBefore(newWrap,insertBefore); else homeEl.appendChild(newWrap); const firstItem=newWrap.querySelector('.wall-item'); if(firstItem)firstItem.className='wall-item wall-item-new'; } return; } const div=document.createElement('div'); div.className='wall-item wall-item-new'; div.id='wall-item-'+(post.id||'new-'+Date.now()); const hasVideo = post.video && post.video.length > 0; const thumbContent = post.img ? `` : (hasVideo ? `` : ''); const videoBadge = hasVideo ? `
🎬
` : ''; const videoBtn = hasVideo ? `` : ``; div.innerHTML=`
${thumbContent}${videoBadge}
${esc(post.title)}
${esc((post.text||'').slice(0,180))}
${videoBtn}
`; track.prepend(div); track.scrollTo({left:0,behavior:'smooth'}); if(hasVideo) refreshShortAISlider(); } // === REST OF FUNCTIONS === let _shortsData=[]; let _wallPosts=[]; let _currentView='home'; let _currentEventId=null; let _currentMatchUrl=null; 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(ir.json()).catch(()=>({topics:[]}));const el=document.getElementById('hot-topics');if(!el)return;el.innerHTML=(j.topics||[]).slice(0,18).map(t=>{const topicText=t.topic||t.label.replace(/^#/,'');return``;}).join('');if(j.topics&&j.topics[0]){const firstTopic=j.topics[0].topic||j.topics[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;showHashtagSources(topic,0);} async function showHashtagSources(topic,page){const box=document.getElementById('hashtag-box');if(!box)return;if(page===0)box.innerHTML=`

🔍 ${esc(topic)}

Đang tìm...
`;try{const r=await fetch(`/api/hashtag/sources?topic=${encodeURIComponent(topic)}&page=${page}`);const j=await r.json();const sources=j.sources||[];if(!sources.length&&page===0){box.innerHTML=`

🔍 ${esc(topic)}

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

🔍 ${esc(topic)} (${j.total} bài từ 8 nguồn)

`;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=>r.json()).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 tổng hợp...';}try{const r=await fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');toast('✅ Đã đăng Tường AI!');if(btn)btn.textContent='✅ Đăng thành công!';if(j.post)prependWallPost(j.post);}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Rewrite AI';}}} 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 r.json();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.style.cursor='pointer'; md.addEventListener('click',function(e){ const statusA=this.querySelector('.status a'); const teamA=this.querySelector('.teams a[href*="/tran-dau/"]'); const a = statusA || teamA; if(a){ e.preventDefault(); e.stopPropagation(); const href=a.getAttribute('href')||''; const m=href.match(/\/tran-dau\/(\d+)\//); if(m){ const fullUrl=href.startsWith('http')?href:'https://bongda.com.vn'+href; openMatch(m[1],fullUrl); } } }); }); el.querySelectorAll('a').forEach(a=>{ a.addEventListener('click',e=>{e.preventDefault();e.stopPropagation()}); }); } function openMatch(id,url){if(!id)return;_currentEventId=id;if(url)_currentMatchUrl=url;document.getElementById('match-overlay').classList.add('active');document.body.style.overflow='hidden';loadMatchTab('detail')} 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ê')||(tab==='detail'&&t.textContent.includes('Chi tiết')))t.classList.add('active')});const el=document.getElementById('mo-body');if(!el)return;el.innerHTML='
Đang tải...
';try{let apiUrl;if(tab==='stats')apiUrl=`/api/match/${_currentEventId}/stats`;else if(tab==='comm')apiUrl=`/api/match/${_currentEventId}/commentaries`;else{apiUrl=`/api/match/${_currentEventId}/detail`;if(_currentMatchUrl)apiUrl+='?url='+encodeURIComponent(_currentMatchUrl)}const r=await fetch(apiUrl);if(!r.ok){el.innerHTML='
Lỗi máy chủ ('+r.status+')
';return}const d=await r.json();if(d.error){el.innerHTML='
'+esc(d.error)+'
';return}if(tab==='detail'&&typeof renderMatchDetail==='function'){renderMatchDetail(el,d);return}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 r.json();}catch(e){return null;}} async function getInteractions(videoId){try{return await fetch('/api/v2/interactions?id='+encodeURIComponent(videoId)).then(r=>r.json());}catch(e){return{views:0,likes:0,comments:0};}} async function getComments(videoId){try{const j=await fetch('/api/v2/comments?id='+encodeURIComponent(videoId)).then(r=>r.json());return j.comments||[];}catch(e){return[];}} async function postComment(videoId,text){try{const j=await fetch('/api/v2/comment',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:videoId,text})}).then(r=>r.json());return j.comments||[];}catch(e){return[];}} function buildTikTokSlide(opts){return`
${opts.vtag}
${opts.badge||''}

${esc(opts.title)}

${opts.extraBtn||''}
${opts.idx+1}/${opts.total}
`;} async function doView(videoId,btn){const j=await doInteract(videoId,'view');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.views);}} async function doLike(videoId,btn){const j=await doInteract(videoId,'like');if(j){const c=btn.querySelector('.count');if(c)c.textContent=fmtNum(j.likes);}} function fmtNum(n){if(!n)return'0';if(n>=1000000)return(n/1000000).toFixed(1)+'M';if(n>=1000)return(n/1000).toFixed(1)+'K';return String(n);} async function loadCounters(videoIds){for(let i=0;iĐ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,forceUrl){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đang tải...
';let articles=(_hlLeagueData||{})[league]||[];if(!articles.length){try{articles=await fetch('/api/highlights/'+league).then(r=>r.json())}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 r.json();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=>r.json()).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/wall').then(r=>r.json()).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 r.json();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 fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url,context:document.querySelector('.article-view')?.innerText?.slice(0,14000)||''})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng Tường AI!');if(j.post)prependWallPost(j.post);}catch(e){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 fetch('/api/url_wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});const j=await r.json();if(!r.ok||j.error)throw new Error(j.error);toast('✅ Đã đăng!');document.getElementById('url-input').value='';if(j.post)prependWallPost(j.post);}catch(e){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 r.json();a.textContent=j.answer||'Không trả lời được';}catch(e){a.textContent='Lỗi: '+e.message}} async function readWallPost(i){const p=_wallPosts[i];if(!p)return;showView('view-article'); const images = p.images || []; let imgGallery = ''; if(images.length > 0){ imgGallery = '
'; images.forEach((imgUrl, imgIdx) => { if(imgIdx === 0){ imgGallery += ``; } else { if(imgIdx === 1) imgGallery += ''; imgGallery += '
'; } const hasVideo = p.video && p.video.length > 0; const voiceOptions = [ {id:'hoaimy', label:'🎙️ Nữ — Hoài My'}, {id:'namminh', label:'🎙️ Nam — Nam Minh'}, ]; let voiceSelector = ''; if(!hasVideo){ voiceSelector = `
🎙️ Chọn giọng đọc:
`; voiceOptions.forEach(v=>{ voiceSelector += ``; }); voiceSelector += `
Tốc độ:
`; voiceSelector += `
`; } document.getElementById('view-article').innerHTML=`
AI

${esc(p.title)}

${imgGallery}

${esc(p.text)}

${hasVideo?``:''}
${hasVideo?`${voiceSelector}`:`${voiceSelector}`}
`; const firstVoiceBtn = document.querySelector('.tts-voice-btn'); if(firstVoiceBtn) firstVoiceBtn.classList.add('active'); 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 r.json();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 arts=await fetch('/api/category/'+id).then(r=>r.json()).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=>r.json()).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(()=>{}); (function(){ try{ var hash = window.location.hash; if(hash && hash.length > 1){ var articleUrl = decodeURIComponent(hash.substring(1)); if(articleUrl.startsWith('http')){ history.replaceState(null, '', window.location.pathname); setTimeout(function(){ if(typeof readArticle==='function') readArticle(articleUrl); }, 1500); } } }catch(e){} })(); (function(){ try{ const pa=localStorage.getItem('pending_article'); const pv=localStorage.getItem('pending_video'); if(pa){ localStorage.removeItem('pending_article'); setTimeout(()=>{ if(typeof readArticle==='function') readArticle(pa); },1500); } if(pv){ localStorage.removeItem('pending_video'); try{ const v=JSON.parse(pv); if(v&&v.url) setTimeout(()=>{window.open(v.url,'_blank')},1500); }catch(e){} } }catch(e){} })(); if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function() { if (typeof loadHome === 'function') loadHome(); }); } else { if (typeof loadHome === 'function') loadHome(); }