let appsPage=1,appsSearch='',appsFilter='';
function loadApps(){
  const el=document.getElementById('page-apps');
  el.innerHTML=`<div class="page-header"><div><h2>App Manager</h2><p>Manage your Android apps</p></div><div class="header-actions"><button class="btn btn-primary" onclick="openAppModal()">➕ Add New App</button></div></div>
  <div class="toolbar"><div class="search-bar"><span class="search-icon">🔍</span><input id="app-search" placeholder="Search apps..." oninput="appsSearch=this.value;appsPage=1;fetchApps()"></div>
  <div class="filter-group"><button class="filter-btn active" onclick="setAppFilter(this,'')">All</button><button class="filter-btn" onclick="setAppFilter(this,'active')">Active</button><button class="filter-btn" onclick="setAppFilter(this,'inactive')">Inactive</button></div></div>
  <div class="app-grid" id="apps-list"></div><div id="apps-pagination"></div>`;
  fetchApps();
}
function setAppFilter(btn,f){document.querySelectorAll('.filter-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');appsFilter=f;appsPage=1;fetchApps();}
function fetchApps(){
  api('get_apps',{search:appsSearch,status:appsFilter,page:appsPage},'GET').then(r=>{
    if(r.status!=='success')return;
    const el=document.getElementById('apps-list');
    if(!r.data.length){el.innerHTML='<div class="empty-state"><div class="empty-icon">📱</div><h3>No Apps Found</h3><p>Add your first app to get started</p><button class="btn btn-primary" onclick="openAppModal()">➕ Add New App</button></div>';document.getElementById('apps-pagination').innerHTML='';return;}
    el.innerHTML=r.data.map(a=>`<div class="app-card">
      <div class="app-card-header">
        <div class="app-card-logo">${a.app_logo_url?`<img src="${a.app_logo_url}" onerror="this.parentElement.innerHTML='📱'">`:'📱'}</div>
        <div class="app-card-info"><h3>${a.app_name}</h3><div class="pkg">${a.pkg_name}</div></div>
        <span class="badge badge-${a.app_status}">${a.app_status}</span>
      </div>
      <div class="app-card-body"><div class="app-card-meta">
        <span class="app-meta-item">v${a.app_version||'1.0.0'}</span>
        <span class="app-meta-item">📡 ${a.api_calls||0} calls</span>
        ${a.full_refer_link?`<span class="app-meta-item">🔗 Refer</span>`:''}
      </div></div>
      <div class="app-card-actions">
        <button class="btn btn-secondary btn-sm" onclick="editApp(${a.id})">✏️ Edit</button>
        <button class="btn btn-secondary btn-sm" onclick="duplicateApp(${a.id})">📋</button>
        <button class="btn btn-danger btn-sm" onclick="deleteApp(${a.id},'${a.app_name.replace(/'/g,"\\'")}')">🗑️</button>
      </div></div>`).join('');
    // Pagination
    let pg='';if(r.pages>1){pg='<div class="pagination">';for(let i=1;i<=r.pages;i++)pg+=`<button class="page-btn ${i===r.page?'active':''}" onclick="appsPage=${i};fetchApps()">${i}</button>`;pg+='</div>';}
    document.getElementById('apps-pagination').innerHTML=pg;
  });
}
function openAppModal(id=0){
  const title=id?'Edit App':'Add New App';
  const body=`<div class="tabs"><div class="tab active" onclick="switchTab(this,'tab-basic')">Basic</div><div class="tab" onclick="switchTab(this,'tab-notify')">Notifications</div><div class="tab" onclick="switchTab(this,'tab-popup')">Popup</div><div class="tab" onclick="switchTab(this,'tab-ads')">Ads</div><div class="tab" onclick="switchTab(this,'tab-extra')">Extra</div></div>
  <form id="app-form" onsubmit="saveApp(event)"><input type="hidden" name="id" value="${id}">
  <div class="tab-panel active" id="tab-basic">
    <div class="form-row"><div class="form-group"><label>Package Name *</label><input name="pkg_name" required placeholder="com.example.app"></div><div class="form-group"><label>App Name *</label><input name="app_name" required placeholder="My App"></div></div>
    <div class="form-group"><label>App Domain</label><input name="app_domain" placeholder="https://myappdomain.com"><div class="hint">Leave empty to use default main domain</div></div>
    <div class="form-group"><label>WhatsApp Channel Link</label><input name="whatsapp_link" placeholder="https://whatsapp.com/channel/..."></div>
    <div class="form-group"><label>Refer Link Path</label><input name="refer_link" placeholder="/?=lol123"><div class="hint">This will be combined with the main domain from Settings</div></div>
    <div class="form-row"><div class="form-group"><label>Version</label><input name="app_version" value="1.0.0"></div><div class="form-group"><label>Status</label><select name="app_status"><option value="active">Active</option><option value="inactive">Inactive</option><option value="maintenance">Maintenance</option></select></div></div>
    <div class="form-group"><label>App Logo</label><div class="upload-zone" id="logo-zone"><div class="upload-icon">📤</div><p>Click or drag to upload logo</p><input type="file" accept="image/*" onchange="uploadLogo(this.files[0])"><div class="upload-preview" id="logo-preview"></div><div class="upload-progress" id="logo-progress" style="display:none"><div class="progress-bar"><div class="progress-fill" id="logo-progress-fill"></div></div><div class="progress-text" id="logo-progress-text">0%</div></div></div><input type="hidden" name="app_logo" id="app-logo-field"></div>
    <div class="form-group"><label>Description</label><textarea name="app_description" placeholder="App description..."></textarea></div>
  </div>
  <div class="tab-panel" id="tab-notify">
    <div class="form-group"><label>Notification Title</label><input name="notification_title"></div>
    <div class="form-group"><label>Notification Body</label><textarea name="notification_body"></textarea></div>
    <div class="form-group"><label>Notification Image URL</label><input name="notification_image"></div>
    <div class="form-group"><label>Notification URL</label><input name="notification_url"></div>
  </div>
  <div class="tab-panel" id="tab-popup">
    <div class="form-group"><label class="checkbox"><input type="checkbox" name="popup_enabled" value="1"> Enable Popup</label></div>
    <div class="form-group"><label>Popup Title</label><input name="popup_title"></div>
    <div class="form-group"><label>Popup Message</label><textarea name="popup_message"></textarea></div>
    <div class="form-row"><div class="form-group"><label>Button Text</label><input name="popup_button_text" value="OK"></div><div class="form-group"><label>Button URL</label><input name="popup_button_url"></div></div>
    <div class="form-group"><label>Popup Image URL</label><input name="popup_image"></div>
  </div>
  <div class="tab-panel" id="tab-ads">
    <div class="form-group"><label class="checkbox"><input type="checkbox" name="ads_enabled" value="1"> Enable Ads</label></div>
    <div class="form-group"><label>Ad Network</label><select name="ad_network"><option value="none">None</option><option value="admob">AdMob</option><option value="facebook">Facebook</option><option value="unity">Unity</option><option value="applovin">AppLovin</option></select></div>
    <div class="form-group"><label>Interstitial Ad ID</label><input name="interstitial_ad_id"></div>
    <div class="form-group"><label>Banner Ad ID</label><input name="banner_ad_id"></div>
    <div class="form-group"><label>Rewarded Ad ID</label><input name="rewarded_ad_id"></div>
    <div class="form-group"><label>Native Ad ID</label><input name="native_ad_id"></div>
  </div>
  <div class="tab-panel" id="tab-extra">
    <div class="form-row"><div class="form-group"><label>Min Version</label><input name="min_version" value="1.0.0"></div><div class="form-group"><label class="checkbox" style="margin-top:24px"><input type="checkbox" name="force_update" value="1"> Force Update</label></div></div>
    <div class="form-group"><label>Update URL</label><input name="update_url" placeholder="https://play.google.com/..."></div>
    <div class="form-group"><label>Custom JSON Data</label><textarea name="custom_data" placeholder='{"key":"value"}'></textarea></div>
  </div></form>`;
  const footer=`<button class="btn btn-secondary" onclick="closeModal()">Cancel</button><button class="btn btn-primary" onclick="document.getElementById('app-form').requestSubmit()">💾 Save App</button>`;
  openModal(title,body,footer);
  if(id)api('get_app',{id},'GET').then(r=>{if(r.status==='success')populateAppForm(r.data);});
}
function switchTab(btn,tabId){btn.parentElement.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));btn.classList.add('active');btn.closest('.modal-body,.page').querySelectorAll('.tab-panel').forEach(p=>p.classList.remove('active'));document.getElementById(tabId).classList.add('active');}
function populateAppForm(d){
  const f=document.getElementById('app-form');if(!f)return;
  ['pkg_name','app_name','app_domain','whatsapp_link','refer_link','app_version','app_description','notification_title','notification_body','notification_image','notification_url','popup_title','popup_message','popup_button_text','popup_button_url','popup_image','interstitial_ad_id','banner_ad_id','rewarded_ad_id','native_ad_id','update_url','min_version'].forEach(k=>{if(f.elements[k])f.elements[k].value=d[k]||'';});
  if(f.elements.app_status)f.elements.app_status.value=d.app_status||'active';
  if(f.elements.ad_network)f.elements.ad_network.value=d.ad_network||'none';
  if(f.elements.popup_enabled)f.elements.popup_enabled.checked=d.popup_enabled==1;
  if(f.elements.ads_enabled)f.elements.ads_enabled.checked=d.ads_enabled==1;
  if(f.elements.force_update)f.elements.force_update.checked=d.force_update==1;
  if(d.custom_data)f.elements.custom_data.value=typeof d.custom_data==='string'?d.custom_data:JSON.stringify(d.custom_data,null,2);
  if(d.app_logo){document.getElementById('app-logo-field').value=d.app_logo;const prev=document.getElementById('logo-preview');if(d.app_logo_url)prev.innerHTML=`<img src="${d.app_logo_url}">`;}
}
function uploadLogo(file){
  if(!file)return;
  const prog=document.getElementById('logo-progress');const fill=document.getElementById('logo-progress-fill');const txt=document.getElementById('logo-progress-text');
  prog.style.display='block';
  const xhr=new XMLHttpRequest();const fd=new FormData();fd.append('action','upload_logo');fd.append('logo',file);
  xhr.upload.onprogress=e=>{if(e.lengthComputable){const pct=Math.round(e.loaded/e.total*100);fill.style.width=pct+'%';txt.textContent=pct+'%';}};
  xhr.onload=()=>{const r=JSON.parse(xhr.responseText);if(r.status==='success'){document.getElementById('app-logo-field').value=r.filename;document.getElementById('logo-preview').innerHTML=`<img src="${r.url}">`;toast('Logo uploaded!');}else{toast(r.message,'error');}prog.style.display='none';};
  xhr.onerror=()=>{toast('Upload failed','error');prog.style.display='none';};
  xhr.open('POST',API);xhr.send(fd);
}
function saveApp(e){
  e.preventDefault();const fd=new FormData(e.target);
  const data={};fd.forEach((v,k)=>data[k]=v);
  if(!data.popup_enabled)data.popup_enabled='0';if(!data.ads_enabled)data.ads_enabled='0';if(!data.force_update)data.force_update='0';
  api('save_app',data).then(r=>{if(r.status==='success'){toast(r.message);closeModal();fetchApps();}else toast(r.message,'error');});
}
function editApp(id){openAppModal(id);}
function deleteApp(id,name){openModal('Delete App',`<div class="confirm-dialog"><div class="confirm-icon">⚠️</div><h3>Delete "${name}"?</h3><p>This cannot be undone.</p><div class="confirm-actions"><button class="btn btn-secondary" onclick="closeModal()">Cancel</button><button class="btn btn-danger" onclick="confirmDeleteApp(${id})">🗑️ Delete</button></div></div>`,'');}
function confirmDeleteApp(id){api('delete_app',{id}).then(r=>{toast(r.message,r.status==='success'?'success':'error');closeModal();fetchApps();});}
function duplicateApp(id){api('duplicate_app',{id}).then(r=>{toast(r.message,r.status==='success'?'success':'error');fetchApps();});}
