// TribeTruth — Supabase client + session plumbing (zero-build, window-global).
// Loaded immediately after the supabase-js UMD bundle and BEFORE every app
// script, so window.sb / window.useSession / window.authApi exist everywhere.
//
// Mirrors the mobile app's F:\Tribe Truth\App\src\lib\auth.ts semantics.
// NOTE: uses React.useState / React.useEffect directly (not the destructured
// hook globals) because shared.jsx hasn't been evaluated yet at this point.

const TT_SUPABASE_URL = "https://yqigdmawjodvkjmzxbdd.supabase.co";
// Public anon key — public-by-design (RLS enforces access); the app ships it too.
const TT_SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlxaWdkbWF3am9kdmtqbXp4YmRkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODM3ODg3MjMsImV4cCI6MjA5OTM2NDcyM30.UCBaSxjKM4jrZp5f4NbkYi5rpmkGQBAGSijkKt1zIIg";

// ── Password-recovery redirect vs. the hash router ──────────────────────
// Reset emails redirect to "https://tribe-truth.com/#auth/reset" and the
// Supabase auth server appends its OWN token fragment, so the URL arrives as
//   …/#auth/reset#access_token=…&type=recovery   (or #error_code=… on expiry)
// The browser folds everything after the FIRST "#" into one hash, which
// breaks both consumers: supabase-js detectSessionInUrl parses the hash with
// URLSearchParams, so the first key becomes "auth/reset#access_token" and
// token detection silently fails; and the app's hash router would try to
// route "auth/reset#access_token=…". Fix, BEFORE createClient runs: strip
// our route prefix so the hash is a pure token fragment supabase-js can
// consume, and stash the intended route so app.jsx lands on the reset form.
(function ttNormalizeAuthHash() {
  const h = window.location.hash || "";
  const second = h.indexOf("#", 1);
  if (second === -1) return;
  const route = h.slice(1, second); // e.g. "auth/reset"
  const fragment = h.slice(second + 1); // e.g. "access_token=…&type=recovery"
  if (!/(^|&)(access_token|refresh_token|error|error_code|error_description|type)=/.test(fragment)) return;
  window.__ttAuthReturnRoute = route || "auth/reset";
  window.history.replaceState(
    null,
    "",
    window.location.pathname + window.location.search + "#" + fragment,
  );
})();

window.sb = window.supabase.createClient(TT_SUPABASE_URL, TT_SUPABASE_ANON_KEY);

/**
 * React hook — current auth session (null = guest / signed out).
 * Reads the persisted session once, then stays live via onAuthStateChange.
 * Returns { session, loading } — `loading` is true only for the first read,
 * so guest browsing never flashes signed-in UI and vice versa.
 */
function useSession() {
  const [state, setState] = React.useState({ session: null, loading: true });
  React.useEffect(() => {
    let alive = true;
    window.sb.auth.getSession().then(({ data }) => {
      if (alive) setState({ session: data.session, loading: false });
    });
    const { data: sub } = window.sb.auth.onAuthStateChange((_event, session) => {
      if (alive) setState({ session, loading: false });
    });
    return () => { alive = false; sub.subscription.unsubscribe(); };
  }, []);
  return state;
}

/** Display name for a session: user_metadata.display_name, else email prefix. */
function sessionDisplayName(session) {
  if (!session || !session.user) return "";
  return (
    (session.user.user_metadata && session.user.user_metadata.display_name) ||
    (session.user.email || "").split("@")[0]
  );
}

// Auth API — same call/return shapes as the app's src/lib/auth.ts.
const authApi = {
  /** Sign in with email/password. Returns { session, user, error }. */
  async signIn(email, password) {
    const { data, error } = await window.sb.auth.signInWithPassword({ email, password });
    return { session: data ? data.session : null, user: data ? data.user : null, error };
  },

  /**
   * Sign up with email/password. Passes display_name as user_metadata so it
   * persists on the user object. Autoconfirm is on, so Supabase normally
   * returns a session immediately (needsConfirmation === false); the
   * no-session branch is kept for graceful handling if that ever changes.
   */
  async signUp(email, password, displayName) {
    const { data, error } = await window.sb.auth.signUp({
      email,
      password,
      options: { data: { display_name: displayName || email.split("@")[0] } },
    });
    if (error) return { session: null, user: null, needsConfirmation: false, error };
    if (data.session) {
      return { session: data.session, user: data.user, needsConfirmation: false, error: null };
    }
    // No session: a confirmation email is on its way.
    return { session: null, user: data.user, needsConfirmation: true, error: null };
  },

  /**
   * Send a password-reset email. The link lands back on #auth/reset with a
   * recovery session (see ttNormalizeAuthHash above). Returns { error }.
   */
  async resetPassword(email) {
    const { error } = await window.sb.auth.resetPasswordForEmail(email, {
      redirectTo: "https://tribe-truth.com/#auth/reset",
    });
    return { error };
  },

  /** Set a new password for the current (recovery) session. Returns { error }. */
  async updatePassword(newPassword) {
    const { error } = await window.sb.auth.updateUser({ password: newPassword });
    return { error };
  },

  /** Sign out the current user. Returns { error }. */
  async signOut() {
    const { error } = await window.sb.auth.signOut();
    return { error };
  },
};

Object.assign(window, { useSession, sessionDisplayName, authApi });
