/* global React, Icon, fmtDate, parseDate */
// ============================================================
// Periodo.jsx — Sistema unificado de período do módulo Financeiro
//
// Exporta (via window):
//   resolvePeriodo(preset, custom) -> { inicio, fim }  (ISO, intervalo FECHADO)
//   filtrarPorPeriodo(rows, intervalo, campo) -> { dentro, semData }
//   campoBase(aba, baseId) -> nome da coluna a filtrar
//   FIN_BASES -> registro de bases por aba
//   useFinPeriodo() -> hook com estado global (localStorage) + base por aba
//   PeriodoFilter -> barra de UI (setas ‹ ›, presets, base, faixa sempre visível)
//
// Regras:
//   - IDs internos em ASCII ('mes-atual', 'mes:2026-07'); rótulos acentuados só na UI.
//   - Todo preset devolve intervalo fechado [inicio, fim]; nada de dt >= x aberto.
//   - localStorage sob 'tm-fin-periodo' com shape { v:1, preset, custom, base }.
//     Leitura em try/catch; se v !== 1 ou JSON inválido → default silencioso.
// ============================================================

var FIN_PERIODO_KEY   = 'tm-fin-periodo';
var FIN_PERIODO_EVENT = 'tm-fin-periodo-change';

var MESES_PT = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];

// ─── Utilitários de data (local, sem fuso) ──────────────────────
function _iso(d) {
  var y = d.getFullYear();
  var m = String(d.getMonth() + 1).padStart(2, '0');
  var dd = String(d.getDate()).padStart(2, '0');
  return y + '-' + m + '-' + dd;
}
function _hoje() { return _iso(new Date()); }
function _ultimoDia(y, m) { return new Date(y, m + 1, 0).getDate(); } // m 0-based
function _mesInterv(y, m) {
  return { inicio: _iso(new Date(y, m, 1)), fim: _iso(new Date(y, m, _ultimoDia(y, m))) };
}

// ─── (a) Resolvedor puro ────────────────────────────────────────
// Devolve SEMPRE { inicio, fim } em ISO. Para 'tudo' → { inicio:null, fim:null }.
function resolvePeriodo(preset, custom) {
  var hoje = new Date();
  var y = hoje.getFullYear(), m = hoje.getMonth();

  if (!preset) preset = 'mes-atual';

  // mês específico: 'mes:YYYY-MM'
  if (preset.indexOf('mes:') === 0) {
    var pm = preset.slice(4).split('-');
    var py = parseInt(pm[0], 10), pmo = parseInt(pm[1], 10) - 1;
    if (isFinite(py) && pmo >= 0 && pmo <= 11) return _mesInterv(py, pmo);
    return _mesInterv(y, m);
  }
  // ano específico: 'ano:YYYY'
  if (preset.indexOf('ano:') === 0) {
    var ay = parseInt(preset.slice(4), 10);
    if (isFinite(ay)) return { inicio: ay + '-01-01', fim: ay + '-12-31' };
    return { inicio: y + '-01-01', fim: y + '-12-31' };
  }

  switch (preset) {
    case 'hoje':
      return { inicio: _hoje(), fim: _hoje() };
    case '7d': {
      var ini = new Date(hoje); ini.setDate(ini.getDate() - 6);
      return { inicio: _iso(ini), fim: _hoje() };
    }
    case 'mes-atual':
      return _mesInterv(y, m);
    case 'mes-anterior': {
      var d = new Date(y, m - 1, 1);
      return _mesInterv(d.getFullYear(), d.getMonth());
    }
    case '90d': {
      var i3 = new Date(hoje); i3.setMonth(i3.getMonth() - 3);
      return { inicio: _iso(i3), fim: _hoje() };
    }
    case 'ano-atual':
      return { inicio: y + '-01-01', fim: y + '-12-31' };
    case 'custom': {
      var c = custom || {};
      return { inicio: c.inicio || null, fim: c.fim || null };
    }
    case 'tudo':
      return { inicio: null, fim: null };
    default:
      return _mesInterv(y, m);
  }
}

