import {memberAvatar} from './member-avatar.js';
const el=(tag,text='',cls='')=>{const n=document.createElement(tag);n.textContent=text;n.className=cls;return n;};
const link=(text,url,cls='')=>{const n=el('a',text,cls);n.href=url;return n;};
const action=(text,detail,cls='')=>{const n=el('button',text,cls);n.type='button';n.onclick=()=>dispatchEvent(new CustomEvent('zs:home-action',{detail}));return n;};
const brands={discord:'/assets/brand-discord.svg',youtube:'/assets/brand-youtube.svg',spotify:'/assets/brand-spotify.svg',github:'/assets/brand-github.svg',photopea:'/assets/brand-photopea.svg',wikipedia:'/assets/brand-wikipedia.svg',drive:'/assets/brand-googledrive.svg'};
const shapes={calculator:'',note:'',game:'',clock:'',tool:'',apps:''};
function glyph(kind){const n=el('span','','home-tile-glyph');n.innerHTML='';return n;}
export function homeHub(rpc,owner,db){
if(document.getElementById('home-hub'))return;
document.body.dataset.homeReady='true';
const hub=el('section','','home-hub');hub.id='home-hub';hub.setAttribute('aria-label','Home');
const welcome=el('header','','home-welcome'),identity=link('','/profile','home-identity'),fallback=memberAvatar(db,{display_name:'?'},{own:true,className:'member-avatar home-self-avatar'}),words=el('div');words.append(el('h1','Home'));identity.append(fallback,words);
welcome.append(identity);hub.append(welcome);
const search=el('form','','home-search'),searchInput=el('input');searchInput.type='search';searchInput.placeholder='Find a game, app, or tool';searchInput.setAttribute('aria-label','Search Zeyad’s Stuff');const searchButton=el('button','Search');searchButton.type='submit';search.append(searchInput,searchButton);search.onsubmit=e=>{e.preventDefault();dispatchEvent(new CustomEvent('zs:home-action',{detail:{section:'browse',query:searchInput.value}}));};hub.append(search);
const friends=el('section','','home-friends-section'),fh=el('div','','home-section-heading'),friendTitle=el('h2','Friends');fh.append(friendTitle,link('See all','/friends'));const friendsList=el('div','','home-friends-strip');friendsList.append(el('p','Loading friends…','muted'));friends.append(fh,friendsList);hub.append(friends);
function shelf(title,section,empty){const box=el('section','','home-shelf'),heading=el('div','','home-section-heading'),list=el('div','','home-game-row');heading.append(el('h2',title),action('See all',{section}));list.setAttribute('aria-label',title);box.append(heading,list);hub.append(box);return {box,list,empty};}
const shelves={recent:shelf('Continue','recent','No recent activity.'),games:shelf('Games','games','No games available.'),apps:shelf('Apps & tools','browse','Browse apps and tools in Discover.')};
document.querySelector('.library').before(hub);
let latestApps=[],latestRecent={};const thumbs=new Map();
function card(app){
const card=el('article','','home-game-card'),open=action('',{id:app.id},'home-game-open');open.setAttribute('aria-label','Open '+app.name);
const art=el('span','','home-game-art');art.style.setProperty('--game-tint',app.bg||'#30343b');const cover=thumbs.get(app.id)||brands[app.id];if(cover){const img=el('img');img.src=cover;img.alt='';img.loading='lazy';img.className=thumbs.has(app.id)?'home-game-cover':'home-game-brand';art.append(img);}else art.append(glyph(app.kind==='builtin'?app.icon:app.category==='games'?'game':'apps'));
art.append(el('span','▶','home-game-play'));open.append(art,el('strong',app.name));card.append(open);
const menu=el('details','','home-card-menu'),toggle=el('summary','•••');toggle.setAttribute('aria-label','Options for '+app.name);const more=el('div','','home-game-actions');more.append(action('Details',{details:app.id}));menu.append(toggle,more);if(app.kind==='shared-game'){const report=el('button','Report');report.type='button';report.setAttribute('aria-label','Report '+app.name);report.onclick=()=>dispatchEvent(new CustomEvent('zs:report-content',{detail:{kind:'game',id:app.gameId,title:app.name}}));more.append(report);}card.append(menu);return card;
}
function paint(shelf,items){shelf.box.hidden=!items.length;shelf.list.replaceChildren();for(const item of items.slice(0,6))shelf.list.append(card(item));}
function update({apps=latestApps,recent=latestRecent}={}){latestApps=apps;latestRecent=recent;const played=apps.filter(a=>recent[a.id]>0).sort((a,b)=>recent[b.id]-recent[a.id]);paint(shelves.recent,played);const games=apps.filter(a=>a.category==='games');paint(shelves.games,games);paint(shelves.apps,apps.filter(a=>a.category!=='games'&&!played.some(p=>p.id===a.id)));}
addEventListener('zs:hub-view',event=>update(event.detail));addEventListener('zs:local-change',event=>{if(event.detail?.key==='recent')update({recent:event.detail.value});});addEventListener('zs:game-thumbnail',event=>{thumbs.set(event.detail.id,event.detail.url);update();});update();
rpc('friends_list').then(rows=>{friendsList.replaceChildren();const accepted=rows.filter(r=>r.state==='accepted'),incoming=rows.filter(r=>r.state==='pending'&&!r.outgoing);friendTitle.textContent='Friends'+(accepted.length?' ('+accepted.length+')':'');const find=link('','/users','home-friend-bubble home-add-friend');find.append(el('span','+','member-avatar'),el('strong','Find friends'));if(!accepted.length)friendsList.append(find);for(const friend of accepted.slice(0,6)){const row=friend.username?link('','/users/'+encodeURIComponent(friend.username),'home-friend-bubble'):el('div','','home-friend-bubble');row.append(memberAvatar(db,friend),el('strong',friend.display_name||'Private member'));friendsList.append(row);}if(incoming.length)fh.append(link(incoming.length+(incoming.length===1?' request':' requests'),'/friends','home-request-count'));if(!accepted.length)friendsList.append(el('p','No friends added. Find profiles in People.','home-empty'));}).catch(()=>friendsList.replaceChildren(link('Open Friends','/friends')));
db.rpc('community_my_profile').then(({data,error})=>{const me=data?.[0];if(error||!me)return;fallback.replaceWith(memberAvatar(db,me,{own:true,className:'member-avatar home-self-avatar'}));words.querySelector('h1').textContent='Home';});
}