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

const MX_CANVAS_CONFIG = window.MX_CANVAS_CONFIG || {};
let MX_CANVAS_ACCOUNT_BASE_URL = String(MX_CANVAS_CONFIG.accountBaseUrl || '').trim().replace(/\/+$/, '');
let accountConfigPromise = null;

async function ensureAccountConfig(){
  if(MX_CANVAS_ACCOUNT_BASE_URL) return MX_CANVAS_ACCOUNT_BASE_URL;
  if(!accountConfigPromise){
    accountConfigPromise = fetch('/api/client-config', {credentials:'include'})
      .then(response => response.ok ? response.json() : {})
      .then(data => {
        MX_CANVAS_ACCOUNT_BASE_URL = String(data.account_base_url || '').trim().replace(/\/+$/, '');
        return MX_CANVAS_ACCOUNT_BASE_URL;
      })
      .catch(() => '');
  }
  return accountConfigPromise;
}

const ACCOUNT_API_PATHS = [
  '/api/auth/login',
  '/api/auth/logout',
  '/api/auth/me',
  '/api/auth/check',
  '/api/auth/users',
  '/api/auth/change-password',
  '/api/admin/usage',
  '/api/admin/teams',
];

const ACCOUNT_API_PREFIXES = [
  '/api/admin/users/',
  '/api/admin/teams/',
  '/api/admin/usage',
];

function shouldProxyToAccountService(path){
  const url = String(path || '').trim();
  if(!MX_CANVAS_ACCOUNT_BASE_URL || !url.startsWith('/api/')) return false;
  if(ACCOUNT_API_PATHS.includes(url)) return true;
  return ACCOUNT_API_PREFIXES.some(prefix => url.startsWith(prefix));
}

function accountApiUrl(path){
  const url = String(path || '');
  if(!shouldProxyToAccountService(url)) return url;
  if(/^https?:\/\//i.test(url)) return url;
  return `${MX_CANVAS_ACCOUNT_BASE_URL}${url.startsWith('/') ? url : `/${url}`}`;
}

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){
    const authResponse = await fetch('/api/auth/me', {credentials:'include', cache:'no-store'});
    const auth = await authResponse.json().catch(() => ({}));
    if(!auth.authenticated){
      location.href = '/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 = '/login';
}

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 管理后台</div>
        <nav class="nav">
          ${items.map(([id, name]) => `<a class="${id === active ? 'active' : ''}" href="/admin${id ? `/${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');
}
