// Tempo — Supabase client (initialized from CDN UMD bundle loaded in index.html)

const SUPABASE_URL = 'https://twaldzmjryjyrzwjckpe.supabase.co';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR3YWxkem1qcnlqeXJ6d2pja3BlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzk3MzY5NDAsImV4cCI6MjA5NTMxMjk0MH0.s51IaUC7nuLb-PmRVNpKZ-uVlllCPH8zpPD-V04otWY';

// The supabase UMD bundle exposes `window.supabase` with a `createClient` factory.
// We expose our configured client as `window.sb`.
if (typeof window.supabase !== 'object' || typeof window.supabase.createClient !== 'function') {
  console.error('[Tempo] Supabase UMD SDK is not loaded. Check that index.html loads supabase-js BEFORE the JSX scripts.');
} else if (!window.sb) {
  window.sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
    auth: {
      persistSession: true,
      autoRefreshToken: true,
      detectSessionInUrl: true,
    },
  });
}

// Today → YYYY-MM-DD dans le fuseau du profil (window.__appTz, fallback Europe/Paris).
// Honore le réglage « fuseau horaire » : « aujourd'hui » est le jour civil vécu
// par l'user, pas celui du navigateur. localDayInTz vient de format-prefs.jsx ;
// fallback sur le fuseau navigateur si le module n'est pas encore chargé.
function todayISO() {
  const tz = (typeof window !== 'undefined' && window.__appTz) || 'Europe/Paris';
  if (typeof localDayInTz === 'function') {
    try { return localDayInTz(new Date(), tz); } catch (e) { /* fallback ci-dessous */ }
  }
  const d = new Date();
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

function dateISO(d) {
  if (!d) return todayISO();
  if (typeof d === 'string') return d.slice(0, 10);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

// Tiny error helper — surfaces Supabase errors as readable French strings.
function sbErrorMessage(err) {
  if (!err) return '';
  const m = (err.message || err.error_description || '').toString();
  if (/Invalid login credentials/i.test(m)) return 'Email ou mot de passe incorrect.';
  if (/Email not confirmed/i.test(m))      return 'Tu dois confirmer ton email avant de te connecter.';
  if (/User already registered/i.test(m))  return 'Un compte existe déjà avec cet email. Connecte-toi.';
  if (/rate limit/i.test(m))               return 'Trop de tentatives — réessaie dans quelques minutes.';
  if (/network|fetch/i.test(m))            return 'Problème réseau — vérifie ta connexion.';
  // Erreur côté base (souvent un trigger sur auth.users) — jamais l'anglais brut au client.
  if (/database error|saving new user/i.test(m)) return 'Création du compte momentanément indisponible. Réessaie dans un instant.';
  // Filet : ne jamais afficher un message technique anglais à l'utilisateur final.
  if (/[a-z]/.test(m) && /\b(error|failed|invalid|null|constraint|violates|schema)\b/i.test(m)) return 'Une erreur est survenue. Réessaie dans un instant.';
  return m || 'Une erreur est survenue.';
}

Object.assign(window, { SUPABASE_URL, SUPABASE_ANON_KEY, todayISO, dateISO, sbErrorMessage });
