// Thin Supabase client for the Palette · Keyword Agent UI.
// Uses the UMD build from jsDelivr so we don't need a bundler.
//
// Global: window.supabase (via the UMD script tag in Keyword Agent.html)
// Exposes: window.palette_auth with {client, getSession, signInMagic, signInPassword,
//   signUpWithInvite, signOut, onChange, waitForSession}.

(() => {
  const SUPABASE_URL = 'https://dfzepihawnsvpxufshbh.supabase.co';
  const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRmemVwaWhhd25zdnB4dWZzaGJoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY4NTUzNDAsImV4cCI6MjA5MjQzMTM0MH0.Mgz5k5OBoNrfOVmOkQ-hTv_tk5excNAOUxC6kHjJLTo';

  if (!window.supabase) {
    console.error('Supabase UMD script missing — add the CDN <script> to index.html');
    return;
  }
  const client = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
    auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true },
  });

  const listeners = new Set();
  let currentSession = null;

  const notify = (session) => {
    currentSession = session;
    listeners.forEach(fn => { try { fn(session); } catch(e) { console.warn(e); } });
  };

  client.auth.getSession().then(({ data }) => notify(data.session || null));
  client.auth.onAuthStateChange((_event, session) => notify(session));

  window.palette_auth = {
    client,
    getSession: () => currentSession,
    waitForSession: async () => {
      const { data } = await client.auth.getSession();
      currentSession = data.session || null;
      return currentSession;
    },
    onChange: (fn) => { listeners.add(fn); return () => listeners.delete(fn); },
    signInMagic: async (email) => {
      return client.auth.signInWithOtp({
        email,
        options: { emailRedirectTo: window.location.origin },
      });
    },
    signInPassword: async (email, password) => {
      return client.auth.signInWithPassword({ email, password });
    },
    signUpWithInvite: async ({ email, password, invite_token }) => {
      const { data, error } = await client.auth.signUp({
        email, password,
        options: { data: { invite_token } },
      });
      if (error) return { error };
      if (data.user && invite_token) {
        try {
          await fetch('/api/auth/invites/redeem', {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify({ token: invite_token, user_id: data.user.id }),
          });
        } catch(e) { /* invite may already be redeemed — continue */ }
      }
      return { data };
    },
    signOut: () => client.auth.signOut(),
  };
})();
