import {incoming} from '/notifications.js'; let soundOn=localStorage.getItem('alnode-sound')!=='no',audio=null,chatLastId=0,chatState='offline',chatPollBusy=false; const soundButton=document.createElement('button');soundButton.id='sound-toggle';soundButton.className='icon-button sound-toggle';soundButton.setAttribute('aria-label','Attiva o disattiva suoni');$('#refresh').before(soundButton); function soundLabel(){soundButton.textContent=soundOn?'♪':'♩';soundButton.classList.toggle('enabled',soundOn);soundButton.title=soundOn?'Suono attivo':'Attiva suono notifiche';soundButton.setAttribute('aria-pressed',String(soundOn))}soundLabel(); async function prepareAudio(){try{audio??=new (window.AudioContext||window.webkitAudioContext)();if(audio.state!=='running')await audio.resume();return audio.state==='running';}catch{return false}} async function chime(force=false){if(!soundOn&&!force)return;if(!await prepareAudio()){soundButton.title='Clicca per attivare l’audio';return;}const t=audio.currentTime+.025;const compressor=audio.createDynamicsCompressor();compressor.threshold.value=-8;compressor.knee.value=10;compressor.ratio.value=3;compressor.connect(audio.destination);for(const [offset,freq]of [[0,659.25],[.23,830.61],[.46,987.77]]){const o=audio.createOscillator(),g=audio.createGain();o.type='triangle';o.frequency.value=freq;g.gain.setValueAtTime(0,t+offset);g.gain.linearRampToValueAtTime(.24,t+offset+.02);g.gain.exponentialRampToValueAtTime(.0001,t+offset+.75);o.connect(g);g.connect(compressor);o.start(t+offset);o.stop(t+offset+.8);}setTimeout(()=>compressor.disconnect(),1700)} soundButton.onclick=async()=>{soundOn=!soundOn;localStorage.setItem('alnode-sound',soundOn?'yes':'no');soundLabel();if(soundOn)await chime();}; for(const event of ['pointerdown','keydown'])document.addEventListener(event,()=>{if(soundOn&&audio?.state!=='running')prepareAudio()},{passive:true}); const soundTest=document.createElement('button');soundTest.id='notification-test';soundTest.className='icon-button';soundTest.textContent='♬';soundTest.title='Prova notifica e suono';soundTest.setAttribute('aria-label','Prova notifica e suono');soundButton.after(soundTest);soundTest.onclick=async()=>{soundOn=true;localStorage.setItem('alnode-sound','yes');soundLabel();arrival('mail','Notifica di prova','Audio attivato · avviso per nuova posta o bollettini');await chime(true);soundTest.dataset.audioState=audio?.state||'unavailable';if(audio?.state!=='running')toast('Audio non attivato dal browser: verifica i permessi audio del sito.');}; const stack=document.createElement('div');stack.className='notification-stack';stack.setAttribute('aria-live','polite');document.body.append(stack); function arrival(kind,title,detail,ids=[]){const item=document.createElement('div');item.className='arrival-toast '+kind;item.innerHTML=`${kind==='mail'?'✉':'▤'}
${esc(title)}${esc(detail)}
`;item.querySelector('button').onclick=e=>{e.stopPropagation();item.remove()};item.onclick=()=>{navigate('bbs');if(ids.length===1)readMessage(ids[0]);item.remove()};stack.append(item);while(stack.children.length>4)stack.firstChild.remove();setTimeout(()=>item.remove(),12000)} let knownStation=null,knownIds;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null} const oldLoadMessages=loadMessages; loadMessages=async function(){await oldLoadMessages();if(!csrf||!allMessages.length)return;if(knownStation!==station.call){knownStation=station.call;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null}}const arrivals=incoming(allMessages,knownIds,station.call);const fresh=[...arrivals.bulletins,...arrivals.mail];knownIds=new Set(allMessages.map(m=>m.id));localStorage.setItem('bpq-message-ids-'+station.call,JSON.stringify([...knownIds]));if(fresh.length){const bulls=fresh.filter(m=>m.type==='B'),mail=fresh.filter(m=>m.type==='P'||m.type==='T');if(bulls.length)arrival('bulletin',bulls.length===1?'Nuovo bollettino scaricato':`${bulls.length} nuovi bollettini scaricati`,bulls.length===1?bulls[0].subject:'Disponibili nella BBS',bulls.map(m=>m.id));if(mail.length)arrival('mail',mail.length===1?'Nuova mail ricevuta':`${mail.length} nuove mail ricevute`,mail.length===1?'Da '+mail[0].from+' · '+mail[0].subject:'Disponibili nella posta personale',mail.map(m=>m.id));chime();}}; setInterval(()=>{if(csrf)loadMessages()},15000); const chatNav=document.createElement('button');chatNav.dataset.page='chat';chatNav.innerHTML='◇ Chat';chatNav.onclick=()=>navigate('chat');$('nav').append(chatNav); const chatPage=document.createElement('section');chatPage.id='chat';chatPage.className='page';chatPage.hidden=true;chatPage.innerHTML=`

Chat

Disconnesso
# General— presenti
◇

Chat BPQ

Connettiti con il tuo account per partecipare alla chat.

`;$('main').append(chatPage); const topicDialog=document.createElement('dialog');topicDialog.innerHTML='

