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();
function prepareAudio(){try{audio??=new (window.AudioContext||window.webkitAudioContext)();audio.resume();}catch{}}
function chime(){if(!soundOn||!audio||audio.state!=='running')return;const t=audio.currentTime;for(const [offset,freq]of [[0,659.25],[.17,987.77]]){const o=audio.createOscillator(),g=audio.createGain();o.type='sine';o.frequency.value=freq;g.gain.setValueAtTime(0,t+offset);g.gain.linearRampToValueAtTime(.045,t+offset+.025);g.gain.exponentialRampToValueAtTime(.0001,t+offset+.65);o.connect(g);g.connect(audio.destination);o.start(t+offset);o.stop(t+offset+.7)}}
soundButton.onclick=()=>{soundOn=!soundOn;localStorage.setItem('alnode-sound',soundOn?'yes':'no');if(soundOn){prepareAudio();setTimeout(chime,60)}soundLabel()};document.addEventListener('pointerdown',()=>{if(soundOn)prepareAudio()},{once:true});
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('alnode-message-ids',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='';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=>`