/** * VNEWS Frontend v2 - Shorts Dantri/SKDS removed, VTV Digital CDN * v2.8 - Changed short AI feed video share button icon (📥) to distinguish from article share (📤) * v2.6 - Fixed share links: doShare now includes post_id for wall posts, * readSlidePost has share button, /s + /s/{slug} render slides/video inline * v2.5 - Added 'Tạo lại' button on wall cards with video * v2.4 - Fixed: prependWallPost detached-element bug, makeShortVideo UI update, slide viewer for rewrite posts */ function _proxyImg(url){ if(!url || typeof url !== 'string') return ''; if(url.startsWith('http') && !url.includes(location.host)){ return '/api/proxy/img?url='+encodeURIComponent(url); } return url; } var _ttsSelections = {}; 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; 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'); loadLivescore('today'); loadHotTopics(); const [featuredData, wallData, hlLeagues, wcData] = await Promise.allSettled([ _fetchWithTimeout('/api/livescore/featured', 5000), _fetchWithTimeout('/api/wall', 5000), _fetchWithTimeout('/api/highlights/leagues', 10000), _fetchWithTimeout('/api/wc2026', 8000), ]).then(results => results.map(r => r.status === 'fulfilled' ? r.value : null)); 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=``; } _wallPosts = (wallData && wallData.posts) || []; _hlLeagueData = hlLeagues || {}; _wc2026Data = wcData; if(wcData) switchWCTab('news'); _renderWallIn(afterEl); _renderHLIn(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 _renderWallIn(afterEl){ if(!_wallPosts||!_wallPosts.length) return; const posts=_wallPosts; 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; const target=document.getElementById('ai-wall-under-compose'); if(target) target.appendChild(wrap); else if(afterEl) 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){ var hasVideo = p.video && p.video.length > 0; var thumbContent = p.img ? '' : (hasVideo ? '' : ''); var videoBadge = hasVideo ? '
🎬
' : ''; var vid = p.id||i; var lang = p.language || detectLanguage(p.title + ' ' + (p.text||'')); var curVoice = p.voice || getAutoVoice(lang); var curEmotion = p.emotion || detectEmotion(p.title + ' ' + (p.text||'')); var selKey = 'inline-' + vid; if(!_ttsSelections[selKey]) _ttsSelections[selKey] = {voice: curVoice, emotion: curEmotion}; var voiceOpts = ''; VOICE_LIST.forEach(function(v){ voiceOpts += ''; }); var emotOpts = ''; EMOTION_LIST.forEach(function(e){ emotOpts += ''; }); var spd = p.short_speed || '1.2'; var voiceBar = '
' +'' +'' +'' +'
'; var makeBtn = hasVideo ? '' : ''; return '
'+thumbContent+videoBadge+'
'+esc(p.title)+'
'+esc((p.text||'').slice(0,180))+'
'+voiceBar+'
'+makeBtn+'
'; } async function makeShortVideo(postId, btn, voice, speed, emotion){ 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...'); if(!voice || !emotion){ const selKey = 'inline-'+postId; const container = document.querySelector('.tts-selector[data-post-id="'+postId+'"]'); if(container){ if(_ttsSelections[selKey]){ voice = voice || _ttsSelections[selKey].voice; emotion = emotion || _ttsSelections[selKey].emotion; } if(!voice){ const selectedVoiceBtn = container.querySelector('.tts-voice-btn.selected') || container.querySelector('.tts-voice-btn[style*="5cb87a"]') || container.querySelector('.tts-voice-btn'); voice = selectedVoiceBtn ? selectedVoiceBtn.dataset.voice : 'vi-VN-HoaiMyNeural'; } if(!emotion){ const selectedEmotionBtn = container.querySelector('.tts-emotion-btn.selected') || container.querySelector('.tts-emotion-btn[style*="5cb87a"]') || container.querySelector('.tts-emotion-btn'); emotion = selectedEmotionBtn ? selectedEmotionBtn.dataset.emotion : 'neutral'; } const speedSelect = container.querySelector('.tts-speed'); speed = speedSelect ? parseFloat(speedSelect.value) || 1.2 : (speed || 1.2); } else { voice = voice || 'vi-VN-HoaiMyNeural'; emotion = emotion || 'neutral'; speed = speed || 1.2; } } try{ const r = await fetch('/api/ai/short/' + encodeURIComponent(postId), {method:'POST',headers:{'Content-Type':'application/json'},body: JSON.stringify({voice:voice, emotion:emotion, speed:speed})}); 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; p.voice = j.voice; p.emotion = j.emotion; const itemId = 'wall-item-'+postId; const el = document.getElementById(itemId); if(el){ const idx = _wallPosts.indexOf(p); el.insertAdjacentHTML('afterend', makeWallItem(p, idx)); el.remove(); } } }catch(e){ toast('❌ '+e.message); if(btn){btn.disabled=false;btn.textContent=origText;} } } var VOICE_LIST = [ {id:'vi-VN-HoaiMyNeural', label:'🎙️ Hoài My (VI)', lang:'vi'}, {id:'vi-VN-NamMinhNeural', label:'🎙️ Nam Minh (VI)', lang:'vi'}, {id:'en-US-AndrewMultilingualNeural', label:'🎙️ Andrew (EN)', lang:'en'}, {id:'en-AU-WilliamMultilingualNeural', label:'🎙️ William (EN)', lang:'en'}, {id:'pt-BR-ThalitaMultilingualNeural', label:'🎙️ Thalita (PT)', lang:'pt'}, {id:'fr-FR-VivienneMultilingualNeural', label:'🎙️ Vivienne (FR)', lang:'fr'}, {id:'fr-FR-RemyMultilingualNeural', label:'🎙️ Rémy (FR)', lang:'fr'}, {id:'de-DE-SeraphinaMultilingualNeural', label:'🎙️ Seraphina (DE)', lang:'de'}, {id:'de-DE-FlorianMultilingualNeural', label:'🎙️ Florian (DE)', lang:'de'}, {id:'ko-KR-HyunsuMultilingualNeural', label:'🎙️ Hyunsu (KO)', lang:'ko'}, {id:'it-IT-GiuseppeMultilingualNeural', label:'🎙️ Giuseppe (IT)', lang:'it'}, ]; var EMOTION_LIST = [ {id:'neutral', label:'😐 Trung tính'}, {id:'happy', label:'😊 Vui vẻ'}, {id:'excited', label:'🔥 Hào hứng'}, {id:'sad', label:'😢 Buồn'}, {id:'humorous', label:'😂 Hài hước'}, {id:'serious', label:'⚠️ Nghiêm túc'}, {id:'urgent', label:'🚨 Khẩn cấp'}, {id:'warm', label:'💖 Ấm áp'}, ]; document.addEventListener('click',function(e){ var btn = e.target.closest('.tts-voice-btn'); if(btn){ var container = btn.closest('.tts-selector'); if(container){ var selKey = 'inline-'+container.dataset.postId; if(!_ttsSelections[selKey]) _ttsSelections[selKey]={voice:btn.dataset.voice,emotion:'neutral'}; var allBtns = container.querySelectorAll('.tts-voice-btn'); for(var i=0;i=2) return 'vi'; if(chars.has('ñ')||chars.has('¿')||chars.has('¡')) return 'es'; if(chars.has('ã')||chars.has('õ')) return 'pt'; var words=t.split(/\s+/); var enWords=['the','is','at','which','on','and','or','but','this','that','with','from','have','been']; var enCount=words.filter(function(w){return enWords.indexOf(w)>=0;}).length; if(enCount>=2) return 'en'; return 'vi'; } function detectEmotion(text){ if(!text) return 'neutral'; var t=text.toLowerCase(); var kws={ happy:['vui','hạnh phúc','tuyệt','thành công','chiến thắng','feliz','maravilloso','happy','joy','wonderful','great','amazing','love','excellent'], excited:['hào hứng','phấn khích','đột phá','kỷ lục','đỉnh cao','emocionante','increíble','excited','thrilling','unbelievable','awesome','breakthrough'], sad:['buồn','đau','mất','thảm họa','khủng hoảng','triste','terrible','sad','unhappy','tragic','painful','death'], humorous:['hài hước','buồn cười','haha','đùa','engraçado','gracioso','funny','hilarious','joke','lol'], serious:['nghiêm trọng','khẩn cấp','quan trọng','lo ngại','sério','crítico','serious','critical','urgent','severe','crisis'], urgent:['khẩn cấp','báo động','ngay lập tức','urgent','breaking','alert','emergency'], warm:['ấm áp','tình cảm','yêu thương','warm','love','heart','touching'] }; var bestScore=0, bestEmotion='neutral'; for(var em in kws){var score=0; for(var kw of kws[em]){if(t.indexOf(kw)>=0) score++;} if(score>bestScore){bestScore=score;bestEmotion=em;}} return bestEmotion; } function getAutoVoice(lang){var map={vi:'vi-VN-HoaiMyNeural',pt:'pt-BR-ThalitaMultilingualNeural',en:'en-US-AndrewMultilingualNeural',fr:'fr-FR-VivienneMultilingualNeural',de:'de-DE-SeraphinaMultilingualNeural',ko:'ko-KR-HyunsuMultilingualNeural',it:'it-IT-GiuseppeMultilingualNeural'};return map[lang]||'vi-VN-HoaiMyNeural';} function buildVoiceEmotionSelector(post){ var lang=post.language||detectLanguage(post.title+' '+(post.text||'')); var _oldVoiceMap = {'hoaimy':'vi-VN-HoaiMyNeural','namminh':'vi-VN-NamMinhNeural','andrew':'en-US-AndrewMultilingualNeural','jenny':'en-US-AndrewMultilingualNeural','thalita':'pt-BR-ThalitaMultilingualNeural','pt_thalita':'pt-BR-ThalitaMultilingualNeural','vivienne':'fr-FR-VivienneMultilingualNeural','remy':'fr-FR-RemyMultilingualNeural','seraphina':'de-DE-SeraphinaMultilingualNeural','florian':'de-DE-FlorianMultilingualNeural','sunhee':'ko-KR-HyunsuMultilingualNeural','hyunsu':'ko-KR-HyunsuMultilingualNeural','giuseppe':'it-IT-GiuseppeMultilingualNeural','ela':'en-US-AndrewMultilingualNeural','denise':'fr-FR-VivienneMultilingualNeural','katja':'de-DE-SeraphinaMultilingualNeural','nanami':'en-US-AndrewMultilingualNeural','xiaochen':'en-US-AndrewMultilingualNeural','es_carlos':'en-US-AndrewMultilingualNeural','pt_francisco':'pt-BR-ThalitaMultilingualNeural'}; var _postVoice = post.voice ? (_oldVoiceMap[post.voice] || post.voice) : ''; var autoVoice= _postVoice || getAutoVoice(lang); var autoEmotion=post.emotion||detectEmotion(post.title+' '+(post.text||'')); var selKey = 'inline-'+post.id; if(!_ttsSelections[selKey]){_ttsSelections[selKey] = {voice: autoVoice, emotion: autoEmotion};} var h='
'; h+='
🎙️ Giọng đọc (ngôn ngữ: '+lang.toUpperCase()+'):
'; VOICE_LIST.forEach(function(v){var sel=v.id===_ttsSelections[selKey].voice?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); h+='
😊 Cảm xúc:
'; EMOTION_LIST.forEach(function(e){var sel=e.id===_ttsSelections[selKey].emotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); h+='
⚡ Tốc độ:'; h+='
'; h+='
'; return h; } window.showVoiceEmotionSelector=function(postId,title,text){ var overlay=document.createElement('div'); overlay.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px'; var box=document.createElement('div');box.style.cssText='background:#1a1a1a;border:2px solid #2d8659;border-radius:16px;padding:20px;max-width:400px;width:100%;max-height:80vh;overflow-y:auto'; var lang=detectLanguage(title+' '+text);var autoEmotion=detectEmotion(title+' '+text); var h='

🎬 Tạo Short AI (ngôn ngữ: '+lang.toUpperCase()+')

'; h+='
🎙️ Chọn giọng đọc:
'; VOICE_LIST.forEach(function(v){var sel=v.id===getAutoVoice(lang)?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); h+='
😊 Chọn cảm xúc:
'; EMOTION_LIST.forEach(function(e){var sel=e.id===autoEmotion?'border-color:#5cb87a;background:#1a2a1f':'border-color:#333;background:#222';h+='';}); h+='
⚡ Tốc độ:
'; h+='
'; h+='
'; h+='
'; h+=''; box.innerHTML=h;overlay.appendChild(box);document.body.appendChild(overlay); var selectedVoice=getAutoVoice(lang),selectedEmotion=autoEmotion; box.querySelectorAll('.ve-voice-btn').forEach(function(btn){btn.addEventListener('click',function(){box.querySelectorAll('.ve-voice-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';});this.style.borderColor='#5cb87a';this.style.background='#1a2a1f';selectedVoice=this.dataset.voice;});}); box.querySelectorAll('.ve-emotion-btn').forEach(function(btn){btn.addEventListener('click',function(){box.querySelectorAll('.ve-emotion-btn').forEach(function(b){b.style.borderColor='#333';b.style.background='#222';});this.style.borderColor='#5cb87a';this.style.background='#1a2a1f';selectedEmotion=this.dataset.emotion;});}); box.querySelector('#ve-cancel-btn').addEventListener('click',function(){overlay.remove();}); box.querySelector('#ve-create-btn').addEventListener('click',async function(){ this.disabled=true;this.textContent='⏳ Đang tạo...'; box.querySelector('#ve-status').style.display='block';box.querySelector('#ve-status').textContent='Đang tạo video shorts...'; try{ var speed=parseFloat(box.querySelector('#ve-speed').value)||1.2; if(!_ttsSelections["inline-"+postId]) _ttsSelections["inline-"+postId]={voice:"vi-VN-HoaiMyNeural",emotion:"neutral"}; _ttsSelections["inline-"+postId].voice=selectedVoice;_ttsSelections["inline-"+postId].emotion=selectedEmotion; var r=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:selectedVoice,emotion:selectedEmotion,speed:speed})}); var j=await r.json(); if(!r.ok||j.error) throw new Error(j.error||'Lỗi tạo video'); toast('✅ Đã tạo Short AI!');overlay.remove(); var p=_wallPosts.find(function(x){return String(x.id)===String(postId);}); if(p){p.video=j.video;p.voice=j.voice;p.emotion=j.emotion;} }catch(e){this.disabled=false;this.textContent='🎬 Tạo Short';box.querySelector('#ve-status').textContent='❌ '+e.message;} }); }; function prependWallPost(post){ _wallPosts.unshift(post); const track=document.getElementById('ai-wall-track'); const wrap=document.getElementById('ai-wall-wrap'); const target=document.getElementById('ai-wall-under-compose'); if(target && (!track||!wrap)){ const newWrap=document.createElement('div'); newWrap.className='slider-wrap';newWrap.id='ai-wall-wrap'; newWrap.innerHTML=`
🧱 Tường AI
${makeWallItem(post,0)}
`; target.appendChild(newWrap); const firstItem=newWrap.querySelector('.wall-item'); if(firstItem)firstItem.className='wall-item wall-item-new'; return; } if(track){ track.insertAdjacentHTML('afterbegin', makeWallItem(post, 0)); track.scrollTo({left:0,behavior:'smooth'}); } } let _wallPosts=[]; let _currentView='home'; let _currentEventId=null; let _currentMatchUrl=null; let _htPage=0,_htTopic=''; async function loadHotTopics(){const j=await fetch('/api/hot_topics').then(r=>r.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('');} 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;const ctrl=new AbortController();setTimeout(()=>ctrl.abort(),4000);fetch('/api/article?url='+encodeURIComponent(s.url),{signal:ctrl.signal}).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
'}} function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]))} function showView(id){document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.getElementById(id)?.classList.add('active')} function switchCat(id){document.querySelectorAll('.cat').forEach(c=>c.classList.remove('active'));document.querySelector(`[data-cat="${id}"]`)?.classList.add('active');document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));document.querySelectorAll('video').forEach(v=>{v.pause();if(v._hls){v._hls.destroy();v._hls=null}});document.querySelectorAll('iframe[data-yt-src]').forEach(f=>{f.src=''});if(id==='home')document.getElementById('view-home').classList.add('active');else if(id==='news-all'){document.getElementById('view-cat').classList.add('active');loadNewsTab()}else{document.getElementById('view-cat').classList.add('active');loadCat(id)}} function toast(msg){let t=document.getElementById('progress-toast');if(t){t.textContent=msg;t.style.display='block';setTimeout(()=>{t.style.display='none'},3500)}} // ===== doShare: COPY link to clipboard, then try native share as bonus ===== function doShare(title,url,img,postId){ var shareUrl; if(postId){ shareUrl = SPACE+'/s?post_id='+encodeURIComponent(postId)+'&title='+encodeURIComponent(title); } else { shareUrl = SPACE+'/s?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title)+'&img='+encodeURIComponent(img||''); } // Try clipboard API first (modern, works on HTTPS) if(navigator.clipboard && navigator.clipboard.writeText){ navigator.clipboard.writeText(shareUrl).then(function(){ toast('📋 Đã sao chép link!'); try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} }).catch(function(){ // Fallback: execCommand (deprecated but works on some browsers) try{ var ta=document.createElement('textarea'); ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0'; document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999); if(document.execCommand('copy')){toast('📋 Đã sao chép link!');} else{prompt('📋 Sao chép link:', shareUrl);} document.body.removeChild(ta); }catch(e){prompt('📋 Sao chép link:', shareUrl);} try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} }); } else { // execCommand approach try{ var ta=document.createElement('textarea'); ta.value=shareUrl;ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='-9999px';ta.style.opacity='0'; document.body.appendChild(ta);ta.select();ta.setSelectionRange(0,99999); if(document.execCommand('copy')){toast('📋 Đã sao chép link!');} else{prompt('📋 Sao chép link:', shareUrl);} document.body.removeChild(ta); }catch(e){prompt('📋 Sao chép link:', shareUrl);} try{if(navigator.share)navigator.share({title:title||'',url:shareUrl}).catch(function(){});}catch(e){} } } 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);/* Remove snap so feed can scroll to show comment input */var sl=panel.closest('.tiktok-slide');if(sl)sl.style.scrollSnapAlign='';setTimeout(function(){var feed=document.getElementById('tiktok-feed');if(feed){var slidePos=sl?sl.offsetTop:0;feed.scrollTop=slidePos+200;}/* Focus input */var inp=document.getElementById('cmt-input-'+idx);if(inp)inp.focus();},300);} 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);/* Keep focus on input after submit */var inp2=document.getElementById('cmt-input-'+idx);if(inp2)inp2.focus();} function toggle169View(videoId,iconId){const slide=videoId?document.querySelector(`.tiktok-slide[data-vid="${videoId}"]`):null;if(slide){slide.classList.toggle('ratio-wide');const iconEl=iconId?document.getElementById(iconId):null;if(iconEl)iconEl.textContent=slide.classList.contains('ratio-wide')?'📺':'🖥️';else{const btn=slide.querySelector('.tiktok-right-btn .icon');if(btn)btn.textContent=slide.classList.contains('ratio-wide')?'📺':'🖥️';}return}document.querySelectorAll('.tiktok-slide.ratio-wide').forEach(s=>s.classList.remove('ratio-wide'));document.querySelectorAll('.tiktok-slide').forEach(s=>s.classList.add('ratio-wide'));document.querySelectorAll('.tiktok-right-btn .icon').forEach(b=>{if(b.textContent==='🖥️')b.textContent='📺';})} 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)+'&img='+encodeURIComponent(a.img||''));const v=await r.json();if(v&&v.src){return{_idx:i,title:a.title||v.title||'',link:a.link||'',img:a.img||v.poster||'',src:v.src,type:v.type||'',poster:v.poster||a.img||''}}return null}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="${esc(v.poster)}"`:'';const vtag=isYT?``:isHLS?``:``;const videoId='hl-'+league+'-'+v._idx;h+=buildTikTokSlide({vtag,title:v.title,badge:'HL',badgeClass:'badge-fpt',videoId,idx:i,total:ordered.length,shareUrl:v.link||'',postId:'',extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} async function openYTShortsFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');el.innerHTML='
Đã xóa Shorts Dân trí/SKĐS
';} async function openShortAIFeed(idx){showView('view-tiktok');const el=document.getElementById('view-tiktok');if(!_wallPosts||!_wallPosts.length){el.innerHTML='
Không có Short AI
';return}const aiPosts=_wallPosts.filter(p=>p.video);if(!aiPosts.length||idx>=aiPosts.length){el.innerHTML='
Không có Short AI
';return}const ordered=aiPosts.slice(idx).concat(aiPosts.slice(0,idx));let h=`
`;ordered.forEach((p,i)=>{const baseIdx=_wallPosts.indexOf(p);const vtag=p.video?``:'';h+=buildTikTokSlide({vtag,title:p.title,badge:'Short AI',badgeClass:'badge-ai',videoId:p.id||'ai-'+i,idx:i,total:ordered.length,shareUrl:p.video||'',postId:p.id||'',extraBtn:``})});h+='
';el.innerHTML=h;setTimeout(()=>initTikTokFeed(),200);} function readWallPost(idx){const p=_wallPosts&&_wallPosts[idx];if(!p)return;if(p.slides&&p.slides.length){readSlidePost(idx);return}readArticle(p.url||'','','',p.title,p.text);} /** Show rewrite slide viewer - vertical slides with text+image */ function readSlidePost(idx){const p=_wallPosts[idx];if(!p||!p.slides)return;showView('view-article');const el=document.getElementById('view-article');let h=`
`;p.slides.forEach((s,i)=>{h+=`
Slide ${s.index||i+1}/${p.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
`;el.innerHTML=h;} function readNewsTab(tab){loadNewsTab();} function loadNewsTab(){const el=document.getElementById('view-cat');if(!el)return;el.innerHTML='
Đang tải tin tức...
';fetch('/api/homepage').then(r=>r.json()).then(articles=>{if(!articles||!articles.length){el.innerHTML='
Không có tin
';return}let h='
';articles.forEach(a=>{const src=a.source||'vne';const badge=a.group||a.source||'';h+=`
${a.img?``:''}
${esc(badge)}
${esc(a.title)}
`;});h+='
';el.innerHTML=h;}).catch(()=>{el.innerHTML='
Lỗi tải
';});} function readArticle(url,title,img,presetTitle,presetText){showView('view-article');const el=document.getElementById('view-article');el.innerHTML='
Đang tải...
';if(presetTitle){el.innerHTML=`

${esc(presetTitle)}

${presetText?`
${esc(presetText)}
`:''}
`;return;}if(!url)return;fetch('/api/article?url='+encodeURIComponent(url)).then(r=>r.json()).then(d=>{let h=`
`;if(d.title)h+=`

${esc(d.title)}

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

${esc(b.text)}

`;else if(b.type==='heading')h+=`

${esc(b.text)}

`;else if(b.type==='img'&&b.src)h+=``;});h+=`
`;el.innerHTML=h;}).catch(()=>{el.innerHTML=`

Không thể tải bài viết

`;});} async function rewriteSlide(url){if(!url)return;const btn=document.querySelector('.article-actions .primary')||event?.target;if(btn){btn.disabled=true;btn.textContent='⏳ Đang tạo slides...';}toast('⏳ Đang tạo slide rewrite...');try{const r=await fetch('/api/rewrite_share',{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||'Lỗi');toast('✅ Đã tạo slide! Đang tạo Short AI...');if(btn)btn.textContent='✅ Đang tạo Short AI...';if(j.post){j.post.slides=j.slides||[];prependWallPost(j.post);}// Show slides immediately if available if(j.slides && j.slides.length){showView('view-article');const el=document.getElementById('view-article');let h=`
`;j.slides.forEach(s=>{h+=`
Slide ${s.index}/${j.slides.length}
${s.image?``:''}

${esc(s.text)}

`;});h+=`
⏳ Đang tạo video Short AI...
`;el.innerHTML=h;} const postId=j.post&&j.post.id;if(postId){setTimeout(async()=>{const sr=await fetch('/api/ai/short/'+encodeURIComponent(postId),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:'vi-VN-HoaiMyNeural',emotion:'neutral',speed:1.2})});const sj=await sr.json();if(sr.ok&&sj.video&&typeof _wallPosts!=='undefined'){const p=_wallPosts.find(x=>String(x.id)===String(postId));if(p){p.video=sj.video;const itemId='wall-item-'+postId;const el2=document.getElementById(itemId);if(el2){const idx=_wallPosts.indexOf(p);el2.insertAdjacentHTML('afterend',makeWallItem(p,idx));el2.remove();}}toast('✅ Short AI đã sẵn sàng!');const statusEl=document.getElementById('short-ai-status');if(statusEl)statusEl.innerHTML='✅ Short AI đẵn sàng! ';}},500);}if(btn)btn.textContent='✅ Hoàn tất';}catch(e){toast('❌ '+e.message);if(btn){btn.disabled=false;btn.textContent='🤖 Slide Rewrite AI';}}} // ===== SHARE VIDEO TO OTHER APPS ===== function shareVideoToApps(videoUrl, title){ if(!videoUrl){ toast('Không có video để chia sẻ'); return; } var fullUrl = videoUrl.startsWith('http') ? videoUrl : window.location.origin + videoUrl; // Step 1: Try navigator.share with URL (async, works on mobile) try{ if(navigator.share){ navigator.share({ title: title || 'Short AI Video', url: fullUrl }).then(function(){toast('✅ Đã chia sẻ!');return;}).catch(function(e){ if(e.name==='AbortError')return; downloadVideo(fullUrl, title); }); return; } }catch(e){} // Step 2: Fallback - download downloadVideo(fullUrl, title); } function downloadVideo(url, title){ var a = document.createElement('a'); a.href = url; a.download = (title||'video').replace(/[^a-zA-Z0-9_\-\p{L}]/gu,'_').substring(0,60)+'.mp4'; a.target = '_blank'; a.rel = 'noopener'; a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); toast('📥 Đang tải video xuống...'); }