/**
 * Bloqueio de print / gravacao de tela (FLAG_SECURE no Android).
 * Politica definida pelo RH em Configuracoes > Aplicativo (tenants.app_screen_capture_allowed).
 */
(function (global) {
  'use strict';

  var LS_SCREEN_CAPTURE = 'registropro_tenant_screen_capture_allowed_v1';
  var appFeaturesSyncPromise = null;

  function isNativeShell() {
    try {
      if (!!global.cordova || !!global.Cordova) return true;
      var p = (global.location && global.location.protocol || '').toLowerCase();
      if (p === 'file:') return true;
      var h = (global.location && global.location.hostname || '').toLowerCase();
      if (h === 'localhost' || h === '127.0.0.1') {
        return p === 'https:' || p === 'http:' || p === 'ionic:' || p === 'capacitor:';
      }
    } catch (e0) {}
    return false;
  }

  function safeGetItem(key) {
    try {
      return localStorage.getItem(key) || '';
    } catch (e) {
      return '';
    }
  }

  function safeSetItem(key, value) {
    try {
      localStorage.setItem(key, value);
    } catch (e) {}
  }

  function readCachedScreenCaptureAllowed() {
    return safeGetItem(LS_SCREEN_CAPTURE) === '1';
  }

  function registroProEmployeeMayCaptureScreen() {
    return readCachedScreenCaptureAllowed();
  }

  function setScreenCaptureAllowedNative(allowed) {
    function run() {
      try {
        if (
          global.registroProScreenCapture &&
          typeof global.registroProScreenCapture.setAllowed === 'function'
        ) {
          global.registroProScreenCapture.setAllowed(
            allowed,
            function () {},
            function () {}
          );
          return;
        }
      } catch (e0) {}
      try {
        if (global.cordova && typeof global.cordova.exec === 'function') {
          global.cordova.exec(function () {}, function () {}, 'ScreenCapture', 'setAllowed', [allowed]);
        }
      } catch (e1) {}
    }

    if (global.cordova && global.cordova.platformId) {
      run();
      return;
    }
    document.addEventListener('deviceready', run, { once: true });
  }

  function registroProApplyScreenCapturePolicy() {
    if (!isNativeShell()) return;
    setScreenCaptureAllowedNative(registroProEmployeeMayCaptureScreen());
  }

  function registroProSyncAppFeaturesForScreenCapture() {
    if (appFeaturesSyncPromise) return appFeaturesSyncPromise;

    appFeaturesSyncPromise = new Promise(function (resolve) {
      var token = safeGetItem('auth_token');
      if (!token || typeof global.registroProGetAppFeaturesApiUrl !== 'function') {
        registroProApplyScreenCapturePolicy();
        appFeaturesSyncPromise = null;
        resolve(false);
        return;
      }

      var tenantSlug = safeGetItem('tenant_slug');
      var employeeId = safeGetItem('employee_id');
      var qs = '';
      if (tenantSlug && employeeId) {
        qs =
          '?tenant_slug=' + encodeURIComponent(tenantSlug) + '&employee_id=' + encodeURIComponent(employeeId);
      }

      fetch(global.registroProGetAppFeaturesApiUrl() + qs, {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          Authorization: 'Bearer ' + token
        }
      })
        .then(function (res) {
          return res
            .json()
            .then(function (j) {
              return { ok: res.ok, json: j };
            })
            .catch(function () {
              return { ok: res.ok, json: null };
            });
        })
        .then(function (result) {
          var allowed = false;
          if (result && result.json && result.json.ok && result.json.data) {
            allowed = !!result.json.data.screen_capture_allowed;
          }
          safeSetItem(LS_SCREEN_CAPTURE, allowed ? '1' : '0');
          registroProApplyScreenCapturePolicy();
          appFeaturesSyncPromise = null;
          resolve(true);
        })
        .catch(function () {
          registroProApplyScreenCapturePolicy();
          appFeaturesSyncPromise = null;
          resolve(false);
        });
    });

    return appFeaturesSyncPromise;
  }

  /** Mantido para compatibilidade: sincroniza via app_features (nao mais por cargo). */
  function registroProSyncProfileForScreenCapture() {
    return registroProSyncAppFeaturesForScreenCapture();
  }

  function bootScreenCaptureModule() {
    if (!isNativeShell()) return;

    function onCordovaReady() {
      if (safeGetItem('auth_token')) {
        registroProSyncAppFeaturesForScreenCapture();
      } else {
        safeSetItem(LS_SCREEN_CAPTURE, '0');
        registroProApplyScreenCapturePolicy();
      }
    }

    if (global.cordova && global.cordova.platformId) {
      onCordovaReady();
    } else {
      document.addEventListener('deviceready', onCordovaReady, { once: true });
    }

    document.addEventListener(
      'resume',
      function () {
        if (safeGetItem('auth_token')) {
          registroProSyncAppFeaturesForScreenCapture();
        } else {
          safeSetItem(LS_SCREEN_CAPTURE, '0');
          registroProApplyScreenCapturePolicy();
        }
      },
      false
    );
  }

  global.registroProEmployeeMayCaptureScreen = registroProEmployeeMayCaptureScreen;
  global.registroProApplyScreenCapturePolicy = registroProApplyScreenCapturePolicy;
  global.registroProSyncAppFeaturesForScreenCapture = registroProSyncAppFeaturesForScreenCapture;
  global.registroProSyncProfileForScreenCapture = registroProSyncProfileForScreenCapture;

  bootScreenCaptureModule();
})(typeof window !== 'undefined' ? window : this);
