window.TRN_AUTH = (() => {
  let _client = null, _config = null;

  async function getConfig() {
    if (_config) return _config;
    const r = await fetch("/api/config");
    if (!r.ok) throw new Error("Cannot load auth config");
    _config = await r.json();
    return _config;
  }

  async function getClient() {
    if (_client) return _client;
    const cfg = await getConfig();
    if (!window.supabase) {
      await new Promise((resolve, reject) => {
        const s = document.createElement("script");
        s.src = "https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.min.js";
        s.onload = resolve; s.onerror = reject;
        document.head.appendChild(s);
      });
    }
    _client = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey, {
      auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true },
    });
    return _client;
  }

  return {
    getClient,
    async signInWithPassword(email, password) {
      const sb = await getClient();
      const { error } = await sb.auth.signInWithPassword({ email, password });
      if (error) throw new Error(error.message);
    },
    async sendPasswordReset(email) {
      const sb = await getClient();
      const { error } = await sb.auth.resetPasswordForEmail(email, { redirectTo: window.location.origin });
      if (error) throw new Error(error.message);
    },
    async getSession() {
      const sb = await getClient();
      const { data: { session } } = await sb.auth.getSession();
      return session;
    },
    async getUser() {
      const sb = await getClient();
      const { data: { user } } = await sb.auth.getUser();
      return user;
    },
    async onAuthStateChange(callback) {
      const sb = await getClient();
      return sb.auth.onAuthStateChange(callback);
    },
    async updatePassword(newPassword) {
      const sb = await getClient();
      const { error } = await sb.auth.updateUser({ password: newPassword });
      if (error) throw new Error(error.message);
    },
    async signOut() { const sb = await getClient(); await sb.auth.signOut(); },
    async getAccessToken() {
      const session = await this.getSession();
      return session?.access_token || null;
    },
  };
})();