// ─── (b) Bases da data por aba (colunas que JÁ existem em db.js) ─
var FIN_BASES = {
  'contas-receber': {
    padrao: 'vencimento',
    opts: [
      { id: 'vencimento',  label: 'Vencimento',  campo: 'vencimento' },
      { id: 'recebimento', label: 'Recebimento', campo: 'data_pagamento' },
      { id: 'faturamento', label: 'Faturamento', campo: 'data_faturamento' },
    ],
  },
  'contas-pagar': {
    padrao: 'vencimento',
    opts: [
      { id: 'vencimento', label: 'Vencimento', campo: 'vencimento' },
      { id: 'pagamento',  label: 'Pagamento',  campo: 'data_pagamento' },
      { id: 'emissao',    label: 'Emissão',    campo: 'data_emissao' },
    ],
  },
  // Abas de base fixa (só mostram confirmados) — base exibida como texto:
  // Entradas/Saídas consomem fromDbContaRec/fromDbContaPag → coluna é 'data_pagamento'.
  // Só o Extrato monta objetos à mão com a chave 'data' (Financeiro_Sections.jsx).
  'entradas': { padrao: 'recebimento', fixo: true, opts: [{ id: 'recebimento', label: 'Recebimento', campo: 'data_pagamento' }] },
  'saidas':   { padrao: 'pagamento',   fixo: true, opts: [{ id: 'pagamento',   label: 'Pagamento',   campo: 'data_pagamento' }] },
  'extrato':  { padrao: 'movimentacao',fixo: true, opts: [{ id: 'movimentacao', label: 'Pagamento/Recebimento', campo: 'data' }] },
  'dre':      { padrao: 'caixa',       fixo: true, opts: [{ id: 'caixa', label: 'Pagamento/Recebimento', campo: 'data_pagamento' }] },
  // Dashboard mistura eixos (cada KPI tem o seu) → não mostra seletor de base
  'dashboard':{ padrao: 'vencimento',  fixo: true, semBase: true, opts: [{ id: 'vencimento', label: '', campo: 'vencimento' }] },
};

// Intervalo imediatamente anterior, de MESMA duração (para comparação no DRE).
// Preset mensal → mês-calendário anterior; anual → ano anterior; demais → bloco de
// mesma quantidade de dias logo antes. 'tudo' (sem limites) → null (sem comparação).
function intervaloAnterior(preset, intervalo) {
  if (!intervalo || (!intervalo.inicio && !intervalo.fim)) return null;
  if (_mesLike(preset)) {
    var d = new Date((intervalo.inicio || _hoje()) + 'T12:00:00');
    d.setMonth(d.getMonth() - 1);
    return _mesInterv(d.getFullYear(), d.getMonth());
  }
  if (_anoLike(preset)) {
    var y = parseInt((intervalo.inicio || _hoje()).slice(0, 4), 10) - 1;
    return { inicio: y + '-01-01', fim: y + '-12-31' };
  }
  if (!intervalo.inicio || !intervalo.fim) return null;
  var a = new Date(intervalo.inicio + 'T12:00:00');
  var b = new Date(intervalo.fim + 'T12:00:00');
  var dias = Math.round((b - a) / 86400000) + 1;
  var prevFim = new Date(a); prevFim.setDate(prevFim.getDate() - 1);
  var prevIni = new Date(prevFim); prevIni.setDate(prevIni.getDate() - (dias - 1));
  return { inicio: _iso(prevIni), fim: _iso(prevFim) };
}

function campoBase(aba, baseId) {
  var cfg = FIN_BASES[aba];
  if (!cfg) return 'vencimento';
  var found = null;
  for (var i = 0; i < cfg.opts.length; i++) { if (cfg.opts[i].id === baseId) { found = cfg.opts[i]; break; } }
  if (!found) found = cfg.opts[0];
  return found ? found.campo : 'vencimento';
}
function baseOpt(aba, baseId) {
  var cfg = FIN_BASES[aba];
  if (!cfg) return null;
  for (var i = 0; i < cfg.opts.length; i++) { if (cfg.opts[i].id === baseId) return cfg.opts[i]; }
  return cfg.opts[0];
}

// Extrai a data ISO (YYYY-MM-DD) de uma linha, dado o nome da coluna.
function baseDataISO(row, campo) {
  if (!row || !campo) return null;
  var v = row[campo];
  if (v == null) {
    var alt = { data_pagamento: 'dataPagamento', data_faturamento: 'dataFaturamento', data_emissao: 'dataEmissao' }[campo];
    if (alt) v = row[alt];
  }
  if (v == null || v === '' || v === '—') return null;
  var s = String(v).slice(0, 10);
  if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
  return parseDate(v) || null;
}

