/**
 * currentAccessToken (DS1 follow-up) — the bearer token for authenticated
 * browser fetches, robust across EVERY sign-in method.
 *
 * The bug this closes: surfaces read `localStorage.getItem('sb-token')`, but
 * that key is written ONLY by the OAuth callback. Email/password users (the
 * majority) had no `sb-token`, so their authenticated fetches (profile stats,
 * tracker, slip, settings) sent no Authorization header and silently returned
 * nothing. DS1 fixed the scan→ledger path; this helper fixes the rest.
 *
 * Supabase-js persists the session as JSON under `sb-<project-ref>-auth-token`
 * with `access_token` at the top level (v2) or under `currentSession` (v1).
 * We read that directly (best-effort, synchronous), falling back to the legacy
 * key. Prefer `useAuth().session?.access_token` in components that already have
 * it; this helper is for the ones that don't.
 *
 * CommonJS (like colorContract.js / clvDisplay.js) so the plain-JS Jest suite
 * can require it AND the .tsx app can import it (Next allowJs).
 *
 * @returns {string|null}
 */
function currentAccessToken() {
  if (typeof window === 'undefined') return null;
  try {
    for (let i = 0; i < window.localStorage.length; i += 1) {
      const k = window.localStorage.key(i) || '';
      if (/^sb-.*-auth-token$/.test(k)) {
        const raw = window.localStorage.getItem(k);
        if (!raw) continue;
        const v = JSON.parse(raw);
        const tok = (v && v.access_token) || (v && v.currentSession && v.currentSession.access_token);
        if (tok) return tok;
      }
    }
  } catch {
    /* fall through to the legacy key */
  }
  return window.localStorage.getItem('sb-token');
}

module.exports = { currentAccessToken };
