/**
 * =============================================================================
 * API RegistroPro — URLs centralizadas (mesmo espírito de routes_exemplo.js)
 *
 * Troque o IP da LAN (variável REGISTRO_PRO_LAN_IP) ao mudar de Wi‑Fi.
 * Os caminhos da API ficam em REGISTRO_PRO_ROUTES.
 *
 * Produção em UM lugar no código (opcional):
 *   Preencha REGISTRO_PRO_DEPLOY_API_BASE abaixo (URL da pasta .../desktop/public/api, sem barra final).
 *   Todas as páginas que carregam este arquivo usam essa base automaticamente.
 *
 * Opcional em runtime (sem editar código / sobrescreve o deploy fixo):
 *   localStorage.setItem('API_BASE_URL', 'https://SEU_IP/.../desktop/public/api');
 *   (No celular / WebView costuma ser obrigatório HTTPS para o IP da LAN.)
 *
 * Legado (URL completa do login):
 *   localStorage.setItem('LOGIN_API_URL', 'http://.../auth/login.php');
 * =============================================================================
 */
(function (global) {
  'use strict';

  // # ===============================
  // # HOSPEDAGEM (ATIVO) — API em produção para APK e navegador
  // # ===============================
  /**
   * URL base da API no servidor (pasta .../desktop/public/api, SEM barra no final).
   * Com este valor preenchido, o app ignora IP da LAN e localhost no celular.
   */
  var REGISTRO_PRO_DEPLOY_API_BASE = 'https://controle.pro-control.site/projetos/apps/ponto-saas/desktop/public/api';

  // # ===============================
  // # LOCAL (DESATIVADO) — descomente para testar no XAMPP / mesma Wi‑Fi do PC
  // # ===============================
  //
  // Windows: tecla Windows + R → cmd → Enter → digite: ipconfig
  // Procure o "Endereço IPv4" do adaptador Wi‑Fi (ex.: 192.168.0.15, 10.0.0.7).
  // Celular e PC precisam estar na mesma rede.
  //
  // /** Só o host IPv4 do PC (sem http://) — app no celular usa isso */
  // var REGISTRO_PRO_LAN_IP = '192.168.1.8';
  //
  // /** Caminho até a pasta /api do projeto (XAMPP) */
  // var REGISTRO_PRO_API_PATH = '/projetos/apps/ponto-saas/desktop/public/api';
  //
  // /**
  //  * Base no app nativo / file:// (celular na mesma Wi‑Fi do PC).
  //  * Muitos WebViews/Android bloqueiam HTTP para IP da LAN — use HTTPS no Apache (cert. local ou mkcert).
  //  */
  // var REGISTRO_PRO_API_BASE = 'https://' + REGISTRO_PRO_LAN_IP + REGISTRO_PRO_API_PATH;
  //
  // /** Navegador no PC (XAMPP) — HTTP costuma bastar no localhost */
  // var REGISTRO_PRO_API_BASE_LOCALHOST = 'http://localhost' + REGISTRO_PRO_API_PATH;
  //
  // Para voltar ao local: comente REGISTRO_PRO_DEPLOY_API_BASE acima ('') e descomente o bloco LOCAL.

  /** Caminho relativo (inferência por URL da página); com hospedagem ativa a base vem de REGISTRO_PRO_DEPLOY_API_BASE. */
  var REGISTRO_PRO_API_PATH = '/projetos/apps/ponto-saas/desktop/public/api';

  // Stubs — não usados enquanto REGISTRO_PRO_DEPLOY_API_BASE estiver preenchido (ver bloco LOCAL acima).
  var REGISTRO_PRO_LAN_IP = '';
  var REGISTRO_PRO_API_BASE = '';
  var REGISTRO_PRO_API_BASE_LOCALHOST = '';

  /**
   * Produção automática por domínio atual:
   * Se o app estiver aberto em http(s), tenta inferir a raiz do projeto a partir de
   * ".../aplicativo/registropro/www" e monta ".../desktop/public/api".
   * Exemplos:
   * - https://dominio.com/aplicativo/registropro/www/login.html
   *   => https://dominio.com/desktop/public/api
   * - https://dominio.com/projetos/apps/ponto-saas/aplicativo/registropro/www/login.html
   *   => https://dominio.com/projetos/apps/ponto-saas/desktop/public/api
   */
  function registroProInferDeployApiBaseFromLocation() {
    try {
      if (!global.location) return '';
      var proto = String(global.location.protocol || '').toLowerCase();
      if (proto !== 'http:' && proto !== 'https:') return '';
      var origin = String(global.location.origin || '');
      var path = String(global.location.pathname || '');
      if (!origin) return '';

      var marker = '/aplicativo/registropro/www';
      var idx = path.toLowerCase().indexOf(marker);
      if (idx >= 0) {
        var projectBase = path.slice(0, idx);
        return normalizeBase(origin + projectBase + '/desktop/public/api');
      }

      return normalizeBase(origin + '/desktop/public/api');
    } catch (e) {
      return '';
    }
  }

  // # ===============================
  // # ROTAS — relativas à base (como url + "listar/confirmar_conta.php" no exemplo)
  // # Só edite aqui se o backend mudar o path do PHP
  // # ===============================

  var REGISTRO_PRO_ROUTES = {
    login: 'auth/login.php',
    clientLog: 'auth/client_log.php',
    passwordRecoverRequest: 'auth/password_recover_request.php',
    passwordResetStart: 'auth/password_reset_start.php',
    passwordResetWithSelfie: 'auth/password_reset_with_selfie.php',
    employeeProfile: 'employee/profile.php',
    employeeProfileUpdate: 'employee/profile_update.php',
    employeeProfileUpload: 'employee/profile_upload.php',
    lastPunch: 'point/last_punch.php',
    punchList: 'point/punch_list.php',
    punchCreate: 'point/punch_create.php',
    /** Colaborador: regras de ponto (point_rules) para o funcionário logado */
    punchRulesResolve: 'employee/punch_rules_resolve.php',
    /** Colaborador: registro por botão — só token, geo completa */
    punchButtonRegister: 'employee/punch_button_register.php',
    /** Colaborador: endereço a partir de lat/lon (Nominatim no servidor) */
    reverseGeocode: 'employee/reverse_geocode.php',
    /** Colaborador: lista de benefícios do funcionário logado */
    employeeBenefitsList: 'employee/benefits_list.php',
    absenceList: 'absence/absence_list.php',
    timelineEventsList: 'employee/timeline_events_list.php',
    timelineEventAppend: 'employee/timeline_event_append.php',
    holeritesList: 'employee/holerites_list.php',
    holeriteView: 'employee/holerite_view.php',
    holeriteSign: 'employee/holerite_sign.php',
    managerHoleritesUpload: 'manager/holerites_upload.php',
    /** Colaborador: lê flags (ex.: atestado_scan_enabled) */
    appFeatures: 'employee/app_features.php',
    /** Colaborador: upload de documentos (atestados/comprovantes) */
    employeeDocumentUpload: 'employee/document_upload.php',
    /** Colaborador: lista documentos por pasta (ex.: dados_pessoais) */
    employeeDocumentsList: 'employee/documents_list.php',
    /** Colaborador: abre/baixa documento pelo id (Authorization Bearer) */
    employeeDocumentDownload: 'employee/document_download.php',
    /** Colaborador: assinatura de documento com selfie + geolocalização */
    employeeDocumentSign: 'employee/document_sign.php',
    /** Colaborador: só upload do vídeo de consentimento (etapa 1 antes de document_sign) */
    employeeDocumentConsentVideoUpload: 'employee/document_sign_consent_video_upload.php',
    /** Colaborador: consulta status de assinatura do documento */
    employeeDocumentSignStatus: 'employee/document_sign_status.php',
    /** Colaborador (Contrato): assinatura dedicada (isolada do fluxo de documentos) */
    employeeContractSign: 'employee/contract_sign.php',
    /** Colaborador (Contrato): upload dedicado do vídeo de consentimento */
    employeeContractConsentVideoUpload: 'employee/contract_sign_consent_video_upload.php',
    /** Colaborador (Contrato): status dedicado da assinatura */
    employeeContractSignStatus: 'employee/contract_sign_status.php',
    /** Colaborador: banners de propaganda do painel (cadastrados pelo RH) */
    appBanners: 'employee/app_banners.php',
    /** Painel RH: GET/POST/PATCH/DELETE banners do app */
    managerAppBanners: 'manager/app_banners.php',
    /** Painel RH: GET/PATCH app_atestado_scan_enabled */
    managerTenantAppFeatures: 'manager/tenant_app_features.php',
    patrolScan: 'employee/patrol_scan.php',
    patrolScansRecent: 'employee/patrol_scans_recent.php',
    patrolRouteStatus: 'employee/patrol_route_status.php',
    managerPatrolCheckpoints: 'manager/patrol_checkpoints.php',
    managerPatrolScansReport: 'manager/patrol_scans_report.php',
    /** Painel RH: GET imagem selfie da leitura (?scan_id=) — Authorization Bearer */
    managerPatrolSelfie: 'manager/patrol_selfie.php',
    cleaningScheduleToday: 'employee/cleaning_schedule_today.php',
    cleaningComplete: 'employee/cleaning_complete.php',
    solicitacoesColleagues: 'employee/solicitacoes_colleagues.php',
    /** Turno do colaborador (cadastro RH → default_work_shift_type_id) */
    solicitacoesMyWorkShifts: 'employee/my_work_shifts.php',
    solicitacoesSubmit: 'employee/solicitacoes_submit.php',
    solicitacoesList: 'employee/solicitacoes_list.php',
    managerCleaningCheckpoints: 'manager/cleaning_checkpoints.php',
    managerCleaningPlans: 'manager/cleaning_plans.php',
    managerCleaningAssignments: 'manager/cleaning_assignments.php',
    condominiumZeladorLogSave: 'employee/condominium_zelador_log_save.php',
    condominiumZeladorLogsList: 'employee/condominium_zelador_logs_list.php',
    condominiumZeladorLogPhoto: 'employee/condominium_zelador_log_photo.php',
    supervisorRouteTrack: 'employee/supervisor_route_track.php'
  };

  /** Corrige digitação comum: https//host → https://host (URL inválida = Failed to fetch) */
  function fixSchemeTypos(s) {
    if (!s || typeof s !== 'string') return s;
    return s
      .replace(/^https\/\//i, 'https://')
      .replace(/^http\/\//i, 'http://');
  }

  function normalizeBase(s) {
    if (!s || typeof s !== 'string') return '';
    s = fixSchemeTypos(s.trim());
    return s.replace(/\/+$/, '');
  }

  /** LAN / localhost — no telemóvel em 4G não alcança; localStorage antigo quebra o login no browser. */
  function registroProIsLanOrLocalhostUrl(s) {
    if (!s || typeof s !== 'string') return false;
    if (/localhost|127\.0\.0\.1/i.test(s)) return true;
    return /\b(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.)/.test(s);
  }

  function registroProIsBrowserOnPublicHost() {
    try {
      var loc = global.location;
      if (!loc || !loc.hostname) return false;
      var h = String(loc.hostname).toLowerCase();
      return h !== '' && h !== 'localhost' && h !== '127.0.0.1';
    } catch (e) {
      return false;
    }
  }

  function registroProIsBrowserOnLocalHost() {
    try {
      var loc = global.location;
      if (!loc || !loc.hostname) return false;
      var h = String(loc.hostname).toLowerCase();
      return h === 'localhost' || h === '127.0.0.1';
    } catch (e) {
      return false;
    }
  }

  function isNativeApp() {
    try {
      if (typeof global.cordova !== 'undefined') return true;
      if (typeof global.Capacitor !== 'undefined') return true;
      if (global.webkit && global.webkit.messageHandlers) return true;
      if (global.location && global.location.protocol === 'file:') return true;
      var ua = (global.navigator && global.navigator.userAgent) || '';
      if (/Cordova/i.test(ua)) return true;
      if (/wv/i.test(ua) && /Android/i.test(ua)) return true;
    } catch (e) {}
    return false;
  }

  function registroProGetDeployApiBaseNormalized() {
    try {
      var explicit = normalizeBase(
        fixSchemeTypos(typeof REGISTRO_PRO_DEPLOY_API_BASE === 'string' ? REGISTRO_PRO_DEPLOY_API_BASE : '')
      );
      if (explicit) return explicit;
      return normalizeBase(registroProInferDeployApiBaseFromLocation());
    } catch (e) {
      return '';
    }
  }

  function registroProGetApiBase() {
    var nativeApp = isNativeApp();
    var onPublic = registroProIsBrowserOnPublicHost();
    var onLocalHost = registroProIsBrowserOnLocalHost();
    var deployBase = registroProGetDeployApiBaseNormalized();
    var deployOk = !!(deployBase && /^https?:\/\//i.test(deployBase));

    // Regra forte para APK/Cordova:
    // se há base de produção configurada, usa SEMPRE ela e ignora localStorage legado.
    if (nativeApp && deployOk) {
      try {
        if (global.localStorage) {
          // Evita reaproveitar URLs antigas (localhost/LAN) em builds móveis.
          global.localStorage.removeItem('API_BASE_URL');
          global.localStorage.removeItem('LOGIN_API_URL');
        }
      } catch (eNativeStorage) {}
      return deployBase;
    }

    // Ambiente local de desenvolvimento (Live Server / localhost):
    // força API no MESMO host da página (127.0.0.1 ou localhost) para evitar
    // CORS/preflight desnecessário e falhas "TypeError: Failed to fetch".
    if (!nativeApp && onLocalHost) {
      try {
        var locLocal = global.location;
        var protoLocal = (locLocal.protocol || 'http:').replace(/:$/, '');
        // Cordova/Android 9+ costuma servir o www em https://localhost ; a regra antiga
        // usava API http://localhost → o WebView bloqueia (conteúdo misto) e o fetch falha.
        if (deployOk && protoLocal === 'https') {
          return deployBase;
        }
        var portLocal = String(locLocal.port || '');
        var isDevStaticPort = portLocal !== '' && portLocal !== '80' && portLocal !== '443';
        // Em portas de dev (ex.: Live Server 5500), o host não executa PHP.
        // Nesses casos, força XAMPP localhost para a API.
        if (isDevStaticPort) {
          return normalizeBase(REGISTRO_PRO_API_BASE_LOCALHOST);
        }
        if (protoLocal === 'http' || protoLocal === 'https') {
          var sameHostLocalBase = normalizeBase(protoLocal + '://' + locLocal.host + REGISTRO_PRO_API_PATH);
          if (sameHostLocalBase && /^https?:\/\//i.test(sameHostLocalBase)) {
            return sameHostLocalBase;
          }
        }
      } catch (eLocalHost) {}
      try {
        var locFb = global.location;
        var protoFb = (locFb.protocol || '').replace(/:$/, '').toLowerCase();
        if (protoFb === 'https' && locFb.host) {
          var httpsFallback = normalizeBase('https://' + locFb.host + REGISTRO_PRO_API_PATH);
          if (httpsFallback && /^https:\/\//i.test(httpsFallback)) {
            return httpsFallback;
          }
        }
      } catch (eFb) {}
      return normalizeBase(REGISTRO_PRO_API_BASE_LOCALHOST);
    }

    try {
      var custom = global.localStorage && global.localStorage.getItem('API_BASE_URL');
      custom = fixSchemeTypos(custom || '');
      if (custom && /^https?:\/\//i.test(custom)) {
        var isLanCustom = registroProIsLanOrLocalhostUrl(custom);
        var skipCustomLanBrowser = onPublic && !nativeApp && isLanCustom;
        // APK (file://): localStorage antigo com IP da LAN não pode sobrepor URL de produção
        var skipCustomLanNative = nativeApp && deployOk && isLanCustom;
        if (!(skipCustomLanBrowser || skipCustomLanNative)) {
          return normalizeBase(custom);
        }
      }
    } catch (e) {}

    try {
      var loginFull = global.localStorage && fixSchemeTypos(global.localStorage && global.localStorage.getItem('LOGIN_API_URL') || '');
      if (loginFull && /^https?:\/\//i.test(loginFull) && /\/auth\/login\.php/i.test(loginFull)) {
        var extracted = loginFull.replace(/\/auth\/login\.php$/i, '');
        var skipLegacyLan =
          (!isNativeApp() && onPublic && registroProIsLanOrLocalhostUrl(extracted)) ||
          (nativeApp && deployOk && registroProIsLanOrLocalhostUrl(extracted));
        if (!skipLegacyLan) {
          if (nativeApp) {
            if (extracted.indexOf('localhost') !== -1 || extracted.indexOf('127.0.0.1') !== -1) {
              return normalizeBase(REGISTRO_PRO_API_BASE);
            }
          }
          return normalizeBase(extracted);
        }
      }
    } catch (e2) {}

    if (deployOk) {
      return deployBase;
    }

    if (!nativeApp && onPublic) {
      try {
        var loc = global.location;
        var proto = (loc.protocol || 'https:').replace(/:$/, '');
        if (proto === 'http' || proto === 'https') {
          var sameHostBase = normalizeBase(proto + '://' + loc.host + REGISTRO_PRO_API_PATH);
          if (sameHostBase && /^https?:\/\//i.test(sameHostBase)) {
            return sameHostBase;
          }
        }
      } catch (eSame) {}
    }

    if (nativeApp) {
      return normalizeBase(REGISTRO_PRO_API_BASE);
    }
    return normalizeBase(REGISTRO_PRO_API_BASE_LOCALHOST);
  }

  /**
   * Monta URL final: base + rota nomeada (REGISTRO_PRO_ROUTES).
   * @param {string} routeKey — ex.: 'login', 'lastPunch'
   */
  function registroProApiUrl(routeKey) {
    var rel = REGISTRO_PRO_ROUTES[routeKey];
    if (!rel || typeof rel !== 'string') {
      try {
        console.warn('[api-config] Rota desconhecida:', routeKey);
      } catch (e) {}
      return registroProGetApiBase() + '/';
    }
    return registroProGetApiBase() + '/' + rel.replace(/^\/+/, '');
  }

  function registroProGetLoginApiUrl() {
    return registroProApiUrl('login');
  }

  function registroProGetClientLogApiUrl() {
    return registroProApiUrl('clientLog');
  }

  function registroProGetProfileApiUrl() {
    return registroProApiUrl('employeeProfile');
  }

  function registroProGetProfileUpdateApiUrl() {
    return registroProApiUrl('employeeProfileUpdate');
  }

  function registroProGetProfileUploadApiUrl() {
    return registroProApiUrl('employeeProfileUpload');
  }

  function registroProGetLastPunchApiUrl() {
    return registroProApiUrl('lastPunch');
  }

  function registroProGetPunchListApiUrl() {
    return registroProApiUrl('punchList');
  }

  function registroProGetPunchCreateApiUrl() {
    return registroProApiUrl('punchCreate');
  }

  function registroProGetPunchRulesResolveApiUrl() {
    return registroProApiUrl('punchRulesResolve');
  }

  function registroProGetPunchButtonRegisterApiUrl() {
    return registroProApiUrl('punchButtonRegister');
  }

  /** Mesmo endpoint de punch_button_register.php — use registration_channel: facial no JSON quando for o caso. */
  function registroProGetPunchRegisterApiUrl() {
    return registroProApiUrl('punchButtonRegister');
  }

  function registroProGetReverseGeocodeApiUrl(lat, lon) {
    var base = registroProApiUrl('reverseGeocode');
    var sep = base.indexOf('?') >= 0 ? '&' : '?';
    return (
      base +
      sep +
      'lat=' +
      encodeURIComponent(String(lat)) +
      '&lon=' +
      encodeURIComponent(String(lon))
    );
  }

  function registroProGetEmployeeBenefitsListApiUrl() {
    return registroProApiUrl('employeeBenefitsList');
  }

  function registroProGetAbsenceListApiUrl() {
    return registroProApiUrl('absenceList');
  }

  function registroProGetTimelineEventsListApiUrl() {
    return registroProApiUrl('timelineEventsList');
  }

  function registroProGetTimelineEventAppendApiUrl() {
    return registroProApiUrl('timelineEventAppend');
  }

  function registroProGetRecoverPasswordApiUrl() {
    return registroProApiUrl('passwordRecoverRequest');
  }

  function registroProGetPasswordResetWithSelfieApiUrl() {
    return registroProApiUrl('passwordResetWithSelfie');
  }

  function registroProGetPasswordResetStartApiUrl() {
    return registroProApiUrl('passwordResetStart');
  }

  function registroProGetHoleritesListApiUrl() {
    return registroProApiUrl('holeritesList');
  }

  /**
   * @param {string|number} holeriteId
   * @param {{ bundle?: boolean }} [opts] — bundle=1 solicita PDF unificado (holerite + espelho + assinatura), se existir
   */
  function registroProGetHoleriteViewApiUrl(holeriteId, opts) {
    opts = opts || {};
    var base = registroProApiUrl('holeriteView');
    var sep = base.indexOf('?') >= 0 ? '&' : '?';
    var u = base + sep + 'id=' + encodeURIComponent(String(holeriteId));
    if (opts.bundle) {
      u += '&bundle=1';
    }
    return u;
  }

  function registroProGetHoleriteSignApiUrl() {
    return registroProApiUrl('holeriteSign');
  }

  function registroProGetManagerHoleritesUploadApiUrl() {
    return registroProApiUrl('managerHoleritesUpload');
  }

  function registroProGetAppFeaturesApiUrl() {
    return registroProApiUrl('appFeatures');
  }

  function registroProGetEmployeeDocumentUploadApiUrl() {
    return registroProApiUrl('employeeDocumentUpload');
  }

  function registroProGetEmployeeDocumentsListApiUrl() {
    return registroProApiUrl('employeeDocumentsList');
  }

  function registroProGetEmployeeDocumentDownloadApiUrl(documentId) {
    var base = registroProApiUrl('employeeDocumentDownload');
    var sep = base.indexOf('?') >= 0 ? '&' : '?';
    return base + sep + 'id=' + encodeURIComponent(String(documentId));
  }

  /** Download direto pela REGISTRO_PRO_DEPLOY_API_BASE — fallback quando a heurística da API erra (ex.: WebView https). */
  function registroProGetEmployeeDocumentDownloadApiUrlFromDeploy(documentId) {
    try {
      var deploy = normalizeBase(registroProGetDeployApiBaseNormalized());
      if (!deploy || !/^https?:\/\//i.test(deploy)) return '';
      var rel = REGISTRO_PRO_ROUTES.employeeDocumentDownload;
      if (!rel || typeof rel !== 'string') return '';
      return deploy + '/' + rel.replace(/^\/+/, '') + '?id=' + encodeURIComponent(String(documentId));
    } catch (e) {
      return '';
    }
  }

  function registroProGetEmployeeDocumentSignApiUrl() {
    return registroProApiUrl('employeeDocumentSign');
  }

  function registroProGetEmployeeDocumentConsentVideoUploadApiUrl() {
    return registroProApiUrl('employeeDocumentConsentVideoUpload');
  }

  function registroProGetEmployeeDocumentSignStatusApiUrl(documentId) {
    var base = registroProApiUrl('employeeDocumentSignStatus');
    var sep = base.indexOf('?') >= 0 ? '&' : '?';
    return base + sep + 'document_id=' + encodeURIComponent(String(documentId));
  }

  function registroProGetEmployeeContractSignApiUrl() {
    return registroProApiUrl('employeeContractSign');
  }

  function registroProGetEmployeeContractConsentVideoUploadApiUrl() {
    return registroProApiUrl('employeeContractConsentVideoUpload');
  }

  function registroProGetEmployeeContractSignStatusApiUrl(documentId) {
    var base = registroProApiUrl('employeeContractSignStatus');
    var sep = base.indexOf('?') >= 0 ? '&' : '?';
    return base + sep + 'document_id=' + encodeURIComponent(String(documentId));
  }

  function registroProGetAppBannersApiUrl() {
    return registroProApiUrl('appBanners');
  }

  function registroProGetManagerAppBannersApiUrl() {
    return registroProApiUrl('managerAppBanners');
  }

  function registroProGetManagerTenantAppFeaturesApiUrl() {
    return registroProApiUrl('managerTenantAppFeatures');
  }

  function registroProGetPatrolScanApiUrl() {
    return registroProApiUrl('patrolScan');
  }

  function registroProGetPatrolScansRecentApiUrl() {
    return registroProApiUrl('patrolScansRecent');
  }

  function registroProGetPatrolRouteStatusApiUrl() {
    return registroProApiUrl('patrolRouteStatus');
  }

  function registroProGetManagerPatrolCheckpointsApiUrl() {
    return registroProApiUrl('managerPatrolCheckpoints');
  }

  function registroProGetManagerPatrolScansReportApiUrl() {
    return registroProApiUrl('managerPatrolScansReport');
  }

  function registroProGetManagerPatrolSelfieApiUrl(scanId) {
    var base = registroProApiUrl('managerPatrolSelfie');
    var sep = base.indexOf('?') >= 0 ? '&' : '?';
    return base + sep + 'scan_id=' + encodeURIComponent(String(scanId));
  }

  function registroProGetCleaningScheduleTodayApiUrl() {
    return registroProApiUrl('cleaningScheduleToday');
  }

  function registroProGetCleaningCompleteApiUrl() {
    return registroProApiUrl('cleaningComplete');
  }

  function registroProGetSolicitacoesColleaguesApiUrl() {
    return registroProApiUrl('solicitacoesColleagues');
  }

  function registroProGetSolicitacoesMyWorkShiftsApiUrl() {
    return registroProApiUrl('solicitacoesMyWorkShifts');
  }

  function registroProGetSolicitacoesSubmitApiUrl() {
    return registroProApiUrl('solicitacoesSubmit');
  }

  function registroProGetSolicitacoesListApiUrl() {
    return registroProApiUrl('solicitacoesList');
  }

  function registroProGetManagerCleaningCheckpointsApiUrl() {
    return registroProApiUrl('managerCleaningCheckpoints');
  }

  function registroProGetManagerCleaningPlansApiUrl() {
    return registroProApiUrl('managerCleaningPlans');
  }

  function registroProGetManagerCleaningAssignmentsApiUrl() {
    return registroProApiUrl('managerCleaningAssignments');
  }

  function registroProGetCondominiumZeladorLogSaveApiUrl() {
    return registroProApiUrl('condominiumZeladorLogSave');
  }

  function registroProGetCondominiumZeladorLogsListApiUrl(workDate) {
    var base = registroProApiUrl('condominiumZeladorLogsList');
    if (workDate && typeof workDate === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(workDate)) {
      var sep = base.indexOf('?') >= 0 ? '&' : '?';
      return base + sep + 'work_date=' + encodeURIComponent(workDate);
    }
    return base;
  }

  function registroProGetCondominiumZeladorLogPhotoApiUrl(logId, index) {
    var base = registroProApiUrl('condominiumZeladorLogPhoto');
    var sep = base.indexOf('?') >= 0 ? '&' : '?';
    return base + sep + 'log_id=' + encodeURIComponent(String(logId)) + '&i=' + encodeURIComponent(String(index));
  }

  function registroProGetSupervisorRouteTrackApiUrl() {
    return registroProApiUrl('supervisorRouteTrack');
  }

  /** Persiste LOGIN_API_URL para scripts legados */
  function registroProSyncLoginUrlToStorage() {
    try {
      if (!global.localStorage) return;
      global.localStorage.setItem('LOGIN_API_URL', registroProGetLoginApiUrl());
    } catch (e) {}
  }

  global.REGISTRO_PRO_ROUTES = REGISTRO_PRO_ROUTES;
  global.registroProApiUrl = registroProApiUrl;
  global.registroProGetApiBase = registroProGetApiBase;
  global.registroProGetLoginApiUrl = registroProGetLoginApiUrl;
  global.registroProGetClientLogApiUrl = registroProGetClientLogApiUrl;
  global.registroProGetProfileApiUrl = registroProGetProfileApiUrl;
  global.registroProGetProfileUpdateApiUrl = registroProGetProfileUpdateApiUrl;
  global.registroProGetProfileUploadApiUrl = registroProGetProfileUploadApiUrl;
  global.registroProGetLastPunchApiUrl = registroProGetLastPunchApiUrl;
  global.registroProGetPunchListApiUrl = registroProGetPunchListApiUrl;
  global.registroProGetPunchCreateApiUrl = registroProGetPunchCreateApiUrl;
  global.registroProGetPunchRulesResolveApiUrl = registroProGetPunchRulesResolveApiUrl;
  global.registroProGetPunchButtonRegisterApiUrl = registroProGetPunchButtonRegisterApiUrl;
  global.registroProGetPunchRegisterApiUrl = registroProGetPunchRegisterApiUrl;
  global.registroProGetReverseGeocodeApiUrl = registroProGetReverseGeocodeApiUrl;
  global.registroProGetEmployeeBenefitsListApiUrl = registroProGetEmployeeBenefitsListApiUrl;
  global.registroProGetAbsenceListApiUrl = registroProGetAbsenceListApiUrl;
  global.registroProGetTimelineEventsListApiUrl = registroProGetTimelineEventsListApiUrl;
  global.registroProGetTimelineEventAppendApiUrl = registroProGetTimelineEventAppendApiUrl;
  global.registroProGetRecoverPasswordApiUrl = registroProGetRecoverPasswordApiUrl;
  global.registroProGetPasswordResetStartApiUrl = registroProGetPasswordResetStartApiUrl;
  global.registroProGetPasswordResetWithSelfieApiUrl = registroProGetPasswordResetWithSelfieApiUrl;
  global.registroProGetHoleritesListApiUrl = registroProGetHoleritesListApiUrl;
  global.registroProGetHoleriteViewApiUrl = registroProGetHoleriteViewApiUrl;
  global.registroProGetHoleriteSignApiUrl = registroProGetHoleriteSignApiUrl;
  global.registroProGetManagerHoleritesUploadApiUrl = registroProGetManagerHoleritesUploadApiUrl;
  global.registroProGetAppFeaturesApiUrl = registroProGetAppFeaturesApiUrl;
  global.registroProGetEmployeeDocumentUploadApiUrl = registroProGetEmployeeDocumentUploadApiUrl;
  global.registroProGetEmployeeDocumentsListApiUrl = registroProGetEmployeeDocumentsListApiUrl;
  global.registroProGetEmployeeDocumentDownloadApiUrl = registroProGetEmployeeDocumentDownloadApiUrl;
  global.registroProGetEmployeeDocumentDownloadApiUrlFromDeploy = registroProGetEmployeeDocumentDownloadApiUrlFromDeploy;
  global.registroProGetEmployeeDocumentSignApiUrl = registroProGetEmployeeDocumentSignApiUrl;
  global.registroProGetEmployeeDocumentConsentVideoUploadApiUrl = registroProGetEmployeeDocumentConsentVideoUploadApiUrl;
  global.registroProGetEmployeeDocumentSignStatusApiUrl = registroProGetEmployeeDocumentSignStatusApiUrl;
  global.registroProGetEmployeeContractSignApiUrl = registroProGetEmployeeContractSignApiUrl;
  global.registroProGetEmployeeContractConsentVideoUploadApiUrl = registroProGetEmployeeContractConsentVideoUploadApiUrl;
  global.registroProGetEmployeeContractSignStatusApiUrl = registroProGetEmployeeContractSignStatusApiUrl;
  global.registroProGetAppBannersApiUrl = registroProGetAppBannersApiUrl;
  global.registroProGetManagerAppBannersApiUrl = registroProGetManagerAppBannersApiUrl;
  global.registroProGetManagerTenantAppFeaturesApiUrl = registroProGetManagerTenantAppFeaturesApiUrl;
  global.registroProGetPatrolScanApiUrl = registroProGetPatrolScanApiUrl;
  global.registroProGetPatrolScansRecentApiUrl = registroProGetPatrolScansRecentApiUrl;
  global.registroProGetPatrolRouteStatusApiUrl = registroProGetPatrolRouteStatusApiUrl;
  global.registroProGetManagerPatrolCheckpointsApiUrl = registroProGetManagerPatrolCheckpointsApiUrl;
  global.registroProGetManagerPatrolScansReportApiUrl = registroProGetManagerPatrolScansReportApiUrl;
  global.registroProGetManagerPatrolSelfieApiUrl = registroProGetManagerPatrolSelfieApiUrl;
  global.registroProGetCleaningScheduleTodayApiUrl = registroProGetCleaningScheduleTodayApiUrl;
  global.registroProGetCleaningCompleteApiUrl = registroProGetCleaningCompleteApiUrl;
  global.registroProGetSolicitacoesColleaguesApiUrl = registroProGetSolicitacoesColleaguesApiUrl;
  global.registroProGetSolicitacoesMyWorkShiftsApiUrl = registroProGetSolicitacoesMyWorkShiftsApiUrl;
  global.registroProGetSolicitacoesSubmitApiUrl = registroProGetSolicitacoesSubmitApiUrl;
  global.registroProGetSolicitacoesListApiUrl = registroProGetSolicitacoesListApiUrl;
  global.registroProGetManagerCleaningCheckpointsApiUrl = registroProGetManagerCleaningCheckpointsApiUrl;
  global.registroProGetManagerCleaningPlansApiUrl = registroProGetManagerCleaningPlansApiUrl;
  global.registroProGetManagerCleaningAssignmentsApiUrl = registroProGetManagerCleaningAssignmentsApiUrl;
  global.registroProGetCondominiumZeladorLogSaveApiUrl = registroProGetCondominiumZeladorLogSaveApiUrl;
  global.registroProGetCondominiumZeladorLogsListApiUrl = registroProGetCondominiumZeladorLogsListApiUrl;
  global.registroProGetCondominiumZeladorLogPhotoApiUrl = registroProGetCondominiumZeladorLogPhotoApiUrl;
  global.registroProGetSupervisorRouteTrackApiUrl = registroProGetSupervisorRouteTrackApiUrl;
  global.registroProSyncLoginUrlToStorage = registroProSyncLoginUrlToStorage;
  global.registroProIsNativeApp = isNativeApp;

  /** Video tutorial de permissoes (YouTube). Vazio = aviso no app. */
  var REGISTRO_PRO_PERMISSIONS_TUTORIAL_VIDEO_URL = '';
  global.REGISTRO_PRO_PERMISSIONS_TUTORIAL_VIDEO_URL = REGISTRO_PRO_PERMISSIONS_TUTORIAL_VIDEO_URL;

  /** Print/gravacao de tela: politica pelo RH (app_features.screen_capture_allowed) */
  (function registroProLoadScreenCaptureModule() {
    try {
      if (!isNativeApp()) return;
      var script = global.document.createElement('script');
      script.src = 'js/registropro-screen-capture.js';
      script.defer = true;
      (global.document.head || global.document.documentElement).appendChild(script);
    } catch (eLoadSc) {}
  })();

  /** Validação de sessão (token expirado → login) em páginas autenticadas */
  (function registroProLoadAuthModule() {
    try {
      var loc = global.location;
      if (!loc || !loc.pathname) return;
      var page = loc.pathname.split('/').pop().toLowerCase();
      var skip = {
        'login.html': 1,
        'splash.html': 1,
        'index.html': 1,
        'reset_passowrd.html': 1,
        'reset_passowrd_selfie.html': 1,
        'senha_alterada_sucesso.html': 1
      };
      if (skip[page]) return;
      var script = global.document.createElement('script');
      script.src = 'js/registropro-auth.js';
      script.defer = true;
      (global.document.head || global.document.documentElement).appendChild(script);
    } catch (eLoadAuth) {}
  })();
})(typeof window !== 'undefined' ? window : this);
