// ─── API CLIENT ───────────────────────────────────────────────────────────────
// MODE LOCAL UNIQUEMENT - Pas besoin de serveur PHP

const API_URL = 'api';
const LOCAL_MODE = true; // Mode local activé

const api = {
  // ─── Token helpers ──────────────────────────────────────────────────────────
  getToken: () => localStorage.getItem('tq_token'),
  setToken: (t) => localStorage.setItem('tq_token', t),
  clearToken: () => localStorage.removeItem('tq_token'),

  // ─── Fetch helper avec Authorization header ─────────────────────────────────
  async request(path, options = {}) {
    const token = this.getToken();
    let res;
    try {
      res = await fetch(API_URL + path, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
          ...(options.headers || {})
        }
      });
    } catch (e) {
      throw new Error('Failed to fetch');
    }
    let data;
    try {
      data = await res.json();
    } catch (e) {
      throw new Error('Réponse serveur invalide');
    }
    if (!res.ok) throw new Error(data.message || 'Erreur réseau');
    return data;
  },

  // ─── Auth ───────────────────────────────────────────────────────────────────
  async register(username, password, email = '') {
    const data = await this.request('/auth.php?action=register', {
      method: 'POST',
      body: JSON.stringify({ username, password, email })
    });
    this.setToken(data.token);
    return data.user;
  },

  async login(username, password) {
    const data = await this.request('/auth.php?action=login', {
      method: 'POST',
      body: JSON.stringify({ username, password })
    });
    this.setToken(data.token);
    return data.user;
  },

  logout() {
    this.clearToken();
  },

  async me() {
    return (await this.request('/auth.php?action=me')).user;
  },

  // ─── Stats ──────────────────────────────────────────────────────────────────
  async saveSession({ category, score, good, bad, bestStreak, mistakes }) {
    return this.request('/stats.php?action=session', {
      method: 'POST',
      body: JSON.stringify({ category, score, good, bad, bestStreak, mistakes })
    });
  },

  async getLeaderboard() {
    return (await this.request('/stats.php?action=leaderboard')).leaderboard;
  },

  async clearMistakes() {
    return this.request('/stats.php?action=mistakes', { method: 'DELETE' });
  },

  // ─── Question du jour ────────────────────────────────────────────────────────
  async saveDaily(day, correct) {
    return this.request('/daily.php?action=answer', {
      method: 'POST',
      body: JSON.stringify({ day, correct })
    });
  },

  async getDailyStatus(day) {
    return this.request(`/daily.php?action=status&day=${day}`);
  }
};
