export const ADMIN_TOKEN_KEY = 'mengya_admin_token';

/** 站点 logo / favicon 解析（固定） */
export const FAVICON_API_URL = 'https://favicon.smyhub.com/api/favicon?url=';

export function getFaviconUrlForSite(siteUrl) {
  return `${FAVICON_API_URL}${encodeURIComponent(siteUrl)}`;
}

export function getApiBase() {
  return (
    process.env.REACT_APP_API_URL ||
    (process.env.NODE_ENV === 'development'
      ? 'http://localhost:5000/api'
      : 'https://nav.api.shumengya.top/api')
  );
}

/** 技术栈项 svg：外链 URL 或 data/logo 下文件名 */
export function getTechstackIconUrl(item) {
  const s = (item?.svg || '').trim();
  if (!s) return null;
  if (/^https?:\/\//i.test(s)) return s;
  if (s.startsWith('//')) return `https:${s}`;
  return `${getApiBase()}/logo/${s}`;
}

/** 技术栈徽章底色：支持 #hex 或 CSS linear-gradient(...) */
export function techBadgeSurfaceStyle(color) {
  const c = String(color || '#555555').trim();
  if (c.includes('gradient(')) {
    return { background: c };
  }
  return { backgroundColor: c };
}

/** 与 techBadgeSurfaceStyle 配套的文字颜色 */
export function techBadgeLabelColor(color) {
  const c = String(color || '').trim();
  if (c.includes('gradient(')) return '#ffffff';
  const u = c.toUpperCase();
  if (u === '#FFFFFF' || u === '#FFF') return '#000000';
  return '#ffffff';
}

export function adminFetch(path, options = {}) {
  const token = sessionStorage.getItem(ADMIN_TOKEN_KEY);
  const headers = {
    'Content-Type': 'application/json',
    ...(options.headers || {}),
    'X-Admin-Token': token || '',
  };
  return fetch(`${getApiBase()}${path}`, { ...options, headers });
}

export async function adminPing(token) {
  const res = await fetch(`${getApiBase()}/admin/ping`, {
    headers: { 'X-Admin-Token': token },
  });
  return res.ok;
}
