/* Sponzza auth (classic content-script global) — Supabase REST + background Google flow. */
var SponzzaAuth = (function () {
  var KEY = 'sponzza_session';
  function cfg() { return SPONZZA_CONFIG; }
  function headers() {
    return { 'Content-Type': 'application/json', 'apikey': cfg().SUPABASE_ANON_KEY };
  }

  function getSession() {
    return new Promise(function (res) {
      try { chrome.storage.local.get(KEY, function (o) { res(o && o[KEY] ? o[KEY] : null); }); }
      catch (e) { res(null); }
    });
  }
  function setSession(s) {
    return new Promise(function (res) {
      var o = {}; o[KEY] = s; chrome.storage.local.set(o, function () { res(s); });
    });
  }
  function signOut() {
    return new Promise(function (res) { chrome.storage.local.remove(KEY, function () { res(); }); });
  }

  // Email OTP — works for Gmail or any custom email, no redirect needed.
  function sendEmailOtp(email) {
    return fetch(cfg().SUPABASE_URL + '/auth/v1/otp', {
      method: 'POST', headers: headers(),
      body: JSON.stringify({ email: email, create_user: true })
    }).then(function (r) {
      if (!r.ok) return r.json().then(function (e) { throw new Error(e.msg || e.error_description || 'Could not send code'); });
      return true;
    });
  }
  function verifyLink(tokenHash, type) {
    return fetch(cfg().SUPABASE_URL + '/auth/v1/verify', {
      method: 'POST', headers: headers(),
      body: JSON.stringify({ type: type || 'magiclink', token_hash: tokenHash })
    }).then(function (r) {
      return r.json().then(function (d) {
        if (!r.ok || !d.access_token) throw new Error(d.msg || d.error_description || 'Invalid or expired link');
        return setSession({
          access_token: d.access_token, refresh_token: d.refresh_token,
          expires_at: d.expires_at, user: { email: (d.user && d.user.email) || '', id: (d.user && d.user.id) }
        });
      });
    });
  }

  // Accepts either a pasted sign-in LINK (default email) or a 6-digit code.
  function verifyInput(email, input) {
    input = (input || '').trim();
    var tok = input.match(/[?&]token=([^&\s]+)/);
    if (tok) {
      var ty = input.match(/[?&]type=([^&\s]+)/);
      return verifyLink(decodeURIComponent(tok[1]), ty ? decodeURIComponent(ty[1]) : 'magiclink');
    }
    return verifyEmailOtp(email, input);
  }

  function verifyEmailOtp(email, token) {
    // New-user signups verify as type 'signup'; repeat logins as 'email'. Try both.
    var types = ['email', 'signup', 'magiclink'];
    var lastErr = 'Invalid or expired code';
    function attempt(i) {
      if (i >= types.length) return Promise.reject(new Error(lastErr));
      return fetch(cfg().SUPABASE_URL + '/auth/v1/verify', {
        method: 'POST', headers: headers(),
        body: JSON.stringify({ type: types[i], email: email, token: token })
      }).then(function (r) {
        return r.json().then(function (d) {
          if (r.ok && d.access_token) {
            return setSession({
              access_token: d.access_token, refresh_token: d.refresh_token,
              expires_at: d.expires_at, user: { email: (d.user && d.user.email) || email, id: (d.user && d.user.id) }
            });
          }
          lastErr = d.msg || d.error_description || lastErr;
          return attempt(i + 1);
        });
      }).catch(function () { return attempt(i + 1); });
    }
    return attempt(0);
  }

  // Google — delegated to the background service worker (chrome.identity).
  function signInGoogle() {
    return new Promise(function (res, rej) {
      chrome.runtime.sendMessage({ type: 'sponzza-google' }, function (reply) {
        if (chrome.runtime.lastError) return rej(new Error(chrome.runtime.lastError.message));
        if (!reply || !reply.ok) return rej(new Error((reply && reply.error) || 'Google sign-in failed'));
        res(reply.session);
      });
    });
  }

  function refresh() {
    return getSession().then(function (s) {
      if (!s || !s.refresh_token) return Promise.reject(new Error('no session'));
      return fetch(cfg().SUPABASE_URL + '/auth/v1/token?grant_type=refresh_token', {
        method: 'POST', headers: headers(),
        body: JSON.stringify({ refresh_token: s.refresh_token })
      }).then(function (r) { return r.json(); }).then(function (d) {
        if (!d.access_token) return Promise.reject(new Error('refresh failed'));
        return setSession({ access_token: d.access_token, refresh_token: d.refresh_token, expires_at: d.expires_at, user: s.user });
      });
    });
  }

  return {
    getSession: getSession, signOut: signOut, refresh: refresh,
    sendEmailOtp: sendEmailOtp, verifyEmailOtp: verifyEmailOtp, verifyInput: verifyInput, signInGoogle: signInGoogle
  };
})();
