// =====================================================================
//  Polycall — client API (front)
//  Détecte le serveur ; en son absence, l'app fonctionne en mode démo
//  (données simulées) et toutes les méthodes de mutation deviennent
//  des "no-op" silencieux.
// =====================================================================
const PolycallAPI = (function () {
  let token = null;
  let enabled = false;
  const BASE = "/api";

  function setToken(t) { token = t; try { t ? localStorage.setItem("polycall-token", t) : localStorage.removeItem("polycall-token"); } catch (e) {} }
  function headers() { const h = { "Content-Type": "application/json" }; if (token) h.Authorization = "Bearer " + token; return h; }

  async function req(method, pathname, body) {
    const r = await fetch(BASE + pathname, { method, headers: headers(), body: body ? JSON.stringify(body) : undefined });
    if (!r.ok) { let e = {}; try { e = await r.json(); } catch (_) {} throw new Error(e.error || ("Erreur " + r.status)); }
    return r.status === 204 ? null : r.json();
  }
  const soft = (p) => p.catch((e) => { console.warn("[PolycallAPI] synchronisation échouée :", e.message); return null; });

  return {
    get enabled() { return enabled; },
    hasToken() { return !!token; },

    async detect() {
      try { token = localStorage.getItem("polycall-token") || null; } catch (e) {}
      try { const r = await fetch(BASE + "/health"); enabled = r.ok; } catch (e) { enabled = false; }
      return enabled;
    },
    async login(email, password) { const d = await req("POST", "/login", { email, password }); setToken(d.token); return d.user; },
    logout() { setToken(null); },
    async me() { return (await req("GET", "/me")).user; },
    async changePassword(currentPassword, newPassword) { return req("POST", "/me/password", { currentPassword, newPassword }); },
    async bootstrap() { return req("GET", "/bootstrap"); },

    // ---- mutations (no-op si le serveur est absent) ----
    saveOperation(op)        { return enabled ? soft(req("POST", "/operations", op)) : Promise.resolve(null); },
    updateOperation(slug, op){ return enabled ? soft(req("PATCH", "/operations/" + slug, op)) : Promise.resolve(null); },
    deleteOperation(slug)    { return enabled ? soft(req("DELETE", "/operations/" + slug)) : Promise.resolve(null); },
    saveCodes(slug, codes)   { return enabled ? soft(req("PUT", "/operations/" + slug + "/codes", { codes })) : Promise.resolve(null); },
    saveAccount(a)           { return enabled ? soft(req("POST", "/accounts", a)) : Promise.resolve(null); },
    updateAccount(id, a)     { return enabled ? soft(req("PATCH", "/accounts/" + id, a)) : Promise.resolve(null); },
    deleteAccount(id)        { return enabled ? soft(req("DELETE", "/accounts/" + id)) : Promise.resolve(null); },
    async createFiche(operation, type, canal, channel, fields) { if (!enabled) return null; try { return await req("POST", "/fiches", { operation, type, canal, channel, fields }); } catch (e) { return null; } },
    updateFiche(id, fields, type, canal) { return enabled ? soft(req("PATCH", "/fiches/" + id, { fields, type, canal })) : Promise.resolve(null); },
    qualifyFiche(id, conclusion)  { return enabled ? soft(req("POST", "/fiches/" + id + "/qualify", conclusion)) : Promise.resolve(null); },
    reopenFiche(id)               { return enabled ? soft(req("POST", "/fiches/" + id + "/reopen")) : Promise.resolve(null); },
    deleteFiche(id)               { return enabled ? soft(req("DELETE", "/fiches/" + id)) : Promise.resolve(null); },
    restoreFiche(id)              { return enabled ? soft(req("POST", "/fiches/" + id + "/restore")) : Promise.resolve(null); },
    purgeFiche(id)                { return enabled ? soft(req("DELETE", "/fiches/" + id + "/purge")) : Promise.resolve(null); },
    emptyTrash(slug)              { return enabled ? soft(req("POST", "/operations/" + slug + "/trash/empty")) : Promise.resolve(null); },
    saveBrand(logo)               { return enabled ? soft(req("PUT", "/settings/brand", { logo })) : Promise.resolve(null); },
  };
})();
window.PolycallAPI = PolycallAPI;