// Filtro central. Registros sem a data-base são EXCLUÍDOS e contados em semData.
// Sem filtro de data ('tudo') → devolve tudo, semData 0.
function filtrarPorPeriodo(rows, intervalo, campo) {
  rows = rows || [];
  if (!intervalo || (!intervalo.inicio && !intervalo.fim)) return { dentro: rows, semData: 0 };
  var semData = 0;
  var dentro = rows.filter(function (r) {
    var d = baseDataISO(r, campo);
    if (!d) { semData++; return false; }
    if (intervalo.inicio && d < intervalo.inicio) return false;
    if (intervalo.fim && d > intervalo.fim) return false;
    return true;
  });
  return { dentro: dentro, semData: semData };
}

// ─── Rótulos de exibição ────────────────────────────────────────
function _mesLike(preset) {
  return preset === 'mes-atual' || preset === 'mes-anterior' || preset.indexOf('mes:') === 0;
}
function _anoLike(preset) {
  return preset === 'ano-atual' || preset.indexOf('ano:') === 0;
}
// Rótulo do botão (nome do preset)
function rotuloPreset(preset) {
  if (preset.indexOf('mes:') === 0) {
    var pm = preset.slice(4).split('-');
    return MESES_PT[parseInt(pm[1], 10) - 1] + ' de ' + pm[0];
  }
  if (preset.indexOf('ano:') === 0) return preset.slice(4);
  var map = {
    'hoje': 'Hoje', '7d': 'Últimos 7 dias', 'mes-atual': 'Este mês',
    'mes-anterior': 'Mês passado', '90d': 'Últimos 3 meses', 'ano-atual': 'Este ano',
    'custom': 'Personalizado', 'tudo': 'Todo o período',
  };
  return map[preset] || 'Período';
}
// Rótulo concreto do centro (com setas)
function rotuloCentro(preset, intervalo) {
  if (preset === 'tudo') return 'Todo o período';
  if (_mesLike(preset)) {
    var d = new Date((intervalo.inicio || _hoje()) + 'T12:00:00');
    return MESES_PT[d.getMonth()] + ' de ' + d.getFullYear();
  }
  if (_anoLike(preset)) return (intervalo.inicio || '').slice(0, 4);
  if (preset === 'hoje') return fmtDate(intervalo.inicio);
  // 7d / 90d / custom → mostra a faixa
  if (intervalo.inicio && intervalo.fim) return fmtDate(intervalo.inicio) + ' – ' + fmtDate(intervalo.fim);
  if (intervalo.inicio) return 'A partir de ' + fmtDate(intervalo.inicio);
  if (intervalo.fim) return 'Até ' + fmtDate(intervalo.fim);
  return 'Período';
}
// Faixa ISO por extenso (sempre visível na meta quando o centro não é a faixa)
function rotuloFaixa(intervalo) {
  if (!intervalo || (!intervalo.inicio && !intervalo.fim)) return 'Todo o período';
  return fmtDate(intervalo.inicio) + ' – ' + fmtDate(intervalo.fim);
}

// ─── (c) Hook de estado global ──────────────────────────────────
var FIN_PERIODO_DEFAULT = { v: 1, preset: 'mes-atual', custom: { inicio: null, fim: null }, base: {} };
function _cloneDefault() { return { v: 1, preset: 'mes-atual', custom: { inicio: null, fim: null }, base: {} }; }

function lerFinPeriodo() {
  try {
    var raw = localStorage.getItem(FIN_PERIODO_KEY);
    if (!raw) return _cloneDefault();
    var obj = JSON.parse(raw);
    if (!obj || obj.v !== 1) return _cloneDefault();
    return {
      v: 1,
      preset: typeof obj.preset === 'string' ? obj.preset : 'mes-atual',
      custom: (obj.custom && typeof obj.custom === 'object')
        ? { inicio: obj.custom.inicio || null, fim: obj.custom.fim || null }
        : { inicio: null, fim: null },
      base: (obj.base && typeof obj.base === 'object') ? obj.base : {},
    };
  } catch (e) {
    return _cloneDefault();
  }
}
function gravarFinPeriodo(st) {
  try { localStorage.setItem(FIN_PERIODO_KEY, JSON.stringify(st)); } catch (e) { /* storage cheio/privado */ }
  try { window.dispatchEvent(new CustomEvent(FIN_PERIODO_EVENT)); } catch (e) { /* ok */ }
}

