/**
 * FenyaBot Mini App — API wrapper
 */

const API_BASE = window.location.origin;

function getInitData() {
  if (window.Telegram?.WebApp?.initData) {
    return window.Telegram.WebApp.initData;
  }
  return '';
}

async function api(path, options = {}) {
  const { method = 'GET', body = null } = options;
  const headers = {
    'X-Telegram-Init-Data': getInitData(),
    'Content-Type': 'application/json',
  };

  const config = { method, headers };
  if (body) config.body = JSON.stringify(body);

  const resp = await fetch(`${API_BASE}${path}`, config);
  if (!resp.ok) {
    const err = await resp.json().catch(() => ({}));
    throw new Error(err.detail || `HTTP ${resp.status}`);
  }
  return resp.json();
}

export const API = {
  getProfile: () => api('/api/profile'),
  getLeagues: () => api('/api/leagues'),
  getMatches: (league) => api(`/api/matches/${league}`),
  placeBet: (data) => api('/api/bet', { method: 'POST', body: data }),
  getMyBets: () => api('/api/mybets'),
  getBetHistory: () => api('/api/bet_history'),
  playCasino: (bet) => api('/api/casino', { method: 'POST', body: { bet } }),
  playPenis: () => api('/api/penis', { method: 'POST' }),
  getTop: () => api('/api/top'),
  getSchedule: (day) => api(`/api/schedule${day != null ? `?day=${day}` : ''}`),
  getUwu: (tags) => api(`/api/uwu?tags=${encodeURIComponent(tags || 'rating:safe score:>500 -animated')}`),
  getFurtokFeed: (safe = true, page = 1, tags = '') => api(`/api/furtok?safe=${safe}&page=${page}${tags ? '&tags=' + encodeURIComponent(tags) : ''}`),
  getShortiesFeed: (page = 1, count = 8) => api(`/api/furtok/shorties?page=${page}&count=${count}`),
  proxyShortiesMediaUrl: (url) => `${API_BASE}/api/proxy-shorties-media?url=${encodeURIComponent(url || '')}`,
  talk: (text) => api('/api/talk', { method: 'POST', body: { text } }),
};
