// Spellstash auth helpers — loaded BEFORE per-page jsx so window.ssAuth is
// ready by the time the page's React app mounts.
//
// Exposes (via window.ssAuth):
//   client       — Supabase JS client (browser-safe publishable key)
//   useSession() — React hook returning [session, loading]
//   authedFetch  — fetch wrapper that adds Authorization: Bearer <jwt>
//   signOut(to)  — clears session and redirects (default "/")
//
// Loaded by: index.html, collection.html, login.html. Uses the global
// `supabase` from the @supabase/supabase-js UMD bundle (CDN).

const SS_SUPABASE_URL = "https://vqehbzmdtmkvlsamjhvq.supabase.co";
const SS_PUBLISHABLE_KEY = "sb_publishable_J0djUhvy6o8abrBnc98FdQ_XEBIWQ7M";

const ssClient = supabase.createClient(SS_SUPABASE_URL, SS_PUBLISHABLE_KEY, {
  auth: {
    persistSession: true,
    autoRefreshToken: true,
    storageKey: "spellstash-auth",
  },
});

window.ssAuth = {
  client: ssClient,

  useSession() {
    const [session, setSession] = React.useState(null);
    const [loading, setLoading] = React.useState(true);
    React.useEffect(() => {
      let mounted = true;
      ssClient.auth.getSession().then(({ data }) => {
        if (mounted) {
          setSession(data.session);
          setLoading(false);
        }
      });
      const { data: sub } = ssClient.auth.onAuthStateChange((_event, s) => {
        if (mounted) setSession(s);
      });
      return () => {
        mounted = false;
        sub.subscription.unsubscribe();
      };
    }, []);
    return [session, loading];
  },

  async authedFetch(url, opts = {}) {
    const { data } = await ssClient.auth.getSession();
    const session = data.session;
    const headers = new Headers(opts.headers || {});
    if (session && session.access_token) {
      headers.set("Authorization", "Bearer " + session.access_token);
    }
    return fetch(url, Object.assign({}, opts, { headers }));
  },

  async signOut(redirectTo) {
    await ssClient.auth.signOut();
    window.location.href = redirectTo || "/";
  },
};