Crea o apri una stanza

';document.body.append(topicDialog); const oldNavigate=navigate;navigate=function(next){oldNavigate(next);$('#breadcrumb').textContent='Stazione / '+({home:'Panoramica',bbs:'BBS',network:'Rete',chat:'Chat',winlink:'Winlink'}[next]);if(next==='chat')pollChat();window.scrollTo({top:0,behavior:'instant'})}; let chatFollowing=true,chatUnread=0,chatScrolling=false; const chatArea=$('#chat-messages');chatArea.tabIndex=0;chatArea.setAttribute('aria-label','Conversazione chat'); const chatJump=document.createElement('button');chatJump.id='chat-jump';chatJump.className='chat-jump';chatJump.hidden=true;chatJump.type='button';chatJump.setAttribute('aria-label','Vai agli ultimi messaggi');$('.chat-main').insertBefore(chatJump,$('#chat-form')); function updateChatJump(){chatJump.hidden=chatFollowing;chatJump.textContent=chatUnread?`${chatUnread} ${chatUnread===1?'nuovo messaggio':'nuovi messaggi'} ↓`:'Ultimi messaggi ↓';} function chatToBottom(){if(page!=='chat')return;chatFollowing=true;chatUnread=0;chatScrolling=true;updateChatJump();requestAnimationFrame(()=>{chatArea.scrollTop=chatArea.scrollHeight;requestAnimationFrame(()=>{chatScrolling=false;});});} chatJump.onclick=chatToBottom; chatArea.addEventListener('scroll',()=>{if(chatScrolling||page!=='chat')return;chatFollowing=chatArea.scrollHeight-chatArea.scrollTop-chatArea.clientHeight<64;if(chatFollowing)chatUnread=0;updateChatJump();},{passive:true}); new ResizeObserver(()=>{if(chatFollowing&&page==='chat')chatToBottom();}).observe(chatArea); const navigateWithChat=navigate;navigate=function(next){navigateWithChat(next);if(next==='chat'){if(chatFollowing)chatToBottom();else updateChatJump();}}; function renderChat(data){ chatState=data.state;const online=data.state==='online'; $('#chat-state').className='chat-status '+data.state;$('#chat-state').textContent=({offline:'Disconnesso',connecting:'Connessione…',online:'● Connesso · '+station.call,error:'Connessione interrotta'}[data.state]);$('#chat-connect').hidden=online;$('#chat-connect').disabled=data.state==='connecting';$('#chat-disconnect').hidden=!online;$('#chat-input').disabled=!online;$('#chat-send').disabled=!online;$('#chat-input').placeholder=online?'Scrivi alla stanza…':'Connettiti per scrivere…'; $('#chat-room-name').textContent='# '+data.topic;$('#chat-presence-count').textContent=online?data.users.filter(u=>u.topic.toLowerCase()===data.topic.toLowerCase()).length+' nella stanza':'Non connesso';$('#chat-user-count').textContent=online?data.users.length:'—'; $('#chat-users').innerHTML=online?data.users.map(u=>``).join('')||'

Nessun utente rilevato

':'

Connettiti per vedere chi è presente.

