const adminEsc = value => String(value ?? '').replace(/[&<>"']/g, char => ({
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
}[char]));

const inferWebAdminBase = () => {
  const explicit = String(window.MX_WEB_ADMIN_BASE || '').trim().replace(/\/+$/, '');
  if(explicit) return explicit;
  const path = String(location.pathname || '').replace(/\/+$/, '');
  const parts = path.split('/').filter(Boolean);
  return parts.length ? `/${parts[0]}` : '';
};

const WEB_ADMIN_BASE = inferWebAdminBase();
const WEB_ADMIN_LOGIN = String(window.MX_WEB_ADMIN_LOGIN || `${WEB_ADMIN_BASE}/login`).trim();

async function adminApi(path, options = {}){
  const response = await fetch(path, { credentials: 'include', cache: 'no-store', ...options });
  const data = await response.json().catch(() => ({}));
  if(response.status === 401){
    location.href = WEB_ADMIN_LOGIN;
    throw new Error('登录已过期，请重新登录');
  }
  if(response.status === 403){
    throw new Error(data.detail || '需要管理员权限');
  }
  if(!response.ok){
    throw new Error(data.detail || data.error?.message || '请求失败');
  }
  return data;
}

function adminMessage(id, text, error = false){
  const el = document.getElementById(id);
  if(!el) return;
  el.textContent = text || '';
  el.className = `msg ${error ? 'error' : 'ok'}`;
}

async function adminLogout(){
  await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => null);
  location.href = WEB_ADMIN_LOGIN;
}

function webAdminHref(module = ''){
  return module ? `${WEB_ADMIN_BASE}/${module}` : WEB_ADMIN_BASE;
}

function adminShell(active, title, subtitle = ''){
  const items = [
    ['', '总览'],
    ['users', '用户管理'],
    ['teams', '团队管理'],
    ['video', '视频 API'],
    ['prompts', '提示词模板'],
    ['home', '首页公告'],
    ['usage', '使用流水'],
    ['security', '实时防护'],
    ['account', '账号安全'],
  ];
  document.body.innerHTML = `
    <div class="admin-shell">
      <aside class="sidebar">
        <div class="brand">MX Canvas Web Admin</div>
        <div class="muted" style="padding:0 18px 10px;font-size:12px">隐藏入口运行中</div>
        <nav class="nav">
          ${items.map(([id, name]) => `<a class="${id === active ? 'active' : ''}" href="${webAdminHref(id)}">${name}</a>`).join('')}
        </nav>
      </aside>
      <main class="main">
        <header class="topbar">
          <div>
            <h1>${adminEsc(title)}</h1>
            <div class="muted">${adminEsc(subtitle)}</div>
          </div>
          <div class="actions">
            <a class="button secondary" href="/">进入用户端</a>
            <button class="secondary" type="button" onclick="adminLogout()">退出登录</button>
          </div>
        </header>
        <div id="adminContent"></div>
      </main>
    </div>
  `;
  return document.getElementById('adminContent');
}
