/* Initializes the Supabase client and exposes it as window.sb.
 *
 * Reads SUPABASE_URL and SUPABASE_ANON_KEY from window.__ENV (set in
 * config.js — gitignored). If config is missing, window.sb stays null and
 * the LoginScreen shows a setup message.
 */
(function () {
  const env = window.__ENV || {};
  if (
    !env.SUPABASE_URL ||
    !env.SUPABASE_ANON_KEY ||
    !env.SUPABASE_URL.startsWith("http") ||
    env.SUPABASE_URL.includes("<your-project-ref>")
  ) {
    console.warn(
      "[supabase] config.js missing or unfilled. Copy config.example.js to config.js and set your Supabase URL + anon key.",
    );
    window.sb = null;
    return;
  }
  if (!window.supabase || typeof window.supabase.createClient !== "function") {
    console.error("[supabase] SDK not loaded. Check the @supabase/supabase-js script tag.");
    window.sb = null;
    return;
  }

  try {
    window.sb = window.supabase.createClient(env.SUPABASE_URL, env.SUPABASE_ANON_KEY, {
      auth: {
        persistSession: true,
        autoRefreshToken: true,
        detectSessionInUrl: true,
        flowType: "pkce",
      },
    });
  } catch (e) {
    console.error("[supabase] failed to initialize:", e);
    window.sb = null;
  }
})();
