function loadSettings(){
  const el=document.getElementById('page-settings');
  el.innerHTML=`<div class="page-header"><div><h2>⚙️ Settings</h2><p>Global configuration</p></div><div class="header-actions"><button class="btn btn-primary" onclick="saveSettings()">💾 Save Settings</button></div></div><div class="settings-grid" id="settings-list"><div class="spinner"></div></div>`;
  api('get_settings',{},'GET').then(r=>{
    if(r.status!=='success')return;
    const el=document.getElementById('settings-list');
    el.innerHTML=r.data.map(s=>`<div class="setting-item">
      <div class="setting-info"><div class="setting-label">${s.setting_key.replace(/_/g,' ').replace(/\b\w/g,c=>c.toUpperCase())}</div><div class="setting-desc">${s.description||''}</div></div>
      <div class="setting-input">${s.setting_type==='boolean'?`<label class="toggle"><input type="checkbox" data-key="${s.setting_key}" ${s.setting_value==='1'?'checked':''}><span class="toggle-slider"></span></label>`:
      `<input data-key="${s.setting_key}" value="${s.setting_value||''}" placeholder="${s.setting_key==='main_domain'?'pakclub24.club':''}">`}</div></div>`).join('');
  });
}
function saveSettings(){
  const data={};
  document.querySelectorAll('#settings-list [data-key]').forEach(el=>{data[el.dataset.key]=el.type==='checkbox'?(el.checked?'1':'0'):el.value;});
  api('save_settings',{settings:JSON.stringify(data)}).then(r=>{toast(r.message,r.status==='success'?'success':'error');});
}
function loadApiKeys(){
  const el=document.getElementById('page-api-keys');
  el.innerHTML=`<div class="page-header"><div><h2>🔑 API Keys</h2><p>Manage API access keys</p></div><div class="header-actions"><button class="btn btn-primary" onclick="createApiKey()">➕ New Key</button></div></div><div id="keys-list"></div>`;
  fetchApiKeys();
}
function fetchApiKeys(){
  api('get_api_keys',{},'GET').then(r=>{
    if(r.status!=='success')return;
    document.getElementById('keys-list').innerHTML='<div class="table-wrapper"><table><tr><th>Name</th><th>Key</th><th>Rate Limit</th><th>Status</th><th>Actions</th></tr>'+
    r.data.map(k=>`<tr><td>${k.key_name}</td><td><code style="font-size:11px;word-break:break-all;background:rgba(255,165,0,0.08);padding:2px 6px;border-radius:4px;color:#FFA500">${k.api_key}</code> <button class="copy-btn" onclick="navigator.clipboard.writeText('${k.api_key}');toast('Copied!')">📋</button></td>
    <td>${k.rate_limit}/min</td><td><span class="badge ${k.is_active==1?'badge-active':'badge-inactive'}">${k.is_active==1?'Active':'Disabled'}</span></td>
    <td><button class="btn btn-secondary btn-sm" onclick="toggleApiKey(${k.id})">⏯️</button><button class="btn btn-danger btn-sm" onclick="deleteApiKey(${k.id})">🗑️</button></td></tr>`).join('')+'</table></div>';
  });
}
function createApiKey(){
  openModal('New API Key',`<div class="form-group"><label>Key Name</label><input id="new-key-name" placeholder="My App Key"></div><div class="form-group"><label>Rate Limit (per min)</label><input id="new-key-limit" type="number" value="100"></div>`,
  `<button class="btn btn-secondary" onclick="closeModal()">Cancel</button><button class="btn btn-primary" onclick="submitApiKey()">Create</button>`);
}
function submitApiKey(){api('create_api_key',{key_name:document.getElementById('new-key-name').value,rate_limit:document.getElementById('new-key-limit').value}).then(r=>{toast(r.message);closeModal();fetchApiKeys();});}
function toggleApiKey(id){api('toggle_api_key',{id}).then(r=>{toast(r.message);fetchApiKeys();});}
function deleteApiKey(id){api('delete_api_key',{id}).then(r=>{toast(r.message);fetchApiKeys();});}
function loadBlocked(){
  const el=document.getElementById('page-blocked');
  el.innerHTML=`<div class="page-header"><div><h2>🚫 Blocked Devices</h2><p>Manage blocked devices</p></div><div class="header-actions"><button class="btn btn-primary" onclick="openBlockModal()">➕ Block Device</button></div></div><div id="blocked-list"></div>`;
  fetchBlocked();
}
function fetchBlocked(){
  api('get_blocked_devices',{},'GET').then(r=>{
    if(r.status!=='success')return;
    const el=document.getElementById('blocked-list');
    if(!r.data.length){el.innerHTML='<div class="empty-state"><div class="empty-icon">✅</div><h3>No Blocked Devices</h3></div>';return;}
    el.innerHTML='<div class="table-wrapper"><table><tr><th>Device ID</th><th>Info</th><th>Reason</th><th>Blocked At</th><th>Action</th></tr>'+
    r.data.map(d=>`<tr><td><code>${d.device_id}</code></td><td>${d.device_info||'-'}</td><td>${d.reason||'-'}</td><td>${d.blocked_at}</td><td><button class="btn btn-success btn-sm" onclick="unblockDevice(${d.id})">✅ Unblock</button></td></tr>`).join('')+'</table></div>';
  });
}
function openBlockModal(){
  openModal('Block Device',`<div class="form-group"><label>Device ID *</label><input id="block-device-id" required></div><div class="form-group"><label>Device Info</label><input id="block-device-info"></div><div class="form-group"><label>Reason</label><input id="block-reason"></div>`,
  `<button class="btn btn-secondary" onclick="closeModal()">Cancel</button><button class="btn btn-danger" onclick="submitBlock()">🚫 Block</button>`);
}
function submitBlock(){api('block_device',{device_id:document.getElementById('block-device-id').value,device_info:document.getElementById('block-device-info').value,reason:document.getElementById('block-reason').value}).then(r=>{toast(r.message);closeModal();fetchBlocked();});}
function unblockDevice(id){api('unblock_device',{id}).then(r=>{toast(r.message);fetchBlocked();});}
function loadLogs(){
  const el=document.getElementById('page-logs');
  el.innerHTML=`<div class="page-header"><div><h2>📋 Activity Logs</h2><p>System activity history</p></div><div class="header-actions"><button class="btn btn-danger btn-sm" onclick="clearLogs()">🗑️ Clear All</button></div></div><div id="logs-list"></div><div id="logs-pagination"></div>`;
  fetchLogs(1);
}
function fetchLogs(page=1){
  api('get_logs',{page},'GET').then(r=>{
    if(r.status!=='success')return;
    document.getElementById('logs-list').innerHTML='<div class="table-wrapper"><table><tr><th>Action</th><th>Details</th><th>IP</th><th>Time</th></tr>'+
    r.data.map(l=>`<tr><td><span class="badge badge-active">${l.action}</span></td><td style="max-width:300px;overflow:hidden;text-overflow:ellipsis">${l.details||''}</td><td>${l.ip_address||''}</td><td style="white-space:nowrap">${l.created_at}</td></tr>`).join('')+'</table></div>';
    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="fetchLogs(${i})">${i}</button>`;pg+='</div>';}
    document.getElementById('logs-pagination').innerHTML=pg;
  });
}
function clearLogs(){api('clear_logs').then(r=>{toast(r.message);loadLogs();});}