function useFinPeriodo() {
  var st = React.useState(lerFinPeriodo);
  var estado = st[0], setEstado = st[1];

  React.useEffect(function () {
    var h = function () { setEstado(lerFinPeriodo()); };
    window.addEventListener(FIN_PERIODO_EVENT, h);
    window.addEventListener('storage', h); // sincroniza entre abas do navegador
    return function () {
      window.removeEventListener(FIN_PERIODO_EVENT, h);
      window.removeEventListener('storage', h);
    };
  }, []);

  var mutate = function (next) { gravarFinPeriodo(Object.assign({}, estado, next)); };
  var intervalo = resolvePeriodo(estado.preset, estado.custom);

  return {
    preset: estado.preset,
    custom: estado.custom,
    intervalo: intervalo,
    baseDe: function (aba) {
      var cfg = FIN_BASES[aba];
      var padrao = cfg ? cfg.padrao : 'vencimento';
      // Base fixa: nunca lê do storage (é constante do código, não estado)
      if (cfg && cfg.fixo) return padrao;
      return (estado.base && estado.base[aba]) || padrao;
    },
    setPreset: function (p) { mutate({ preset: p }); },
    setCustom: function (c) { mutate({ preset: 'custom', custom: { inicio: c.inicio || null, fim: c.fim || null } }); },
    setBaseDe: function (aba, id) {
      var cfg = FIN_BASES[aba];
      if (cfg && cfg.fixo) return; // abas fixas não gravam base
      var base = Object.assign({}, estado.base); base[aba] = id;
      mutate({ base: base });
    },
    limpar: function () { mutate({ preset: 'tudo' }); },
    navegar: function (dir) {
      var p = estado.preset;
      if (_mesLike(p)) {
        var iv = resolvePeriodo(p, estado.custom);
        var d = new Date((iv.inicio || _hoje()) + 'T12:00:00');
        d.setMonth(d.getMonth() + dir);
        mutate({ preset: 'mes:' + d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') });
        return;
      }
      if (_anoLike(p)) {
        var ivy = resolvePeriodo(p, estado.custom);
        var yy = parseInt((ivy.inicio || _hoje()).slice(0, 4), 10) + dir;
        mutate({ preset: 'ano:' + yy });
        return;
      }
      // hoje / 7d / 90d / custom → desloca a faixa pela própria duração
      var cur = resolvePeriodo(p, estado.custom);
      if (!cur.inicio || !cur.fim) return; // 'tudo' → sem navegação
      var a = new Date(cur.inicio + 'T12:00:00');
      var b = new Date(cur.fim + 'T12:00:00');
      var dias = Math.round((b - a) / 86400000) + 1;
      a.setDate(a.getDate() + dir * dias);
      b.setDate(b.getDate() + dir * dias);
      mutate({ preset: 'custom', custom: { inicio: _iso(a), fim: _iso(b) } });
    },
  };
}

// Últimos N meses como opções { id:'mes:YYYY-MM', label:'Julho de 2026' }
function mesesRecentes(n) {
  var out = [];
  var d = new Date();
  for (var i = 0; i < n; i++) {
    var y = d.getFullYear(), m = d.getMonth();
    out.push({ id: 'mes:' + y + '-' + String(m + 1).padStart(2, '0'), label: MESES_PT[m] + ' de ' + y, curto: MESES_PT[m].slice(0, 3), ano: y });
    d.setMonth(d.getMonth() - 1);
  }
  return out;
}

// ─── (c) Componente de UI: PeriodoFilter ────────────────────────
// Props: { aba, count, semDataCount }
//   aba          — chave em FIN_BASES (define opções de base)
//   count        — nº de registros dentro do período (a tela calcula e passa)
//   semDataCount — nº de registros descartados por não terem a data-base
function PeriodoFilter(props) {
  var aba = props.aba;
  var per = useFinPeriodo();
  var menu = React.useState(null); // null | 'preset' | 'meses' | 'custom' | 'base'
  var open = menu[0], setOpen = menu[1];

  var cfg = FIN_BASES[aba] || { padrao: 'vencimento', opts: [] };
  var baseId = per.baseDe(aba);
  var baseAtual = baseOpt(aba, baseId) || { label: 'Vencimento' };
  var intervalo = per.intervalo;
  var isTudo = per.preset === 'tudo';

  var closeAll = function () { setOpen(null); };
  var pickPreset = function (id) { per.setPreset(id); closeAll(); };
  var pickMes = function (id) { per.setPreset(id); closeAll(); };
  var pickBase = function (id) { per.setBaseDe(aba, id); closeAll(); };

  var onKeyBar = function (e) { if (e.key === 'Escape') closeAll(); };

  var presetItens = [
    { id: 'hoje', label: 'Hoje' },
    { id: '7d', label: 'Últimos 7 dias' },
    { id: 'mes-atual', label: 'Este mês' },
    { id: 'mes-anterior', label: 'Mês passado' },
    { id: '90d', label: 'Últimos 3 meses' },
    { id: 'ano-atual', label: 'Este ano' },
  ];

  var mostrarFaixaNaMeta = _mesLike(per.preset) || _anoLike(per.preset) || per.preset === 'hoje' || isTudo;

  return (
    <div className="periodo-bar" onKeyDown={onKeyBar}>
      {/* Navegação: ‹ centro › */}
      <div className="periodo-nav">
        <button className="periodo-arrow" aria-label="Período anterior" disabled={isTudo}
          onClick={function () { if (!isTudo) per.navegar(-1); }}>
          <Icon name="chevron-left" size={16} />
        </button>

        <div className="periodo-centro-wrap">
          <button className="periodo-centro" aria-haspopup="true" aria-expanded={open === 'preset'}
            onClick={function () { setOpen(open === 'preset' ? null : 'preset'); }}>
            <Icon name="calendar" size={13} />
            <span>{rotuloCentro(per.preset, intervalo)}</span>
            <Icon name="chevron-down" size={13} />
          </button>

          {open === 'preset' && <>
            <div className="periodo-overlay" onClick={closeAll} />
            <div className="periodo-menu" role="menu">
              <div className="periodo-menu-head">Período</div>
              {presetItens.map(function (it) {
                var ativo = per.preset === it.id;
                return (
                  <div key={it.id} role="menuitem" tabIndex={0}
                    className={'periodo-menu-item' + (ativo ? ' ativo' : '')}
                    onClick={function () { pickPreset(it.id); }}
                    onKeyDown={function (e) { if (e.key === 'Enter') pickPreset(it.id); }}>
                    <span>{it.label}</span>
                    {ativo && <Icon name="check" size={13} />}
                  </div>
                );
              })}
              <div className="periodo-menu-sep" />
              <div className="periodo-menu-item" role="menuitem" tabIndex={0}
                onClick={function () { setOpen('meses'); }}
                onKeyDown={function (e) { if (e.key === 'Enter') setOpen('meses'); }}>
                <span>Escolher mês</span><Icon name="chevron-right" size={13} />
              </div>
              <div className={'periodo-menu-item' + (per.preset === 'custom' ? ' ativo' : '')} role="menuitem" tabIndex={0}
                onClick={function () { setOpen('custom'); }}
                onKeyDown={function (e) { if (e.key === 'Enter') setOpen('custom'); }}>
                <span>Personalizado</span>
                {per.preset === 'custom' && <Icon name="check" size={13} />}
              </div>
              <div className="periodo-menu-sep" />
              <div className={'periodo-menu-item' + (isTudo ? ' ativo' : '')} role="menuitem" tabIndex={0}
                onClick={function () { pickPreset('tudo'); }}
                onKeyDown={function (e) { if (e.key === 'Enter') pickPreset('tudo'); }}>
                <span>Todo o período</span>
                {isTudo && <Icon name="check" size={13} />}
              </div>
            </div>
          </>}

          {open === 'meses' && <>
            <div className="periodo-overlay" onClick={closeAll} />
            <div className="periodo-menu" role="menu">
              <div className="periodo-menu-item periodo-voltar" onClick={function () { setOpen('preset'); }}>
                <Icon name="chevron-left" size={12} /> Voltar
              </div>
              <div className="periodo-meses-grid">
                {mesesRecentes(18).map(function (mm) {
                  var ativo = per.preset === mm.id;
                  return (
                    <div key={mm.id} className={'periodo-mes-cell' + (ativo ? ' ativo' : '')}
                      onClick={function () { pickMes(mm.id); }}>
                      <div className="periodo-mes-nome">{mm.curto}</div>
                      <div className="periodo-mes-ano">{mm.ano}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          </>}

          {open === 'custom' && <>
            <div className="periodo-overlay" onClick={closeAll} />
            <div className="periodo-menu" role="menu">
              <div className="periodo-menu-item periodo-voltar" onClick={function () { setOpen('preset'); }}>
                <Icon name="chevron-left" size={12} /> Voltar
              </div>
              <div className="periodo-custom">
                <label>De</label>
                <input type="date" className="input" value={(per.custom && per.custom.inicio) || ''}
                  onChange={function (e) { per.setCustom({ inicio: e.target.value, fim: per.custom && per.custom.fim }); }} />
                <label>Até</label>
                <input type="date" className="input" value={(per.custom && per.custom.fim) || ''}
                  onChange={function (e) { per.setCustom({ inicio: per.custom && per.custom.inicio, fim: e.target.value }); }} />
                <button className="btn primary sm" style={{ width: '100%', marginTop: 8 }} onClick={closeAll}>Aplicar</button>
              </div>
            </div>
          </>}
        </div>

        <button className="periodo-arrow" aria-label="Próximo período" disabled={isTudo}
          onClick={function () { if (!isTudo) per.navegar(1); }}>
          <Icon name="chevron-right" size={16} />
        </button>
      </div>

      {/* Base da data */}
      {cfg.semBase ? null : cfg.fixo ? (
        <span className="periodo-base fixo" title="Base fixa nesta tela">por {baseAtual.label}</span>
      ) : (
        <div className="periodo-base-wrap">
          <button className="periodo-base" aria-haspopup="true" aria-expanded={open === 'base'}
            onClick={function () { setOpen(open === 'base' ? null : 'base'); }}>
            por {baseAtual.label} <Icon name="chevron-down" size={12} />
          </button>
          {open === 'base' && <>
            <div className="periodo-overlay" onClick={closeAll} />
            <div className="periodo-menu periodo-menu-base" role="menu">
              <div className="periodo-menu-head">Filtrar por</div>
              {cfg.opts.map(function (o) {
                var ativo = baseId === o.id;
                return (
                  <div key={o.id} role="menuitem" tabIndex={0}
                    className={'periodo-menu-item' + (ativo ? ' ativo' : '')}
                    onClick={function () { pickBase(o.id); }}
                    onKeyDown={function (e) { if (e.key === 'Enter') pickBase(o.id); }}>
                    <span>{o.label}</span>
                    {ativo && <Icon name="check" size={13} />}
                  </div>
                );
              })}
            </div>
          </>}
        </div>
      )}

      {/* Meta: faixa + contagem + aviso */}
      <div className="periodo-meta">
        {mostrarFaixaNaMeta && !isTudo && <span className="periodo-faixa">{rotuloFaixa(intervalo)}</span>}
        {typeof props.count === 'number' && (
          <span className="periodo-count">{mostrarFaixaNaMeta && !isTudo ? ' · ' : ''}{props.count} registro{props.count === 1 ? '' : 's'}</span>
        )}
        {props.semDataCount > 0 && (
          <span className="periodo-aviso" title="Não entram no período por falta da data-base">
            <Icon name="alert-circle" size={12} /> {props.semDataCount} sem data de {baseAtual.label.toLowerCase()}
          </span>
        )}
      </div>

      {/* Limpar */}
      {!isTudo && (
        <button className="periodo-limpar" aria-label="Limpar filtro de período" onClick={per.limpar}>
          Limpar <Icon name="x" size={12} />
        </button>
      )}
    </div>
  );
}

// ─── Exposição global ───────────────────────────────────────────
Object.assign(window, {
  resolvePeriodo, filtrarPorPeriodo, baseDataISO, intervaloAnterior,
  campoBase, baseOpt, FIN_BASES,
  useFinPeriodo, PeriodoFilter,
  rotuloPreset, rotuloCentro, rotuloFaixa, mesesRecentes,
});