'; const recipient=$('#chat-recipient').value;$('#chat-recipient').innerHTML=''+data.users.filter(u=>u.call!==station.call).map(u=>``).join('');$('#chat-recipient').value=recipient;if(!$('#chat-recipient').value)$('#chat-recipient').value='';$('#chat-recipient').disabled=!online;if(online&&$('#chat-recipient').value)$('#chat-input').placeholder='Messaggio privato a '+$('#chat-recipient').value+'…'; $$('.chat-user').forEach(b=>b.onclick=()=>{$('#chat-recipient').value=b.dataset.call===station.call?'':b.dataset.call;$('#chat-input').placeholder=b.dataset.call===station.call?'Scrivi alla stanza…':'Messaggio privato a '+b.dataset.call+'…';$('#chat-input').focus();}); $('#chat-topics').innerHTML=[...new Set(['General',...data.topics,data.topic])].map(t=>``).join(''); $$('[data-topic]').forEach(b=>b.onclick=async()=>{try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:b.dataset.topic})});chatFollowing=true;chatUnread=0;pollChat();}catch(e){toast(e.message);}}); $('#chat-links').innerHTML=online?data.links.map(l=>``).join('')||'':''; const events=data.events.filter(e=>e.id>chatLastId),initial=chatLastId===0; if(events.length){if(chatArea.querySelector('.chat-empty'))chatArea.replaceChildren();const fragment=document.createDocumentFragment();let added=0; for(const event of events){chatLastId=Math.max(chatLastId,event.id);if(event.type==='system'&&/^[A-Z0-9]{3,6}(?:\s+[A-Z0-9]{3,6})*$/.test(event.text))continue; const element=document.createElement('div');if(event.type==='message'&&!/\*\*\* (?:Joined|Left)/i.test(event.text)){element.className='chat-event '+(event.sender===station.call?'own':'')+(event.to?' private':'');element.innerHTML=`
${esc(event.sender?.slice(0,2)||'?')}
${esc(event.sender)}${event.to?` → ${esc(event.to)} · privato`:''}

${esc(event.text)}

`;added++;}else{element.className='chat-system';element.textContent=(event.sender?event.sender+' · ':'')+event.text;}fragment.append(element);} chatArea.append(fragment);while(chatArea.children.length>300)chatArea.firstChild.remove(); if(initial||chatFollowing||events.some(e=>e.sender===station.call&&e.type==='message')){chatFollowing=true;if(page==='chat')chatToBottom();}else{chatUnread+=added;updateChatJump();} } } async function pollChat(){if(!csrf||chatPollBusy)return;chatPollBusy=true;try{renderChat(await api('/chat'))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}} $('#chat-connect').onclick=async()=>{try{chatLastId=0;chatFollowing=true;chatUnread=0;$('#chat-messages').innerHTML='';renderChat(await api('/chat/connect',{method:'POST',body:'{}'}))}catch(e){toast(e.message)}};$('#chat-disconnect').onclick=async()=>{try{await api('/chat/disconnect',{method:'POST',body:'{}'});pollChat()}catch(e){toast(e.message)}}; $('#chat-form').onsubmit=async e=>{e.preventDefault();const input=$('#chat-input'),button=$('#chat-send'),text=input.value.trim();if(!text)return;button.disabled=true;try{await api('/chat/send',{method:'POST',body:JSON.stringify({text,to:$('#chat-recipient').value})});input.value='';await pollChat()}catch(err){toast(err.message)}finally{button.disabled=chatState!=='online';input.focus()}}; $('#new-topic').onclick=()=>topicDialog.showModal();$('#topic-cancel').onclick=()=>topicDialog.close();$('#topic-form').onsubmit=async e=>{e.preventDefault();try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:$('#topic-name').value})});topicDialog.close();pollChat()}catch(err){toast(err.message)}}; setInterval(()=>{if(csrf&&(page==='chat'||chatState==='online'||chatState==='connecting'))pollChat()},2000); const presenceButton=document.createElement('button');presenceButton.className='secondary mobile-presence';presenceButton.textContent='Utenti';presenceButton.setAttribute('aria-expanded','false');presenceButton.onclick=()=>{const open=$('.chat-layout').classList.toggle('users-open');presenceButton.setAttribute('aria-expanded',String(open))};$('.chat-actions').prepend(presenceButton); $('#chat-recipient').addEventListener('change',()=>{$('#chat-input').placeholder=$('#chat-recipient').value?'Messaggio privato a '+$('#chat-recipient').value+'…':'Scrivi alla stanza…';}); if(location.hash==='#chat')navigate('chat'); window.addEventListener('DOMContentLoaded',()=>{for(const target of ['#bbs .mail-list-heading','#winlink .mail-list-heading']){const heading=$(target);if(heading){const tag=document.createElement('small');tag.className='mail-timezone';tag.textContent='Timezone: '+mailTimezone();heading.append(tag);}}}); function restoreMailPage(){const target=location.hash.slice(1);if(['home','bbs','winlink','chat','network','monitor'].includes(target)&&page!==target&&document.getElementById(target))navigate(target);} window.addEventListener('DOMContentLoaded',restoreMailPage);window.addEventListener('hashchange',restoreMailPage);