document
.querySelectorAll('.event-card')
.forEach(card => {

card.addEventListener(
'click',
function(){

document
.querySelectorAll('.event-card')
.forEach(c=>{
c.classList.remove('active');
});

this.classList.add('active');

loadDiscussion(
this.dataset.event
);

});

});

function loadDiscussion(eventId){

let fd = new FormData();

fd.append('ajax',1);
fd.append('load_discussion',1);
fd.append('event_id',eventId);

fetch('',{
method:'POST',
body:fd
})

.then(res=>res.text())

.then(html=>{

document
.getElementById(
'discussionContent'
)
.innerHTML=html;

bindForms();

autoScroll();

});

}

function bindForms(){

let form =
document.getElementById(
'messageForm'
);

if(form){

form.addEventListener(
'submit',
function(e){

e.preventDefault();

sendForm(form);

});

}

document
.querySelectorAll('.reply-form')
.forEach(f=>{

f.addEventListener(
'submit',
function(e){

e.preventDefault();

sendForm(f);

});

});

bindImages();

}

function sendForm(form){

let fd = new FormData(form);

fd.append('ajax',1);
fd.append('send_message',1);

fetch('',{
method:'POST',
body:fd
})

.then(res=>res.text())

.then(res=>{

if(res=='slow_down'){

alert(
'Please wait before sending another message.'
);

return;

}

loadDiscussion(
fd.get('event_id')
);

});

}

function toggleReply(id){

let form =
document.getElementById(
'replyForm'+id
);

document
.querySelectorAll('.reply-form')
.forEach(f=>{
f.classList.add('hidden');
});

form.classList.toggle('hidden');

}

function bindImages(){

document
.querySelectorAll('.preview-image')
.forEach(img=>{

img.addEventListener(
'click',
function(){

document
.getElementById(
'imageModal'
)
.style.display='flex';

document
.getElementById(
'modalImage'
)
.src=this.src;

});

});

}

document
.getElementById(
'closeModal'
)
.addEventListener(
'click',
function(){

document
.getElementById(
'imageModal'
)
.style.display='none';

});

function autoScroll(){

let msgBox =
document.getElementById(
'messagesBox'
);

if(msgBox){

msgBox.scrollTop =
msgBox.scrollHeight;

}

}

setInterval(()=>{

let active =
document.querySelector(
'.event-card.active'
);

if(active){

loadDiscussion(
active.dataset.event
);

}

},5000);