import { createBrowserClient } from "@supabase/ssr";
import type { SupabaseClient } from "@supabase/supabase-js";
import { readSupabasePublicConfig } from "@/lib/supabase/config";

let browserClient: SupabaseClient | null = null;

/**
 * Browser Supabase client that uses cookies (via @supabase/ssr) so the session
 * is shared with the server/middleware and stays in sync after login.
 */
export const supabaseBrowser = (): SupabaseClient | null => {
  const config = readSupabasePublicConfig();
  if (!config) {
    return null;
  }

  if (!browserClient) {
    browserClient = createBrowserClient(config.url, config.anonKey);
  }

  return browserClient;
};
