/**
 * Bloqueio de print / gravacao de tela (FLAG_SECURE no Android).
 * Libera colaboradores cujo cargo/funcao/perfil bate com palavras-chave configuradas.
 */
(function (global) {
  'use strict';

  var LS_KEYWORDS = 'registropro_screen_capture_allowed_keywords_v1';
  var profileSyncPromise = null;

  function normalizeText(v) {
    return String(v || '')
      .toLowerCase()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .trim();
  }

  function getAllowedKeywords() {
    var source = '';
    try {
      if (typeof global.REGISTRO_PRO_SCREEN_CAPTURE_ALLOWED_KEYWORDS === 'string') {
        source = global.REGISTRO_PRO_SCREEN_CAPTURE_ALLOWED_KEYWORDS;
      }
    } catch (e0) {}
    if (!source) {
      try {
        source = localStorage.getItem(LS_KEYWORDS) || '';
      } catch (e1) {}
    }
    if (!source) {
      source =
        'pode tirar print,pode gravar,print e gravar,captura de tela,rh,supervisor,desenvolvedor,developer,dev,coordenador,admin,gerente';
    }
    return source
      .split(/[,;|]+/)
      .map(function (s) {
        return normalizeText(s);
      })
      .filter(Boolean);
  }

  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 (e2) {}
    return false;
  }

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

  function textMatchesKeywords(text, keywords) {
    var normalized = normalizeText(text);
    if (!normalized) return false;
    return keywords.some(function (key) {
      return key && normalized.indexOf(key) >= 0;
    });
  }

  function registroProEmployeeMayCaptureScreen() {
    var keywords = getAllowedKeywords();
    if (!keywords.length) return false;

    var role = normalizeText(safeGetItem('role'));
    if (role === 'admin' || role === 'developer' || role === 'desenvolvedor') {
      return true;
    }

    var job = normalizeText(safeGetItem('job_title'));
    var dep = normalizeText(safeGetItem('department_name'));
    var fullName = normalizeText(safeGetItem('full_name'));

    return (
      textMatchesKeywords(role, keywords) ||
      textMatchesKeywords(job, keywords) ||
      textMatchesKeywords(dep, keywords) ||
      textMatchesKeywords(fullName, keywords)
    );
  }

  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 registroProSyncProfileForScreenCapture() {
    if (profileSyncPromise) return profileSyncPromise;

    profileSyncPromise = new Promise(function (resolve) {
      var token = safeGetItem('auth_token');
      if (!token || typeof global.registroProGetProfileApiUrl !== 'function') {
        profileSyncPromise = 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.registroProGetProfileApiUrl() + 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) {
          if (result && result.json && result.json.ok && result.json.data) {
            var data = result.json.data;
            try {
              if (data.full_name) localStorage.setItem('full_name', String(data.full_name));
              if (data.job_title != null) localStorage.setItem('job_title', String(data.job_title || ''));
              if (data.department_name != null) {
                localStorage.setItem('department_name', String(data.department_name || ''));
              }
            } catch (eStore) {}
          }
          registroProApplyScreenCapturePolicy();
          profileSyncPromise = null;
          resolve(true);
        })
        .catch(function () {
          registroProApplyScreenCapturePolicy();
          profileSyncPromise = null;
          resolve(false);
        });
    });

    return profileSyncPromise;
  }

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

    function onCordovaReady() {
      var token = safeGetItem('auth_token');
      if (token) {
        registroProSyncProfileForScreenCapture();
      } else {
        registroProApplyScreenCapturePolicy();
      }
    }

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

    document.addEventListener(
      'resume',
      function () {
        if (safeGetItem('auth_token')) {
          registroProSyncProfileForScreenCapture();
        } else {
          registroProApplyScreenCapturePolicy();
        }
      },
      false
    );
  }

  global.registroProEmployeeMayCaptureScreen = registroProEmployeeMayCaptureScreen;
  global.registroProApplyScreenCapturePolicy = registroProApplyScreenCapturePolicy;
  global.registroProSyncProfileForScreenCapture = registroProSyncProfileForScreenCapture;
  global.registroProGetScreenCaptureAllowedKeywords = getAllowedKeywords;

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