/* DOM READY */
document.addEventListener('DOMContentLoaded',()=>{


/* MENU TOGGLE */
const menuToggle=document.getElementById('menuToggle');
const menu=document.getElementById('menu');
let menuBackdrop=document.getElementById('menuBackdrop');
if(!menuBackdrop){
menuBackdrop=document.createElement('div');
menuBackdrop.id='menuBackdrop';
Object.assign(menuBackdrop.style,{
position:'fixed',
top:0,
left:0,
width:'100%',
height:'100%',
background:'rgba(0,0,0,0.5)',
zIndex:2000,
display:'none'
});
document.body.appendChild(menuBackdrop);
}
if(menuToggle&&menu){menuToggle.onclick=()=>{const isShow=menu.classList.toggle('show');menuBackdrop.style.display=isShow?'block':'none';};}
menuBackdrop.onclick=()=>{menu.classList.remove('show');menuBackdrop.style.display='none';};


/* NAVIGATION SHORTCUT & ESC */
window.addEventListener('keydown',e=>{
if(e.key==='ArrowLeft'&&window.prevPage){location.href=(window.pageBaseUrl||'')+window.prevPage;
}else if(e.key==='ArrowRight'&&window.nextPage){location.href=(window.pageBaseUrl||'')+window.nextPage;}});


/* PUSH Button */
const pushBtn=document.getElementById("pushMainBtn");
if(pushBtn){pushBtn.addEventListener("click",openPushDialog);}


/* Download Popup */
document.addEventListener('click',function(e){
const anchor=e.target.closest('a');
if(!anchor||!anchor.href)return;
const fileUrl=anchor.href;
const targets=['download_file_inbox.php','download_file_outbox.php','download_folder_inbox.php','download_folder_outbox.php'];
const urlPath=fileUrl.split('?')[0];
if(!targets.some(t=>urlPath.endsWith(t)))return;
e.preventDefault();
const urlObj=new URL(fileUrl,window.location.origin);
const urlParams=urlObj.searchParams;
const isFolder=urlPath.includes('folder')||urlParams.has('folder');
let fileNameRaw=urlParams.get('fax')||urlParams.get('folder')||'document';
let extension='';
if(isFolder){extension='zip';}
else{
const type=urlParams.get('type')||'pdf';
extension=(type==='tiff'||type==='tif')?'tiff':'pdf';
}
const finalFileName=fileNameRaw.toLowerCase().endsWith('.'+extension)?fileNameRaw:`${fileNameRaw}.${extension}`;
fetch(fileUrl).then(r=>{if(!r.ok)throw new Error('fail');return r.blob();}).then(blob=>{
const blobUrl=window.URL.createObjectURL(blob);
const tempAnchor=document.createElement('a');
tempAnchor.style.display='none';
tempAnchor.href=blobUrl;
tempAnchor.download=finalFileName;
document.body.appendChild(tempAnchor);
tempAnchor.click();
setTimeout(()=>{window.URL.revokeObjectURL(blobUrl);document.body.removeChild(tempAnchor);},150);
}).catch(err=>{
console.error('Download error:',err);
alert(window.FAX_LANG?.download_error||'Download error');
});
});


/* PUSH Modal */
document.addEventListener("click",function(e){
if(e.target.id==="btnPushRegister")registerPush();
if(e.target.id==="btnPushTest")testPush();
});
function openPushDialog(){
const body=`<p>${FAX_LANG.pushDesc}</p>`;
const actions=`<button class="modal-btn danger half" id="btnPushRegister">${FAX_LANG.pushRegister}</button><button class="modal-btn half" id="btnPushTest">${FAX_LANG.pushTest}</button>`;
openModal(FAX_LANG.pushTitle,body,actions);
}
async function registerPush(){
if(!('serviceWorker'in navigator)||!('PushManager'in window)){modalAlert(FAX_LANG.pushNotSupported);return;}
const permission=await Notification.requestPermission();
if(permission!=="granted"){modalAlert(FAX_LANG.pushNeedPermission);return;}
await navigator.serviceWorker.register('/sw.js');
const registration=await navigator.serviceWorker.ready;
const existing=await registration.pushManager.getSubscription();
if(existing){modalAlert(FAX_LANG.pushAlready);return;}
const publicKey=window.PUSH_CONFIG?.publicKey;
if(!publicKey){modalAlert("Push public key not configured");return;}
function urlBase64ToUint8Array(base64String){
const padding='='.repeat((4-base64String.length%4)%4);
const base64=(base64String+padding).replace(/-/g,'+').replace(/_/g,'/');
const rawData=window.atob(base64);
const outputArray=new Uint8Array(rawData.length);
for(let i=0;i<rawData.length;++i){
outputArray[i]=rawData.charCodeAt(i);
}
return outputArray;
}
const subscription=await registration.pushManager.subscribe({
userVisibleOnly:true,
applicationServerKey:urlBase64ToUint8Array(publicKey)
});
await fetch('/include/plugin/push.subscribe.php',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify(subscription)
});
closeModal();
modalAlert(FAX_LANG.pushSuccess);
}
async function testPush(){
const registration=await navigator.serviceWorker.ready;
const subscription=await registration.pushManager.getSubscription();
if(!subscription){modalAlert("Push not registered");return;}
const res=await fetch('/include/plugin/push.test.php',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify(subscription)
});
const txt=await res.text();
closeModal();
if(txt.trim()==="ok"){
modalAlert(FAX_LANG.pushTestSuccess);
}else{
modalAlert(FAX_LANG.pushTestFail);
}}
});

/* Fax View Modal */
window.openFaxViewer=function(url){
const modal=document.getElementById('faxViewerModal');
const display=document.getElementById('faxViewerDisplay');
if(!modal||!display)return;
display.innerHTML='<object data="'+url+'#view=FitH" type="application/pdf" width="100%" height="100%"><p>This browser does not support PDF files</p></object>';
modal.style.display="block";
document.body.style.overflow="hidden";
};
window.closeFaxViewer=function(){
const modal=document.getElementById('faxViewerModal');
const display=document.getElementById('faxViewerDisplay');
if(display)display.innerHTML='';
if(!modal)return;
modal.style.display="none";
document.body.style.overflow="";
};
