/* ClientBase, Supabase client + local-first sync layer (étape 1/6)
   Configuration fournie par window.SUPABASE_CONFIG dans index.html. */

// Debug helper : log uniquement en mode dev (localhost) OU si ?debug=1 dans
// l'URL OU si localStorage.cb_debug = "1". En production, silence total —
// console propre pour le user final. Utilisable partout via window.cbDebug.
(function setupDebug() {
  const isDev = (() => {
    try {
      const h = window.location.hostname || "";
      if (h === "localhost" || h === "127.0.0.1" || h.endsWith(".local")) return true;
      if (new URLSearchParams(window.location.search).get("debug") === "1") return true;
      if (localStorage.getItem("cb_debug") === "1") return true;
    } catch {}
    return false;
  })();
  const noop = () => {};
  window.cbDebug = {
    enabled: isDev,
    log:  isDev ? console.log.bind(console)  : noop,
    warn: isDev ? console.warn.bind(console) : noop,
    info: isDev ? console.info.bind(console) : noop,
    // error reste toujours actif (vrais bugs à investiguer)
    error: console.error.bind(console),
  };
})();

(function initSupabase() {
  const cfg = window.SUPABASE_CONFIG || {};
  if (!cfg.url || !cfg.anonKey) {
    window.cbDebug.warn("[cb-supabase] pas de SUPABASE_CONFIG, mode 100% localStorage");
    window.cbSupabase = null;
    return;
  }
  if (typeof window.supabase === "undefined" || !window.supabase.createClient) {
    window.cbDebug.warn("[cb-supabase] @supabase/supabase-js pas chargé, mode 100% localStorage");
    window.cbSupabase = null;
    return;
  }
  window.cbSupabase = window.supabase.createClient(cfg.url, cfg.anonKey, {
    auth: {
      persistSession: true,
      autoRefreshToken: true,
      detectSessionInUrl: true,
      flowType: "pkce",
      storageKey: "cb_sb_auth_v1",
    },
  });
  window.cbDebug.info("[cb-supabase] client prêt →", cfg.url);
})();

/* Statut de connexion pour la future couche data.
   - null    : pas encore testé
   - true    : on a une session Supabase valide → on synchro
   - false   : offline ou pas de compte cloud → on reste 100% localStorage */
window.cbSync = {
  online: null,
  listeners: new Set(),
  set(v) {
    if (this.online === v) return;
    this.online = v;
    this.listeners.forEach(fn => { try { fn(v); } catch (e) { console.error(e); } });
  },
  onChange(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); },
};

/* Suit l'état de la session Supabase. */
if (window.cbSupabase) {
  window.cbSupabase.auth.getSession().then(({ data }) => {
    window.cbSync.set(!!data.session);
  });
  window.cbSupabase.auth.onAuthStateChange((_event, session) => {
    window.cbSync.set(!!session);
  });
}
