import {createClient} from '/account-base.js'; const $=id=>document.getElementById(id); let client; let busy=false; let currentSession=null; function formatDate(value){if(!value)return 'Indefinite โ€” until a staff member lifts it';const date=new Date(value);return Number.isFinite(date.getTime())?'Date unavailable':date.toLocaleString();} function remainingTime(value){if(!value)return 'Indefinite';const ms=new Date(value).getTime()-Date.now();if(!Number.isFinite(ms))return 'Unavailable';if(ms<=0)return 'Expired โ€” refresh account status';const days=Math.floor(ms/86400000);const hours=Math.ceil(ms%86400000/3600000);return [days?days+' day'+(days===1?'':'s'):null,hours?hours+' hour'+(hours===1?'':'s'):null].filter(Boolean).join(', ')||'Less than 1 hour';} async function rpc(name,args={}){const {data,error}=await client.rpc(name,args);if(error)throw new Error(error.message);return data;} async function loadAppeals(){const rows=await rpc('my_suspension_appeals',{p_limit:10});const list=$('appeal-history');list.replaceChildren();$('appeals-history-panel').hidden=!rows.length;if(!rows.length){const empty=document.createElement('p');empty.className='muted';empty.textContent='No appeals submitted.';list.append(empty);return;}for(const row of rows){const card=document.createElement('article');card.className='appeal-ticket';const title=document.createElement('strong');title.textContent='Ticket #'+row.id+' ยท '+row.state.replaceAll('_',' ');const time=document.createElement('small');time.textContent='Submitted '+formatDate(row.created_at);const summary=document.createElement('p');summary.textContent=row.message;card.append(title,time,summary);list.append(card);}const active=rows.some(row=>['open','reviewing'].includes(row.state));$('appeal-form').hidden=active;if(active)$('appeal-feedback').textContent='You already have an open appeal. Staff will review your ticket.';} async function loadSuspension(){const rows=await rpc('my_suspension');const suspension=rows?.[0];$('suspension-panel').hidden=!suspension?.active;if(!suspension?.active)return false;$('suspension-reason').textContent=suspension.reason;$('suspension-start').textContent=formatDate(suspension.suspended_at);$('suspension-end').textContent=formatDate(suspension.suspended_until);$('suspension-remaining').textContent=remainingTime(suspension.suspended_until);return true;} function message(value,error=false){const el=$('account-message');el.textContent=value;el.dataset.error=String(error);el.dataset.tone=error?'error':value.includes('Checking')?'loading':value.startsWith('Your account is ready')?'hidden':'quiet';} async function sync(session){ if(!session){location.replace('/signin');return;} const response=await fetch('/api/account/session',{method:'POST',headers:{authorization:'Bearer '+session.access_token},cache:'no-store'}); if(!response.ok)throw new Error('Unable to verify this account. Please sign in again.'); const data=await response.json(); const account=data.account; if(!account)throw new Error('Account information is unavailable.'); currentSession=session; $('account-identity').textContent=account.email; $('account-status').textContent=account.status==='approved'?'Approved':account.status==='blocked'?'Blocked':'Pending approval'; $('hub-links').hidden=false; $('open-site').hidden=!data.allowed; $('open-profile').hidden=!data.allowed; const role=data.allowed?await rpc('staff_my_role'):'member'; $('open-admin').hidden=!['owner','administrator','moderator'].includes(role); const suspended=account.status==='blocked' ? await loadSuspension() : false; if(!suspended)$('suspension-panel').hidden=true; await loadAppeals(); message(suspended?'Your account is suspended. See the reason and appeal options below.':data.allowed?'Your account is ready. Choose where you want to go.': account.status==='blocked'?'This account is blocked. Contact site staff if you believe this is an error.':'Your account is waiting for approval. You can refresh this page to check again.'); } async function start(){ const response=await fetch('/api/account/config',{cache:'no-store'}); if(!response.ok)throw new Error('Could not load account configuration.'); const config=await response.json(); if(!config.enabled)throw new Error('Account 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)throw error; await sync(data.session); client.auth.onAuthStateChange((event,session)=>{ if(event==='SIGNED_OUT'){location.replace('/signin');return;} if(event==='TOKEN_REFRESHED'&&session){ setTimeout(()=>sync(session).catch(error=>message(error.message,true)),0); } }); $('appeal-form').addEventListener('submit',async event=>{ event.preventDefault(); if(busy||!currentSession)return; const submit=$('appeal-submit'); busy=true;submit.disabled=true; try{ const messageText=$('appeal-message').value.trim(); if(messageText.length<20||messageText.length>2000)throw new Error('Enter 20โ€“2000 characters.'); const response=await fetch('/api/account/appeal',{method:'POST',headers:{ 'authorization':'Bearer '+currentSession.access_token,'content-type':'application/json' },body:JSON.stringify({message:messageText})}); const result=await response.json(); if(!response.ok)throw new Error(result.error||'Unable to submit appeal.'); $('appeal-message').value=''; $('appeal-feedback').textContent='Appeal ticket #'+result.ticket_id+' created. '+(result.discord_notified?'Staff were notified in Discord.':'Your ticket is saved for staff review in the admin dashboard.'); await loadAppeals(); }catch(error){$('appeal-feedback').textContent=error.message||'Unable to submit appeal.';} finally{busy=false;submit.disabled=false;} }); $('signout').addEventListener('click',async()=>{ if(busy)return;busy=true;$('signout').disabled=true; try{ const {error}=await client.auth.signOut({scope:'local'}); if(error)throw error; await fetch('/api/account/session',{method:'DELETE'}); location.replace('/signin'); }catch(error){message(error.message||'Unable to sign out.',true);busy=false;$('signout').disabled=false;} }); } start().catch(error=>message(error.message||'Unable to load the account hub.',true));