let selectedFiles=[];
let selectedNums=[];
let allContacts=[];
let isSubmitting=false;

document.addEventListener('DOMContentLoaded',async()=>{
const statusInterval=setInterval(refreshFaxStatus,3000);
refreshFaxStatus();
window.addEventListener('beforeunload',()=>clearInterval(statusInterval));
await loadAllContacts();
const urlParams=new URLSearchParams(window.location.search);
const num=urlParams.get('num');
if(num&&getOnlyNumbers(num).length>0){
if(!selectedNums.includes(num)){
selectedNums.push(num);
renderNumList();
}
window.history.replaceState({},document.title,window.location.pathname);
}
});

function _L(k,fallback=''){return window.FAX_LANG?.[k]||fallback||k;}

async function loadAllContacts(){
try{
const csrfInput=document.getElementById('csrf_input');
const csrfToken=csrfInput?csrfInput.value:'';
if(!csrfToken)return;
const res=await fetch('include/service/contacts_list.php',{method:'POST',headers:{'X-CSRF-TOKEN':csrfToken,'Content-Type':'application/x-www-form-urlencoded'}});
if(!res.ok)throw new Error('Forbidden');
allContacts=await res.json();
if(selectedNums.length>0)renderNumList();
}catch(e){console.error(e);}
}

function renderNumList(){
const list=document.getElementById('num-list');
if(!list)return;
list.innerHTML='';
selectedNums.forEach((num,idx)=>{
const div=document.createElement('div');
div.className='item-badge';
const span=document.createElement('span');
span.textContent=getNameByNumber(num);
const closeBtn=document.createElement('span');
closeBtn.className='remove-btn';
closeBtn.textContent='×';
closeBtn.onclick=()=>{
selectedNums.splice(idx,1);
renderNumList();
};
div.appendChild(span);
div.appendChild(closeBtn);
list.appendChild(div);
});
}

function getNameByNumber(num){
const cleanNum=getOnlyNumbers(num);
const contact=allContacts.find(c=>getOnlyNumbers(c.fax)===cleanNum);
return contact?`📒 ${contact.name}`:num;
// 전화번호까지 나오게하려면...
// return contact?`${contact.name} (${num})`:num;
}

function addNumber(){
const input=document.getElementById('numInput');
if(!input)return;
let val=input.value.trim();
if(!val)return;
const matchedContact=allContacts.find(c=>c.name.trim()===val);
let finalNum=matchedContact?matchedContact.fax:val.replace(/[^0-9+\- ]/g,'');
if(getOnlyNumbers(finalNum).length>0){
if(!selectedNums.includes(finalNum)){
selectedNums.push(finalNum);
renderNumList();
}}
input.value='';
}

async function submitForm(){
if(isSubmitting)return;
const msgSelectFile=typeof tSelectFileMsg!=='undefined'?tSelectFileMsg:'Please select at least one file';
const msgEnterNum=typeof tEnterNumMsg!=='undefined'?tEnterNumMsg:'Please enter at least one fax number';
const msgConfirmSend=typeof tConfirmSendMsg!=='undefined'?tConfirmSendMsg:'Do you want to send this fax?';
const msgError=typeof tErrorMsg!=='undefined'?tErrorMsg:'Error occurred';
if(selectedFiles.length===0){modalAlert(msgSelectFile);return;}
if(selectedNums.length===0){modalAlert(msgEnterNum);return;}
modalConfirm(msgConfirmSend,async()=>{
if(isSubmitting)return;
isSubmitting=true;
const submitBtn=document.querySelector('.send-btn');
if(submitBtn)submitBtn.disabled=true;
const csrfToken=document.getElementById('csrf_input')?.value||'';
const form=document.getElementById('faxForm');
const formData=new FormData(form);
formData.set('csrf',csrfToken);
selectedFiles.forEach(f=>{formData.append('uploadedfile[]',f);});
formData.set('faxnumber',selectedNums.join(','));
try{
const res=await fetch('include/service/fax_send.php',{
method:'POST',
body:formData,
headers:{'X-CSRF-TOKEN':csrfToken}
});
const result=await res.json();
if(result.success){location.href='fax_send.php';
}else{modalAlert(result.message||'Transmission failed');}
}catch(e){console.error(e);modalAlert(msgError);
}finally{isSubmitting=false;if(submitBtn)submitBtn.disabled=false;}
});
}

