var TOKEN = localStorage.getItem('admin_token') || '';
var TITLES = {dashboard:'仪表盘','sys-site':'网站设置','sys-services':'外部服务','sys-manage':'服务管理','sys-strategy':'性能配置','sys-password':'修改密码','cloud-config':'网盘设置',cleanup:'存储清理'};

function api(path, opts){
  opts = opts || {};
  opts.headers = opts.headers || {};
  if(TOKEN) opts.headers['Authorization'] = 'Bearer ' + TOKEN;
  return fetch(path, opts).then(function(r){
    if(r.status === 401){ localStorage.removeItem('admin_token'); location.reload(); throw new Error('unauth'); }
    return r.json();
  });
}

function toast(msg, type){
  type = type || 'success';
  var t = document.createElement('div'); t.className = 'toast toast-'+type; t.textContent = msg;
  document.body.appendChild(t);
  setTimeout(function(){ t.remove(); }, 2500);
}

document.querySelectorAll('.nav-item').forEach(function(el){
  el.onclick = function(){ nav(this.dataset.page); };
});

function nav(page){
  document.querySelectorAll('.nav-item').forEach(function(e){ e.classList.remove('active'); });
  var target = document.querySelector('[data-page="'+page+'"]');
  if(target) target.classList.add('active');
  document.getElementById('pageTitle').textContent = TITLES[page] || page;
  var c = document.getElementById('content');
  c.innerHTML = '<div class="loading">加载中...</div>';
  try{ window['page_'+page.replace(/-/g,'_')](c); }
  catch(e){ c.innerHTML = '<div class="card"><p>加载出错: '+e.message+'</p></div>'; }
}

function logout(){
  localStorage.removeItem('admin_token');
  location.reload();
}
