const API=(location.hostname==='localhost'||location.hostname==='127.0.0.1')?'':'http://127.0.0.1:5180';const devicesEl=document.querySelector('#devices'),guidance=document.querySelector('#guidance'),refresh=document.querySelector('#refresh'),apk=document.querySelector('#apk'),dropzone=document.querySelector('#dropzone'),fileName=document.querySelector('#fileName'),install=document.querySelector('#install'),statusEl=document.querySelector('#status');let selectedDevice=null;
const labels={authorized:'Ready',unauthorized:'Authorization needed',offline:'Offline',unavailable:'Unavailable'};
function updateInstall(){install.disabled=!(selectedDevice?.state==='authorized'&&apk.files.length)}
function setStatus(text,type=''){statusEl.textContent=text;statusEl.className='status '+type}
async function loadDevices(){refresh.disabled=true;devicesEl.innerHTML='<div class="empty"><div class="spinner"></div><strong>Checking for phones…</strong></div>';guidance.classList.add('hidden');selectedDevice=null;updateInstall();try{const response=await fetch(API+'/api/devices');const data=await response.json();if(!response.ok)throw new Error(data.error);if(!data.devices.length){devicesEl.innerHTML='<div class="empty"><strong>No phone detected.</strong>&nbsp; Connect it by USB, then refresh.</div>';showGuide('Enable Developer Options by tapping Build number seven times, then enable USB debugging and reconnect the cable.');return}devicesEl.innerHTML='';data.devices.forEach((d,i)=>{const button=document.createElement('button');button.className=`device ${d.state}`;button.innerHTML=`<i class="dot"></i><span><strong>${escapeHtml(d.name)}</strong><small>${escapeHtml(d.serial)}</small></span><span class="state">${labels[d.state]}</span>`;button.onclick=()=>selectDevice(d,button);devicesEl.append(button);if(i===0)selectDevice(d,button)})}catch(e){devicesEl.innerHTML='<div class="empty"><strong>Windows companion not connected.</strong></div>';showGuide('Download and run the DroidPirate Windows Companion, then click Refresh.');setStatus('The installer page cannot reach the local Windows companion.','error')}finally{refresh.disabled=false}}
function selectDevice(device,button){selectedDevice=device;document.querySelectorAll('.device').forEach(x=>x.classList.remove('selected'));button.classList.add('selected');if(device.state==='unauthorized')showGuide('Unlock your phone, accept “Allow USB debugging?”, then click Refresh.');else if(device.state==='offline')showGuide('Reconnect the USB cable, unlock the phone, and click Refresh.');else guidance.classList.add('hidden');updateInstall()}
function showGuide(text){guidance.textContent=text;guidance.classList.remove('hidden')}
function chosen(){const f=apk.files[0];fileName.textContent=f?`${f.name} • ${formatSize(f.size)}`:'Android application package (.apk)';updateInstall()}
async function doInstall(){const f=apk.files[0];if(!f||!selectedDevice)return;install.disabled=true;install.textContent='Installing…';setStatus(`Sending ${f.name} directly to your phone through the local companion…`);const body=new FormData();body.append('serial',selectedDevice.serial);body.append('apk',f);try{const response=await fetch(API+'/api/install',{method:'POST',headers:{'X-DroidPirate-Companion':'1'},body});const data=await response.json();if(!response.ok)throw new Error(data.error);setStatus(data.message,'success')}catch(e){setStatus(e.message,'error')}finally{install.textContent='Install APK';updateInstall()}}
function escapeHtml(s){const d=document.createElement('div');d.textContent=s;return d.innerHTML}function formatSize(n){return n>1048576?(n/1048576).toFixed(1)+' MB':Math.ceil(n/1024)+' KB'}
refresh.onclick=loadDevices;apk.onchange=chosen;install.onclick=doInstall;['dragenter','dragover'].forEach(n=>dropzone.addEventListener(n,e=>{e.preventDefault();dropzone.classList.add('drag')}));['dragleave','drop'].forEach(n=>dropzone.addEventListener(n,e=>{e.preventDefault();dropzone.classList.remove('drag')}));dropzone.addEventListener('drop',e=>{const f=e.dataTransfer.files[0];if(f?.name.toLowerCase().endsWith('.apk')){const dt=new DataTransfer();dt.items.add(f);apk.files=dt.files;chosen()}else setStatus('Please choose an .apk file.','error')});loadDevices();