function getOnlyNumbers(str){return str.replace(/[^0-9]/g,'');}

function handleFiles(input){
if(!input.files)return;
Array.from(input.files).forEach(file=>{
if(!selectedFiles.some(f=>f.name===file.name&&f.size===file.size)){selectedFiles.push(file);}
});
renderList('file-list',selectedFiles,removeFile);
input.value='';
}

function renderList(elementId,items,removeFn){
const list=document.getElementById(elementId);
if(!list)return;
list.innerHTML='';
items.forEach((item,idx)=>{
const div=document.createElement('div');
div.className='item-badge';
div.innerHTML=`<span>${item.name||item}</span>`;
const btn=document.createElement('span');
btn.className='remove-btn';
btn.textContent='×';
btn.onclick=()=>removeFn(idx);
div.appendChild(btn);
list.appendChild(div);
});
}

function removeFile(idx){selectedFiles.splice(idx,1);renderList('file-list',selectedFiles,removeFile);}

function openAddressBook(){
const body=`<div class="address-book-container"><input type="text" id="contactSearch" placeholder="${_L('keyword')}" onkeyup="filterContacts()" class="modal-input"><div id="contactListArea"></div></div>`;
const actions=`<button class="modal-btn danger half" onclick="addSelectedContacts()">${_L('selected')}</button><button class="modal-btn half" onclick="closeModal()">${_L('cancel')}</button>`;
openModal(_L('addressbook'),body,actions);
filterContacts();
}

function filterContacts(){
const searchInput=document.getElementById('contactSearch');
const query=searchInput?searchInput.value.toLowerCase():'';
const area=document.getElementById('contactListArea');
if(!area)return;
area.innerHTML='';
const txtPublic=typeof tPublicText!=='undefined'?tPublicText:'Public';
const txtUsers=typeof tUsersText!=='undefined'?tUsersText:'Users';
const filtered=allContacts.filter(c=>c.name.toLowerCase().includes(query)||c.fax.includes(query));
filtered.forEach((c,idx)=>{
const item=document.createElement('div');
const rowClass=(idx%2===0)?'row-alternate':'row-classic';
const isPublic=(c.origin==='public');
const badgeText=isPublic?txtPublic:txtUsers;
const badgeClass=isPublic?'badge-public':'badge-user';
item.className=`contact-item-row ${rowClass}`;
item.innerHTML=`<div style="display:flex;align-items:center;"><input type="checkbox" id="cb_${idx}" value="${c.fax}" style="margin-right:10px;"><div onclick="toggleContactCheck(${idx})" style="flex:1;"><div><span class="badge ${badgeClass}">${badgeText}</span> <strong>${c.name}</strong></div><div style="font-size:0.9em;color:var(--fax-date-color);">${c.fax}</div></div></div>`;
area.appendChild(item);
});
}

function addSelectedContacts(){
const checkboxes=document.querySelectorAll('#contactListArea input:checked');
checkboxes.forEach(cb=>{
if(getOnlyNumbers(cb.value).length>0&&!selectedNums.includes(cb.value)){selectedNums.push(cb.value);}
});
renderNumList();
if(typeof closeModal==='function'){
closeModal();
}else{
const legacyModal=document.getElementById('addressBookModal');
if(legacyModal)legacyModal.style.display='none';
}}

function toggleContactCheck(idx){
const cb=document.getElementById('cb_'+idx);
if(cb)cb.checked=!cb.checked;
}

function refreshFaxStatus(){
fetch('fax_send_status.php').then(r=>r.json()).then(data=>{
const el=document.querySelector('.fax-status-badge');
if(el&&data.label){
el.textContent=data.label;
el.style.color=data.color||'';
}
}).catch(()=>{});}
