/* Auth (Supabase) + cliente al Worker.
   - window.sb: cliente supabase-js (auth + sesión en el navegador).
   - window.api(path, opts): fetch al Worker con el JWT del usuario adjunto.
   - window.useSession(): hook con la sesión actual. */
(() => {
  const cfg = window.SUPABASE_CONFIG || {};
  // supabase-js UMD expone window.supabase.createClient
  const sb = window.supabase.createClient(cfg.url, cfg.anonKey, {
    // PKCE: el enlace del correo trae un ?code= de un solo uso, no el access_token.
    // El token nunca aparece en la URL. supabase-js canjea el code y limpia la URL.
    auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true, flowType: 'pkce' },
  });
  window.sb = sb;

  async function api(path, opts = {}) {
    const { data } = await sb.auth.getSession();
    const token = data.session?.access_token;
    const headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) };
    if (token) headers['Authorization'] = 'Bearer ' + token;
    const res = await fetch((cfg.apiBase || '') + path, { ...opts, headers });
    const txt = await res.text();
    let body = null;
    try { body = txt ? JSON.parse(txt) : null; } catch { body = txt; }
    if (!res.ok) {
      const msg = (body && body.error) ? (body.error + (body.detalle ? ' — ' + body.detalle : '')) : ('HTTP ' + res.status);
      const err = new Error(msg); err.status = res.status; err.body = body;
      throw err;
    }
    return body;
  }
  window.api = api;

  // Hook de sesión: null = cargando, false = sin sesión, objeto = logueado.
  window.useSession = () => {
    const { useState, useEffect } = React;
    const [session, setSession] = useState(null);
    useEffect(() => {
      sb.auth.getSession().then(({ data }) => setSession(data.session || false));
      const { data: sub } = sb.auth.onAuthStateChange((_e, s) => setSession(s || false));
      return () => sub.subscription.unsubscribe();
    }, []);
    return session;
  };
})();
