// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cfg  = (window as any).accessmateConfig ?? {};
const BASE  = cfg.restBase   ?? '/wp-json/accessmate/v1';
const NONCE = cfg.nonce      ?? '';

export const isPremium: boolean = !!cfg.isPremium;
export const upgradeUrl: string = cfg.upgradeUrl ?? '';
export const assetsUrl: string  = cfg.assetsUrl  ?? '';

export async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
  // With plain WordPress permalinks, BASE already contains '?rest_route=…'.
  // Split path into route and query parts so we join with '&' rather than '?'.
  const [routePart, queryPart] = path.split('?');
  const sep = BASE.includes('?') ? '&' : '?';
  const url = BASE + routePart + (queryPart ? sep + queryPart : '');
  const res = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'X-WP-Nonce': NONCE,
      ...options.headers,
    },
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json() as Promise<T>;
}
