// src/data/supabase.jsx — SPEC §10.2
// Exposes window.supabase (the v2 client instance) and window.getAccessToken().
// Requires the supabase-js UMD bundle to be loaded BEFORE this file — the UMD
// initially exposes `window.supabase` as a NAMESPACE (containing createClient,
// AuthError, etc.). We capture the namespace, then overwrite window.supabase
// with the actual client instance so callers can use `window.supabase.auth`.
// Replace the placeholders with real project values before shipping.

const SUPABASE_URL = "https://hmlxmhvyipubkdeppoac.supabase.co";
const SUPABASE_ANON_KEY =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImhtbHhtaHZ5aXB1YmtkZXBwb2FjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY5NjQ5MzQsImV4cCI6MjA5MjU0MDkzNH0.x2inOknAGcbM-nnaYHXSINknftoqszl9kTCqEmqXoyE";

// Capture the UMD namespace (has .createClient) before we overwrite the global.
const _supabaseNs = window.supabase;
const _placeholder = SUPABASE_URL.includes("<") || SUPABASE_ANON_KEY.includes("<");
if (_placeholder) {
  // Keep placeholder values from crashing the page during dev bring-up.
  // Replace SUPABASE_URL and SUPABASE_ANON_KEY above with real values to enable auth.
  console.warn("supabase.jsx: placeholder config — auth is disabled");
  window.supabase = null;
} else if (!_supabaseNs || typeof _supabaseNs.createClient !== "function") {
  console.error("supabase-js UMD did not load before supabase.jsx");
  window.supabase = null;
} else if (!window.__gfSupabaseClient) {
  window.__gfSupabaseClient = _supabaseNs.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
    auth: {
      persistSession: true,
      autoRefreshToken: true,
      storageKey: "gf-auth",
    },
  });
  window.supabase = window.__gfSupabaseClient;
}

window.getAccessToken = async () => {
  if (!window.supabase || !window.supabase.auth) return null;
  const {
    data: { session },
  } = await window.supabase.auth.getSession();
  return session?.access_token || null;
};

// Fetch /me once the user has a session, cache on window.gfUser, and broadcast
// gf:auth so components can re-read. Callers: LoginModal, SignupModal, and
// the checkout success-poll. Returns the populated user object or null.
window.refreshGfUser = async () => {
  const token = await window.getAccessToken();
  if (!token) {
    window.gfUser = null;
    window.dispatchEvent(new Event("gf:auth"));
    return null;
  }
  if (typeof window.apiFetch !== "function") return null;
  try {
    const me = await window.apiFetch("/me", { auth: token });
    window.gfUser = me;
    window.dispatchEvent(new Event("gf:auth"));
    return me;
  } catch (err) {
    if (err && err.status === 401) {
      window.gfUser = null;
      window.dispatchEvent(new Event("gf:auth"));
    }
    return null;
  }
};

// Re-read /me when supabase-js emits an auth event (sign in, sign out, refresh).
if (window.supabase && window.supabase.auth) {
  window.supabase.auth.onAuthStateChange((_event) => {
    window.refreshGfUser();
  });
}
