(() => {
'use strict';
const $ = s => document.querySelector(s);
const defaults = {posts: DEMO.posts, liked:[], reposted:[], saved:[], followed:['mayamakes','dailybrief','studionorth'], tab:'For you', replies:{}};
let state;
try { state={...defaults,...JSON.parse(localStorage.getItem('orbit-demo-v1')||'{}')}; if(!Array.isArray(state.posts)||!Array.isArray(state.followed)) throw Error('bad state'); } catch { state=JSON.parse(JSON.stringify(defaults)); }
let page='home', detailId=null, query='', moreTrends=false, morePeople=false, modal=null, attachment='', toastTimer;
function save(){ try {localStorage.setItem('orbit-demo-v1',JSON.stringify(state));} catch {toast('Could not save changes in this browser.');} }
function toast(message){const el=$('#toast');el.textContent=message;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2500);}
function allPosts(){return state.posts.concat(Object.values(state.replies).flat());}
function render(){ $('#navigation').innerHTML=View.navigation(page); $('#main').innerHTML=View.main(page,state,detailId,query)+'<button class="mobile-compose" id="mobile-compose" aria-label="Compose post">+</button>';View.side(state,moreTrends,morePeople); }
function go(next,id){page=next;detailId=id||null;render();window.scrollTo(0,0);}
function toggle(list,id){const at=list.indexOf(id);if(at<0)list.push(id);else list.splice(at,1);}
function newPost(body){return {id:'local-'+Date.now()+'-'+Math.random().toString(36).slice(2,7),name:'You',handle:'you',initial:'Y',color:'#ce795f',time:'now',text:body,likes:0,reposts:0,replies:0,views:'',media:attachment||null};}
function publish(body,replyTo){body=body.trim();if(!body||body.length>280)return;const p=newPost(body);if(replyTo){(state.replies[replyTo] ||= []).push(p);}else state.posts.unshift(p);attachment='';save();closeModal();if(replyTo)go('detail',replyTo);else go('home');toast(replyTo?'Your reply was posted.':'Your post was sent.');}
function closeModal(){modal=null;attachment='';$('#modal-root').innerHTML='';}
function openModal(replyId){attachment='';const p=allPosts().find(x=>x.id===replyId);modal={replyId:replyId||null};$('#modal-root').innerHTML=`<div class="modal-backdrop" data-dismiss><section class="modal" role="dialog" aria-modal="true" aria-label="${replyId?'Reply':'Compose post'}"><button class="modal-close" data-close aria-label="Close">×</button>${p?`<div class="reply-context">Replying to <strong>@${View.esc(p.handle)}</strong><br>${View.esc(p.text.slice(0,110))}</div>`:''}<div class="modal-compose"><span class="avatar avatar-you">Y</span><div class="composer-body"><textarea id="modal-text" maxlength="280" placeholder="${replyId?'Post your reply':'What is happening?!'}" aria-label="${replyId?'Reply text':'Post text'}"></textarea><div class="composer-bottom"><div class="composer-tools"><button class="tool" data-tool="image" aria-label="Add image">${View.icon('image')}</button><button class="tool" data-tool="smile" aria-label="Add emoji">${View.icon('smile')}</button></div><div><span class="counter" id="modal-counter"></span><button class="post-button" id="modal-post" disabled>${replyId?'Reply':'Post'}</button></div></div><div id="modal-attachment"></div></div></div></section></div>`;$('#modal-text').focus();}
function updateText(el){const isModal=el.id==='modal-text';const btn=$(isModal?'#modal-post':'#inline-post');const counter=$(isModal?'#modal-counter':'#inline-counter');if(btn)btn.disabled=!el.value.trim();if(counter)counter.textContent=el.value.length?`${el.value.length}/280`:'';}
function addImage(){const input=document.createElement('input');input.type='file';input.accept='image/png,image/jpeg,image/gif,image/webp';input.onchange=()=>{const file=input.files[0];if(!file)return;if(file.size>700000){toast('Choose an image smaller than 700 KB for local storage.');return;}const reader=new FileReader();reader.onload=()=>{attachment=reader.result;const target=$(modal?'#modal-attachment':'#inline-attachment');if(target)target.innerHTML='<p class="muted">Image attached <button data-remove-image aria-label="Remove image">×</button></p>';};reader.readAsDataURL(file);};input.click();}
function postAction(type,id){const p=allPosts().find(x=>x.id===id);if(!p)return;
if(type==='reply'){openModal(id);return;}
if(type==='heart')toggle(state.liked,id);else if(type==='repeat')toggle(state.reposted,id);else if(type==='bookmark')toggle(state.saved,id);else if(type==='share'){const url=location.href.split('#')[0]+'#post/'+encodeURIComponent(id);if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(url).then(()=>toast('Link copied to clipboard.'),()=>toast('Unable to copy link.'));else toast('Copy the page URL to share this local demo.');return;}else if(type==='chart'){toast('View counts are sample data.');return;}else if(type==='menu'){toast('Post options are not available in this demo.');return;}
save();render();if(type==='bookmark')toast(state.saved.includes(id)?'Added to your bookmarks':'Removed from your bookmarks');
}
document.addEventListener('click',e=>{
const nav=e.target.closest('[data-nav]');if(nav){e.preventDefault();location.hash=nav.dataset.nav;if(page===nav.dataset.nav)go(page);return;}
const tab=e.target.closest('[data-tab]');if(tab){state.tab=tab.dataset.tab;save();render();return;}
const follow=e.target.closest('[data-follow]');if(follow){toggle(state.followed,follow.dataset.follow);save();render();return;}
const trend=e.target.closest('[data-trend]');if(trend){query=trend.dataset.trend;$('#search').value=query;go('explore');return;}
const action=e.target.closest('[data-action]');if(action){e.stopPropagation();postAction(action.dataset.action,action.dataset.id);return;}
const tool=e.target.closest('[data-tool]');if(tool){if(tool.dataset.tool==='image')addImage();else if(tool.dataset.tool==='smile'){const field=$(modal?'#modal-text':'#inline-text');if(field){field.value+=' 😊';updateText(field);field.focus();}}else toast('This composer tool is not implemented in the demo.');return;}
if(e.target.closest('[data-remove-image]')){attachment='';const target=$(modal?'#modal-attachment':'#inline-attachment');if(target)target.innerHTML='';return;}
if(e.target.closest('#inline-post')){publish($('#inline-text').value);return;}
if(e.target.closest('#modal-post')){publish($('#modal-text').value,modal&&modal.replyId);return;}
if(e.target.closest('#open-compose')||e.target.closest('#mobile-compose')){openModal();return;}
if(e.target.closest('[data-close]')||e.target.matches('[data-dismiss]')){closeModal();return;}
if(e.target.closest('[data-back]')){location.hash='home';go('home');return;}
if(e.target.closest('[data-refresh]')){window.scrollTo({top:0,behavior:'smooth'});toast('You’re all caught up.');return;}
if(e.target.closest('#more-trends')){moreTrends=!moreTrends;View.side(state,moreTrends,morePeople);return;}
if(e.target.closest('#more-people')){morePeople=!morePeople;View.side(state,moreTrends,morePeople);return;}
if(e.target.closest('#premium')){go('premium');return;}
if(e.target.closest('#account-button')){go('profile');return;}
const post=e.target.closest('[data-post]');if(post){go('detail',post.dataset.post);}
});
document.addEventListener('input',e=>{if(e.target.matches('#inline-text,#modal-text'))updateText(e.target);});
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&modal)closeModal();if(e.key==='Enter'&&e.target.id==='search'){query=e.target.value;go('explore');}else if(e.key==='Enter'&&e.target.matches('[data-post]'))go('detail',e.target.dataset.post);else if(e.key==='Enter'&&e.target.matches('[data-trend]')){query=e.target.dataset.trend;$('#search').value=query;go('explore');}});
function hashRoute(){const hash=decodeURIComponent(location.hash.slice(1));if(hash.startsWith('post/'))go('detail',hash.slice(5));else if(['home','explore','notifications','messages','bookmarks','communities','premium','profile','more'].includes(hash))go(hash);}
window.addEventListener('hashchange',hashRoute);render();hashRoute();
})();