/* API client — connects frontend to Fastify backend on Hetzner VPS */
const resolveApiBase = () => {
  if (typeof window === 'undefined') return 'https://api.marcianusexperience.com/api/v1';
  if (window.MARCIANUS_API_URL) return String(window.MARCIANUS_API_URL).replace(/\/$/, '');
  const { protocol, hostname } = window.location;
  // Local dev (file:// or localhost)
  if (protocol === 'file:' || hostname === 'localhost' || hostname === '127.0.0.1') {
    return 'http://localhost:3001/api/v1';
  }
  // Production — HTTPS API domain with SSL cert
  return 'https://api.marcianusexperience.com/api/v1';
};

const API_BASE = resolveApiBase();

const MarcianusAPI = {
  async _get(path, params = {}) {
    const url = new URL(API_BASE + path);
    Object.entries(params).forEach(([k, v]) => v !== undefined && url.searchParams.set(k, v));
    try {
      const res = await fetch(url.toString());
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return await res.json();
    } catch (err) {
      console.warn('[API] GET', path, err.message);
      return null;
    }
  },

  async _post(path, body) {
    try {
      const res = await fetch(API_BASE + path, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return await res.json();
    } catch (err) {
      console.warn('[API] POST', path, err.message);
      return null;
    }
  },

  // Events
  getEvents: (params) => MarcianusAPI._get('/events', params),
  getEvent:  (slug)   => MarcianusAPI._get(`/events/${slug}`),
  getEventKPIs: (id)  => MarcianusAPI._get(`/events/${id}/kpis`),
  createEvent: (body) => MarcianusAPI._post('/events', body),

  // Users
  getUsers:      (params) => MarcianusAPI._get('/users', params),
  getUser:       (id)     => MarcianusAPI._get(`/users/${id}`),
  getLeaderboard: ()      => MarcianusAPI._get('/users/leaderboard'),

  // Content
  getContent:  (params) => MarcianusAPI._get('/content', params),
  getContentItem: (slug) => MarcianusAPI._get(`/content/${slug}`),
  likeContent:   (slug) => MarcianusAPI._post(`/content/${slug}/like`, {}),
  downloadContent: (slug) => MarcianusAPI._post(`/content/${slug}/download`, {}),

  // Hexis AI
  getMatches:    (userId, params) => MarcianusAPI._get(`/hexis/match/${userId}`, params),
  getDashboard:  ()               => MarcianusAPI._get('/hexis/dashboard'),
  getAlerts:     (userId)         => MarcianusAPI._get(`/hexis/alerts/${userId}`),
  chat:          (body)           => MarcianusAPI._post('/hexis/chat', body),

  // Analytics
  track: (body) => MarcianusAPI._post('/analytics/track', body),
  getAnalyticsSummary: (params) => MarcianusAPI._get('/analytics/summary', params),
};

window.MarcianusAPI = MarcianusAPI;
