/* 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="";
};

/* PWA + WebApp Check */
const isWebApp=
window.matchMedia('(display-mode: standalone)').matches||
window.navigator.standalone===true;
if(isWebApp){

/* Pull To Refresh */
const d=document,
app=d.getElementById('main'),
i=d.createElement('div');
Object.assign(i.style,{
position:'fixed',
top:0,
left:'50%',
width:'34px',
height:'34px',
borderRadius:'50%',
background:'rgba(255,255,255,.95)',
boxShadow:'0 2px 10px rgba(0,0,0,.12)',
zIndex:9999,
display:'flex',
alignItems:'center',
justifyContent:'center',
transform:'translateX(-50%) translateY(-80px)',
transition:'transform .25s cubic-bezier(.22,1,.36,1)',
backdropFilter:'blur(10px)',
WebkitBackdropFilter:'blur(10px)'
});
i.innerHTML='<div id=ptrSpinner style="width:18px;height:18px;border:2px solid #bbb;border-top-color:#333;border-radius:50%"></div>';
d.body.appendChild(i);
const s=i.firstChild;
let y=0,p=0,r=0;
const rs=v=>v**.85;
addEventListener('touchstart',e=>{if(!scrollY&&!r){y=e.touches[0].clientY;p=1;}},{passive:1});
addEventListener('touchmove',e=>{
if(!p||r)return;
if(document.getElementById('faxViewerModal')?.style.display==='block')return;
let m=e.touches[0].clientY-y;
if(m<=0)return;
m=Math.min(rs(m),120);
i.style.transition='none';
if(app)app.style.transition='none';
i.style.transform=`translateX(-50%) translateY(${m-80}px)`;
if(app){app.style.transform=`translateY(${m*.35}px)`;}
s.style.transform=`rotate(${m*3}deg)`;
},{passive:1});
addEventListener('touchend',()=>{if(!p||r)return;p=0;
const b=parseFloat((app?.style.transform||'').replace(/[^\d.-]/g,''))||0;
i.style.transition='transform .3s cubic-bezier(.22,1,.36,1)';
if(app){app.style.transition='transform .3s cubic-bezier(.22,1,.36,1)';}
if(b>=30){
r=1;
i.style.transform='translateX(-50%) translateY(12px)';
if(app){app.style.transform='translateY(20px)';}
s.style.animation='ptrSpin .7s linear infinite';
setTimeout(()=>location.reload(),400);
}else{i.style.transform='translateX(-50%) translateY(-80px)';
if(app){app.style.transform='translateY(0)';}}
});
}
