import {createClient} from '/account-base.js'; const $=id=>document.getElementById(id); const PAGE_SIZE=30; const ALL_VIEWS=['overview','accounts','reports','appeals','profiles','announcements','flags','staff','requests','activity']; let VIEWS=[...ALL_VIEWS]; let staffRole='member'; let client,offset=0,total=0,busy=false,selectedUser=null; let allReports=[]; const node=(tag,className='',value='')=>{ const el=document.createElement(tag); if(className)el.className=className; el.textContent=value; return el; }; function tell(value,error=false) { $('status').textContent=value; $('status').dataset.error=String(error); $('status').dataset.tone=error?'error':value.includes('Verifying')?'loading':value==='Dashboard data updated.'?'hidden':'quiet'; } function dateString(value) { if(!value)return 'Until manually lifted'; const date=new Date(value); return Number.isNaN(date.getTime())?'Unknown date':date.toLocaleString(); } async function rpc(name,args={}) { const {data,error}=await client.rpc(name,args); if(error)throw new Error(error.message||'Database request failed.'); return data; } async function run(action) { if(busy)return; busy=true; try{await action();} catch(error){tell(error instanceof Error?error.message:'Something went wrong.',true);} finally{busy=false;} } function button(value,handler,className=''){ const item=node('button',className,value); item.type='button'; item.addEventListener('click',()=>run(handler)); return item; } function viewName() { const requested=location.hash.replace(/^#/,''); return VIEWS.includes(requested)?requested:VIEWS[0]; } function openView(next,{focus=false}={}) { const name=VIEWS.includes(next)?next:VIEWS[0]; for(const view of VIEWS) { const tab=$('tab-'+view); const active=view===name; tab.setAttribute('aria-selected',String(active)); tab.tabIndex=active?0:-1; $('view-'+view).hidden=!active; if(active&&focus)tab.focus(); } if(location.hash!=='#'+name)history.replaceState(null,'','#'+name); } function initTabs(){ for(const name of ALL_VIEWS){ if(!VIEWS.includes(name)){$('tab-'+name).hidden=true;$('view-'+name).hidden=true;} } for(const [i,name] of VIEWS.entries()){ const tab=$('tab-'+name); tab.addEventListener('click',()=>openView(name)); tab.addEventListener('keydown',event=>{ if(!['ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End'].includes(event.key))return; event.preventDefault(); const index=event.key==='Home'?0:event.key==='End'?VIEWS.length-1: (i+(['ArrowRight','ArrowDown'].includes(event.key)?1:-1)+VIEWS.length)%VIEWS.length; openView(VIEWS[index],{focus:true}); }); } for(const action of document.querySelectorAll('[data-go]')){ action.addEventListener('click',()=>{ const view=action.dataset.go; if(view==='accounts'&&action.dataset.accountFilter){ $('filter').value=action.dataset.accountFilter; $('search').value=''; offset=0; run(loadAccounts); } openView(view); }); } window.addEventListener('hashchange',()=>openView(viewName())); openView(viewName()); } function updateBubble(id,count){ const item=$(id); item.hidden=!count; item.textContent=String(count); } function manageProfile(row) { $('bio-user').value=row.user_id; $('badge-user').value=row.user_id; $('moderate-user').value=row.user_id; openView('profiles'); tell('Selected '+row.email+' for profile moderation.'); } async function copyUserId(row){ try{ await navigator.clipboard.writeText(row.user_id); tell('User ID copied to clipboard.'); }catch{ tell('Clipboard access is unavailable. User ID: '+row.user_id); } } async function loadAccounts(){ const rows=await rpc('admin_list_accounts',{ p_search:$('search').value.trim(),p_filter:$('filter').value, p_offset:offset,p_page_size:PAGE_SIZE }); total=Number(rows[0]?.total_count??0); if(!rows.length&&offset>0){offset=Math.max(0,offset-PAGE_SIZE);return loadAccounts();} $('page-info').textContent='Page '+(Math.floor(offset/PAGE_SIZE)+1); $('previous').disabled=offset===0; $('next').disabled=offset+rows.length>=total; const container=$('account-list'); container.replaceChildren(); if(!rows.length){container.append(node('p','muted','No accounts match your search.'));return;} for(const row of rows){ const card=node('article','account-row'); const info=node('div','account-info'); const heading=node('div'); heading.append(node('span','account-email',row.email||'(email unavailable)')); const status=row.is_suspended?'suspended':row.status; heading.append(node('span','pill '+status,status)); if(row.is_owner)heading.append(node('span','pill','Owner')); info.append(heading, node('div','account-meta','Joined: '+dateString(row.created_at)), node('div','account-meta','User ID: '+row.user_id)); if(row.is_suspended){ info.append(node('div','account-meta','Suspended until: '+ dateString(row.suspended_until)+' · Reason: '+(row.suspension_reason||'Not specified'))); } const actions=node('div','account-actions'); actions.append( button('Manage profile',()=>manageProfile(row)), button('Copy ID',()=>copyUserId(row)) ); if(staffRole==='owner'&&!row.is_owner)actions.append(button('Manage role',()=>{ $('staff-user').value=row.user_id;openView('staff');tell('Choose a staff role for '+row.email+'.'); })); if(!row.is_owner){ if(row.is_suspended)actions.append(button('Unsuspend',()=>unsuspend(row))); else if(row.status==='approved')actions.append(button('Suspend',()=>openSuspend(row),'danger')); if(row.status==='pending')actions.append(button('Approve',()=>setAccess(row,'approved'),'primary')); if(row.status==='blocked')actions.append(button('Unblock',()=>setAccess(row,'approved'))); else actions.append(button('Block',()=>setAccess(row,'blocked'),'danger')); } card.append(info,actions); container.append(card); } } async function setAccess(row,nextStatus){ const action=nextStatus==='blocked'?'block':row.status==='blocked'?'unblock':'approve'; if(!confirm('Are you sure you want to '+action+' '+row.email+'?'))return; await rpc('review_access',{target_user:row.user_id,next_status:nextStatus}); await refresh(); tell('Account '+action+' completed.'); } function openSuspend(row){ selectedUser=row; $('suspend-target').textContent=row.email; $('suspend-reason').value=''; $('suspend-duration').value='24'; $('suspend-dialog').showModal(); } async function unsuspend(row){ if(!confirm('Restore access for '+row.email+'?'))return; await rpc('admin_unsuspend',{p_target:row.user_id}); await refresh(); tell('Suspension lifted.'); } async function loadStaff(){ const rows=await rpc('staff_list_roles'); const container=$('staff-list');container.replaceChildren(); if(!rows.length){container.append(node('p','muted','No staff roles assigned yet.'));return;} for(const entry of rows){ const card=node('article','account-row'); const details=node('div','account-info'); details.append(node('strong','',entry.email),node('p','account-meta',entry.role+' · '+entry.user_id)); const actions=node('div','account-actions'); actions.append(button('Edit',async()=>{ $('staff-user').value=entry.user_id;$('staff-role').value=entry.role; $('staff-user').focus(); })); actions.append(button('Revoke',async()=>{ if(!confirm('Revoke '+entry.role+' role from '+entry.email+'?'))return; await rpc('staff_set_role',{p_user:entry.user_id,p_role:null}); await loadStaff(); tell('Staff role revoked.'); },'danger')); card.append(details,actions);container.append(card); } } async function loadHistory(){ const events=await rpc('admin_moderation_history',{p_limit:50}); const container=$('history-list'); container.replaceChildren(); if(!events?.length){container.append(node('p','muted','No moderation actions yet.'));return;} for(const event of events){ const item=node('div','history-item'); const body=node('div'); body.append(node('div','history-action', event.action.replaceAll('-',' ')+' · '+(event.target_email||'Deleted account'))); if(event.reason)body.append(node('div','history-detail','Reason: '+event.reason)); if(event.action==='suspend')body.append(node('div','history-detail', 'Until: '+dateString(event.suspended_until))); item.append(body,node('time','history-detail',dateString(event.changed_at))); container.append(item); } } async function communityChange(operation,payload){ await rpc('community_admin',{p_operation:operation,p_payload:payload}); } function renderReports(){ const choice=$('report-filter').value; const matches=allReports.filter(report=> choice==='all'||(choice==='active'?['open','reviewing'].includes(report.state):report.state===choice)); const container=$('reports-list'); container.replaceChildren(); $('report-filter-count').textContent=matches.length+' shown (latest 50 loaded)'; if(!matches.length){container.append(node('p','muted','No reports in this category.'));return;} for(const report of matches){ const card=node('article','admin-report-card'); const header=node('div','admin-report-title'); header.append(node('strong','',`#${report.id} · ${report.content_kind||'profile'} · ${report.category}`),node('span','pill '+report.state,report.state.replaceAll('-',' '))); if(report.target){ const profileAction=button('Moderate reported profile',async()=>{ $('bio-user').value=report.target; $('badge-user').value=report.target; $('moderate-user').value=report.target; openView('profiles'); $('moderate-reason').focus(); tell('Selected reported user for moderation. Review evidence before taking action.'); }); header.append(profileAction); } card.append(header, node('p','report-details',report.details), node('p','report-meta','Reported: '+dateString(report.created_at)), node('p','report-meta','Target user: '+(report.target||'Unavailable')), node('p','report-meta','Reported by: '+report.reporter)); if(report.snapshot&&Object.keys(report.snapshot).length){const evidence=node('details','report-evidence');evidence.append(node('summary','','Content at time of report'),node('pre','',JSON.stringify(report.snapshot,null,2)));card.append(evidence);} if(report.content_kind==='game')card.append(button('Unpublish reported game',async()=>{const reason=note.value.trim();if(reason.length<10)throw Error('Enter a moderator note of at least 10 characters first.');await rpc('hub_hide_reported_game',{p_report:report.id,p_reason:reason});tell('Game unpublished. Review and save the report status separately.');})); const form=node('form','admin-report-form'); const statusLabel=node('label','','Status'); const select=document.createElement('select'); for(const [key,label] of [['open','Open'],['reviewing','Under review'],['resolved','Resolved'],['dismissed','Dismissed']]){ const opt=document.createElement('option');opt.value=key;opt.textContent=label;opt.selected=key===report.state;select.append(opt); } statusLabel.append(select); const noteLabel=node('label','','Private moderator note'); const note=document.createElement('input');note.maxLength=2000; note.placeholder='What action was taken?';note.value=report.staff_note||''; noteLabel.append(note); const save=node('button','primary','Save review');save.type='submit'; form.append(statusLabel,noteLabel,save); form.addEventListener('submit',event=>{ event.preventDefault(); run(async()=>{ await communityChange('review_report',{id:report.id,state:select.value,note:note.value}); await loadReports(); if(staffRole!=='moderator')await loadAudit(); tell('Report #'+report.id+' updated.'); }); }); card.append(form); container.append(card); } } async function loadAppeals(){ const rows=await rpc('admin_suspension_appeals',{p_limit:50}); const count=rows.filter(row=>['open','reviewing'].includes(row.state)).length; updateBubble('appeals-bubble',count); const container=$('appeals-list'); container.replaceChildren(); if(!rows.length){container.append(node('p','muted','No suspension appeals yet.'));return;} for(const appeal of rows){ const card=node('article','admin-report-card'); const heading=node('div','admin-report-title'); heading.append(node('strong','','Ticket #'+appeal.id+' · '+appeal.email), node('span','pill',appeal.state)); card.append(heading,node('p','report-details',appeal.message), node('p','report-meta','Submitted '+dateString(appeal.created_at)+' · Suspension until: '+dateString(appeal.suspension_until)), node('p','report-meta','User ID: '+appeal.user_id)); const form=node('form','admin-report-form'); const stateLabel=node('label','','Review status'); const state=document.createElement('select'); for(const key of ['open','reviewing','accepted','denied']){ const opt=document.createElement('option');opt.value=key;opt.textContent=key; opt.selected=appeal.state===key;state.append(opt); } stateLabel.append(state); const noteLabel=node('label','','Private staff note'); const note=document.createElement('input'); note.maxLength=2000;note.minLength=5;note.required=true; note.placeholder='Record why this decision was made…'; note.value=appeal.staff_note||''; noteLabel.append(note); const save=node('button','primary','Save decision');save.type='submit'; form.append(stateLabel,noteLabel,save); form.addEventListener('submit',event=>{ event.preventDefault(); run(async()=>{ await rpc('admin_review_suspension_appeal',{ p_id:appeal.id,p_state:state.value,p_note:note.value.trim() }); await loadAppeals(); if(staffRole!=='moderator')await loadAudit(); tell('Appeal ticket #'+appeal.id+' updated. Unsuspend separately if accepted.'); }); }); card.append(form); container.append(card); } } async function loadReports(){ allReports=await rpc('hub_content_reports',{p_staff:true,p_offset:0})||[]; const open=allReports.filter(row=>['open','reviewing'].includes(row.state)).length; $('report-count').textContent=allReports.length===50&&open?'≥'+open:String(open); updateBubble('reports-bubble',open); renderReports(); } function auditSummary(event){ let payload={}; try{payload=JSON.parse(event.subject||'{}');}catch{return event.action.replaceAll('_',' ');} const user=typeof payload.user_id==='string'?payload.user_id.slice(0,8)+'…':'unknown'; if(['assign_badge','remove_badge'].includes(event.action)) return (event.action==='assign_badge'?'Assigned':'Removed')+' '+(payload.code||'badge')+' · User '+user; if(event.action==='moderate_bio')return 'Moderated bio · User '+user; if(['clear_bio','clear_avatar','clear_banner','hide_profile'].includes(event.action))return event.action.replaceAll('_',' ')+' · User '+user; if(event.action==='review_report')return 'Reviewed report #'+(payload.id||'?')+' · '+(payload.state||'updated'); if(event.action==='set_flag')return 'Flag '+(payload.key||'updated')+' · '+(payload.enabled?'enabled':'disabled'); if(event.action==='announce')return 'Published announcement · '+(payload.title||'Untitled'); return event.action.replaceAll('_',' '); } async function loadAudit(){ const events=await rpc('community_admin_audit',{p_limit:50}); const container=$('community-audit');container.replaceChildren(); if(!events?.length){container.append(node('p','muted','No community actions yet.'));return;} for(const event of events){ const row=node('div','history-item'); row.append(node('span','history-action',auditSummary(event)), node('time','history-detail',dateString(event.created_at))); container.append(row); } } async function loadPublicConfig(){ const config=await rpc('community_public_config'); const announcements=$('active-announcements'); announcements.replaceChildren(); const active=Array.isArray(config?.announcements)?config.announcements:[]; if(!active.length)announcements.append(node('p','muted','No active announcements.')); for(const item of active){ const row=node('article','admin-compact-item'); const body=node('div'); body.append(node('strong','',item.title),node('p','',item.body)); row.append(body,node('span','admin-compact-label','ACTIVE')); announcements.append(row); } const flags=$('flags-list');flags.replaceChildren(); const entries=Object.entries(config?.flags||{}).sort(([a],[b])=>a.localeCompare(b)); if(!entries.length)flags.append(node('p','muted','No feature flags configured.')); for(const [key,enabled] of entries){ const row=node('div','admin-compact-item'); const label=node('div'); label.append(node('strong','',key),node('p','',enabled?'Enabled':'Disabled')); const btn=button('Edit',async()=>{ $('flag-key').value=key; $('flag-enabled').checked=Boolean(enabled); openView('flags'); $('flag-key').focus(); tell('Editing '+key+'. Save to apply changes.'); }); row.append(label,btn);flags.append(row); } } async function refresh(){ if(staffRole!=='moderator')await Promise.all([loadAccounts(),loadHistory()]); if(staffRole!=='moderator')try{ const stats=await rpc('admin_global_stats'); const row=stats?.[0]||{}; $('total-count').textContent=String(row.total_accounts??'—'); $('visible-count').textContent=String(row.approved_accounts??'—'); $('pending-count').textContent=String(row.pending_accounts??'—'); $('suspension-count').textContent=String(row.active_suspensions??'—'); $('blocked-count').textContent=String(row.blocked_accounts??'—'); updateBubble('pending-bubble',Number(row.pending_accounts||0)); }catch(error){ for(const id of ['total-count','visible-count','pending-count','suspension-count','blocked-count'])$(id).textContent='—'; tell('Account totals unavailable: '+error.message,true); } const jobs=[loadReports(),loadAppeals()]; if(staffRole!=='moderator')jobs.push(loadAudit()); if(staffRole==='owner')jobs.push(loadPublicConfig(),loadStaff()); const extras=await Promise.allSettled(jobs); const errors=extras.filter(result=>result.status==='rejected'); if(errors.length)tell(errors.length+' community section(s) could not refresh. Check the preview database.',true); else tell('Dashboard data updated.'); } function bindForms(){ $('staff-form').addEventListener('submit',event=>{ event.preventDefault(); if(staffRole!=='owner')return; run(async()=>{ const user=$('staff-user').value.trim(); const role=$('staff-role').value; if(!confirm('Assign '+role+' role to account '+user+'?'))return; await rpc('staff_set_role',{p_user:user,p_role:role}); await loadStaff(); tell('Staff role assigned. The account can now access authorized tools.'); }); }); $('filters').addEventListener('submit',event=>{event.preventDefault();offset=0;run(loadAccounts);}); $('filter').addEventListener('change',()=>{offset=0;run(loadAccounts);}); $('report-filter').addEventListener('change',renderReports); $('previous').addEventListener('click',()=>{offset=Math.max(0,offset-PAGE_SIZE);run(loadAccounts);}); $('next').addEventListener('click',()=>{if(offset+PAGE_SIZErun(refresh)); $('cancel-suspension').addEventListener('click',()=>$('suspend-dialog').close()); $('suspend-dialog').addEventListener('close',()=>{selectedUser=null;}); $('suspend-form').addEventListener('submit',event=>{ event.preventDefault(); if(!selectedUser)return; const target=selectedUser,reason=$('suspend-reason').value.trim(); const duration=$('suspend-duration').value; if(reason.length<5||reason.length>500)return tell('Suspension reasons must be 5–500 characters.',true); run(async()=>{ await rpc('admin_suspend',{p_target:target.user_id,p_reason:reason, p_hours:duration==='indefinite'?null:Number(duration)}); $('suspend-dialog').close(); await refresh(); tell('Account suspended.'); }); }); $('moderate-profile-form').addEventListener('submit',event=>{ event.preventDefault(); run(async()=>{ const user=$('moderate-user').value.trim(); const action=$('moderate-action').value; const reason=$('moderate-reason').value.trim(); if(reason.length<10||reason.length>500)return tell('A 10–500 character reason is required.',true); const labels={clear_bio:'clear the bio',clear_avatar:'remove the avatar', clear_banner:'remove the banner',hide_profile:'hide the profile'}; if(!labels[action])return tell('Select a valid moderation action.',true); if(!confirm('Are you sure you want to '+labels[action]+' for user '+user+'?'))return; await rpc('community_moderate_profile',{p_target:user,p_action:action,p_reason:reason}); $('moderate-reason').value=''; if(staffRole!=='moderator')await loadAudit(); tell('Profile moderation action applied and logged.'); }); }); $('bio-form').addEventListener('submit',event=>{ event.preventDefault(); run(async()=>{ const id=$('bio-user').value.trim(),bio=$('bio-value').value; if(!confirm('Replace the bio for '+id+'?'))return; await communityChange('moderate_bio',{user_id:id,bio}); if(staffRole!=='moderator')await loadAudit(); tell('Profile bio updated.'); }); }); $('badge-form').addEventListener('submit',event=>{ event.preventDefault(); const mode=event.submitter?.dataset.mode==='remove'?'remove_badge':'assign_badge'; run(async()=>{ await communityChange(mode,{user_id:$('badge-user').value.trim(),code:$('badge-code').value}); if(staffRole!=='moderator')await loadAudit(); tell(mode==='assign_badge'?'Badge assigned.':'Badge removed.'); }); }); $('announcement-form').addEventListener('submit',event=>{ event.preventDefault(); run(async()=>{ await communityChange('announce',{title:$('announcement-title').value.trim(), body:$('announcement-body').value.trim()}); $('announcement-form').reset(); await Promise.all([loadPublicConfig(),loadAudit()]); tell('Announcement saved in Supabase.'); }); }); $('flag-form').addEventListener('submit',event=>{ event.preventDefault(); run(async()=>{ await communityChange('set_flag',{key:$('flag-key').value.trim(),enabled:$('flag-enabled').checked}); await Promise.all([loadPublicConfig(),loadAudit()]); tell('Feature flag saved. It only changes behavior where explicitly enforced.'); }); }); } async function start(){ const configResponse=await fetch('/api/account/config',{cache:'no-store'}); if(!configResponse.ok)throw new Error('Could not load account configuration.'); const config=await configResponse.json(); if(!config.enabled)throw new Error('Accounts mode is not enabled.'); client=createClient(config.url,config.key,{auth:{ flowType:'pkce',detectSessionInUrl:false,persistSession:true,autoRefreshToken:true }}); const {data,error}=await client.auth.getSession(); if(error||!data.session){location.replace('/signin');return;} const response=await fetch('/api/account/session',{ method:'POST',headers:{authorization:'Bearer '+data.session.access_token} }); if(!response.ok){location.replace('/signin');return;} const {account,allowed}=await response.json(); if(!allowed){tell('An approved account is required.',true);return;} staffRole=await rpc('staff_my_role'); if(!['owner','administrator','moderator'].includes(staffRole)){tell('Staff access is required.',true);return;} VIEWS=staffRole==='owner'?[...ALL_VIEWS]:staffRole==='administrator'? ['overview','accounts','reports','appeals','profiles','requests','activity']: ['reports','appeals','profiles','requests']; document.querySelector('.admin-topline .eyebrow').textContent="ZEYAD'S STUFF / "+staffRole.toUpperCase()+" CONSOLE"; if(staffRole!=='owner'){ $('badge-form').closest('.admin-block').hidden=true; $('bio-form').closest('.admin-block').hidden=staffRole==='moderator'; } client.auth.onAuthStateChange((event,session)=>{ if(event==='SIGNED_OUT')location.replace('/signin'); if(event==='TOKEN_REFRESHED'&&session){ setTimeout(()=>fetch('/api/account/session',{method:'POST', headers:{authorization:'Bearer '+session.access_token}}).catch(()=>{}),0); } }); initTabs(); bindForms(); $('admin-layout').hidden=false; await refresh(); } start().catch(error=>tell(error instanceof Error?error.message:'Unable to load admin dashboard.',true));