<div class="card">
  <h1>Configurações Fiscais</h1>
  <p class="muted">Defina modelo, ambiente e opções para NF-e / NFC-e / NFS-e.</p>

  <div class="grid" style="gap:0.75rem;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));">
    <div class="form-group">
      <label for="modelVersion">Versão do modelo</label>
      <select id="modelVersion" class="input">
        <option value="2024">2024</option>
        <option value="2026">2026</option>
      </select>
      <small class="muted">Afeta cálculos e leiautes em módulos fiscais.</small>
    </div>
    <div class="form-group">
      <label for="environment">Ambiente</label>
      <select id="environment" class="input">
        <option value="homologation">Homologação</option>
        <option value="production">Produção</option>
      </select>
      <small class="muted">Usado por emissões e certificados (A1/A3).</small>
    </div>
    <div class="form-group">
      <label for="effectiveFrom">Vigência (AAAA-MM-DD)</label>
      <input id="effectiveFrom" class="input" type="date" />
      <small class="muted">Opcional. Define a data de entrada em vigor.</small>
    </div>
  </div>

  <h3 style="margin-top:0.75rem;">Documentos ativos</h3>
  <div class="grid" style="gap:0.75rem;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));">
    <label class="checkbox"><input type="checkbox" id="nfeEnabled" /> <span>Ativar NF-e</span></label>
    <label class="checkbox"><input type="checkbox" id="nfceEnabled" /> <span>Ativar NFC-e</span></label>
    <label class="checkbox"><input type="checkbox" id="nfseEnabled" /> <span>Ativar NFS-e</span></label>
  </div>

  <h3 style="margin-top:0.75rem;">Políticas de cancelamento</h3>
  <p class="muted" style="margin-top:-0.5rem;">Defina regras mínimas de justificativa, janela temporal e exigência de certificado.</p>
  <div class="grid" style="gap:0.75rem;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));">
    <div class="form-group">
      <label>NF-e: Justificativa mínima</label>
      <input id="nfceMinReason" type="number" class="input" min="0" step="1" placeholder="Ex.: 15" />
      <small class="muted">Caracteres mínimos da justificativa.</small>
    </div>
    <div class="form-group">
      <label>NF-e: Janela (minutos)</label>
      <input id="nfceWindowMin" type="number" class="input" min="0" step="1" placeholder="Ex.: 30" />
      <small class="muted">Tempo limite para cancelar após autorização.</small>
    </div>
    <div class="form-group">
      <label class="checkbox"><input type="checkbox" id="nfceRequireCert" /> <span>NF-e: Exigir certificado</span></label>
      <small class="muted">Valida presença de A1/A3 conforme ambiente.</small>
    </div>

    <div class="form-group">
      <label>CT-e: Justificativa mínima</label>
      <input id="cteMinReason" type="number" class="input" min="0" step="1" placeholder="Ex.: 15" />
      <small class="muted">Caracteres mínimos da justificativa.</small>
    </div>
    <div class="form-group">
      <label>CT-e: Janela (minutos)</label>
      <input id="cteWindowMin" type="number" class="input" min="0" step="1" placeholder="Ex.: 60" />
      <small class="muted">Tempo limite para cancelar após autorização.</small>
    </div>
    <div class="form-group">
      <label class="checkbox"><input type="checkbox" id="cteRequireCert" /> <span>CT-e: Exigir certificado</span></label>
      <small class="muted">Valida presença de A1/A3 conforme ambiente.</small>
    </div>

    <div class="form-group">
      <label>NFS-e: Justificativa mínima</label>
      <input id="nfseMinReason" type="number" class="input" min="0" step="1" placeholder="Ex.: 10" />
      <small class="muted">Caracteres mínimos da justificativa.</small>
    </div>
  </div>

  <div class="card">
    <h3 style="margin-top:0.75rem;">Glossário da Reforma Tributária</h3>
    <p class="muted" style="margin-top:-0.5rem;">Ative a compatibilidade com o glossário oficial para padronizar termos e preparar futuras parametrizações (CBS/IBS, CST, apuração assistida).</p>
    <div class="grid" style="gap:0.75rem;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));">
      <div class="form-group">
        <label class="checkbox"><input type="checkbox" id="rtGlossaryEnable" /> <span>Ativar compatibilidade com Glossário RT</span></label>
        <small class="muted">Quando ativo, telas e provedores podem exibir termos padronizados.</small>
      </div>
      <div class="form-group">
        <label for="rtGlossaryVersion">Versão do glossário</label>
        <select id="rtGlossaryVersion" class="input">
          <option value="I-2025-08">Versão I – agosto/2025</option>
          <option value="custom">Personalizada</option>
        </select>
        <small class="muted">Selecione a oficial ou use uma etiqueta personalizada.</small>
      </div>
      <div class="form-group">
        <label for="rtGlossaryCustom">Etiqueta personalizada</label>
        <input type="text" id="rtGlossaryCustom" class="input" placeholder="Ex.: II-2026-03" />
        <small class="muted">Preencha apenas quando "Personalizada" estiver selecionado.</small>
      </div>
      <div class="form-group">
        <label for="rtGlossaryUrl">Documento oficial (URL)</label>
        <input type="url" id="rtGlossaryUrl" class="input" placeholder="https://..." />
        <small class="muted">Link para o documento oficial no gov.br (referência interna).</small>
      </div>
    </div>
  </div>

  <h3 style="margin-top:0.75rem;">NFS-e por UF</h3>
  <p class="muted" style="margin-top:-0.5rem;">Configure alíquota de ISS por UF. Para RJ, o padrão é 5%.</p>
  <div style="overflow:auto;">
    <table class="table">
      <thead>
        <tr>
          <th style="width:100px;">UF</th>
          <th style="width:160px;">ISS (%)</th>
          <th>Ações</th>
        </tr>
      </thead>
      <tbody id="ufRatesRows"><tr><td colspan="3" class="muted">Carregando…</td></tr></tbody>
    </table>
  </div>
  <div style="display:flex;gap:0.5rem;margin-top:0.25rem;align-items:center;">
    <select id="newUf" class="input" style="width:120px;">
      <option value="AC">AC</option>
      <option value="AL">AL</option>
      <option value="AP">AP</option>
      <option value="AM">AM</option>
      <option value="BA">BA</option>
      <option value="CE">CE</option>
      <option value="DF">DF</option>
      <option value="ES">ES</option>
      <option value="GO">GO</option>
      <option value="MA">MA</option>
      <option value="MT">MT</option>
      <option value="MS">MS</option>
      <option value="MG">MG</option>
      <option value="PA">PA</option>
      <option value="PB">PB</option>
      <option value="PR">PR</option>
      <option value="PE">PE</option>
      <option value="PI">PI</option>
      <option value="RJ">RJ</option>
      <option value="RN">RN</option>
      <option value="RS">RS</option>
      <option value="RO">RO</option>
      <option value="RR">RR</option>
      <option value="SC">SC</option>
      <option value="SP">SP</option>
      <option value="SE">SE</option>
      <option value="TO">TO</option>
    </select>
    <input id="newIss" class="input" type="number" step="0.01" placeholder="ISS (%)" style="width:140px;" />
    <button id="btnAddUf" class="btn btn-secondary" type="button">Adicionar UF</button>
  </div>

  <div style="display:flex;gap:0.5rem;margin-top:0.75rem;">
    <button id="btnSave" class="btn">Salvar configurações</button>
    <div id="saveStatus" class="muted" style="align-self:center;"></div>
  </div>
</div>

<script>
(function(){
  const modelVersionEl = document.getElementById('modelVersion');
  const environmentEl = document.getElementById('environment');
  const effectiveFromEl = document.getElementById('effectiveFrom');
  const nfeEnabledEl = document.getElementById('nfeEnabled');
  const nfceEnabledEl = document.getElementById('nfceEnabled');
  const nfseEnabledEl = document.getElementById('nfseEnabled');
  const ufRatesRowsEl = document.getElementById('ufRatesRows');
  const newUfEl = document.getElementById('newUf');
  const newIssEl = document.getElementById('newIss');
  const btnAddUfEl = document.getElementById('btnAddUf');
  const btnSaveEl = document.getElementById('btnSave');
  const saveStatusEl = document.getElementById('saveStatus');
  // Cancel policies elements
  const nfceMinReasonEl = document.getElementById('nfceMinReason');
  const nfceWindowMinEl = document.getElementById('nfceWindowMin');
  const nfceRequireCertEl = document.getElementById('nfceRequireCert');
  const cteMinReasonEl = document.getElementById('cteMinReason');
  const cteWindowMinEl = document.getElementById('cteWindowMin');
  const cteRequireCertEl = document.getElementById('cteRequireCert');
  const nfseMinReasonEl = document.getElementById('nfseMinReason');

  // Glossário RT elements
  const rtGlossaryEnableEl = document.getElementById('rtGlossaryEnable');
  const rtGlossaryVersionEl = document.getElementById('rtGlossaryVersion');
  const rtGlossaryCustomEl = document.getElementById('rtGlossaryCustom');
  const rtGlossaryUrlEl = document.getElementById('rtGlossaryUrl');

  let currentCfg = { model_version: '2024', environment: 'production', effective_from: null, options: {} };
  let ufRates = {}; // { UF: { iss: number } }

  function renderUfRates(){
    const keys = Object.keys(ufRates);
    if (keys.length === 0){ ufRatesRowsEl.innerHTML = '<tr><td colspan="3" class="muted">Nenhuma UF configurada</td></tr>'; return; }
    const rows = keys.sort().map((uf, idx)=>{
      const iss = typeof ufRates[uf]?.iss === 'number' ? ufRates[uf].iss : parseFloat(ufRates[uf]?.iss||'0')||0;
      const rid = 'row_' + uf;
      return `<tr id="${rid}">
        <td>${uf}</td>
        <td><input type="number" step="0.01" class="input" style="width:120px;" value="${iss}" data-uf="${uf}" /></td>
        <td><button class="btn btn-warning" data-remove="${uf}">Remover</button></td>
      </tr>`;
    }).join('');
    ufRatesRowsEl.innerHTML = rows;
    // Bind inputs
    ufRatesRowsEl.querySelectorAll('input[data-uf]').forEach(inp=>{
      inp.addEventListener('input', ()=>{
        const uf = inp.getAttribute('data-uf');
        const v = parseFloat(inp.value||'0');
        if (!isFinite(v)) return; ufRates[uf] = { iss: v };
      });
    });
    ufRatesRowsEl.querySelectorAll('button[data-remove]').forEach(btn=>{
      btn.addEventListener('click', ()=>{
        const uf = btn.getAttribute('data-remove');
        delete ufRates[uf];
        renderUfRates();
      });
    });
  }

  async function loadConfig(){
    try {
      const resp = await apiRequest('/api/fiscal/config');
      const js = await resp.json().catch(()=>({}));
      const cfg = js.data || js || {};
      currentCfg = {
        model_version: String(cfg.model_version||'2024'),
        environment: String(cfg.environment||'production'),
        effective_from: cfg.effective_from || null,
        options: (cfg.options && typeof cfg.options === 'object') ? cfg.options : {}
      };
      modelVersionEl.value = currentCfg.model_version;
      environmentEl.value = currentCfg.environment === 'homologation' ? 'homologation' : 'production';
      effectiveFromEl.value = currentCfg.effective_from ? String(currentCfg.effective_from).slice(0, 10) : '';
      // Document toggles
      const opt = currentCfg.options || {};
      nfeEnabledEl.checked = !!(opt.nfe && opt.nfe.enabled);
      nfceEnabledEl.checked = !!(opt.nfce && opt.nfce.enabled);
      nfseEnabledEl.checked = !!(opt.nfse && opt.nfse.enabled);
      // Cancel policies
      const pol = (opt.cancellation && typeof opt.cancellation === 'object') ? opt.cancellation : {};
      const nfcePol = (pol.nfce && typeof pol.nfce === 'object') ? pol.nfce : {};
      const ctePol = (pol.cte && typeof pol.cte === 'object') ? pol.cte : {};
      const nfsePol = (pol.nfse && typeof pol.nfse === 'object') ? pol.nfse : {};
      nfceMinReasonEl.value = String(nfcePol.min_reason_length ?? 15);
      nfceWindowMinEl.value = String(nfcePol.window_minutes ?? 0);
      nfceRequireCertEl.checked = !!(nfcePol.require_certificate ?? false);
      cteMinReasonEl.value = String(ctePol.min_reason_length ?? 15);
      cteWindowMinEl.value = String(ctePol.window_minutes ?? 0);
      cteRequireCertEl.checked = !!(ctePol.require_certificate ?? true);
      nfseMinReasonEl.value = String(nfsePol.min_reason_length ?? 10);
      // Glossário RT
      const rt = (opt.rt_glossary && typeof opt.rt_glossary === 'object') ? opt.rt_glossary : {};
      rtGlossaryEnableEl.checked = !!rt.enable;
      const ver = String(rt.version || 'I-2025-08');
      rtGlossaryVersionEl.value = ver === 'custom' ? 'custom' : ver;
      rtGlossaryCustomEl.value = String(rt.custom_label || '');
      rtGlossaryUrlEl.value = String(rt.url || '');
      // UF rates
      const rates = (opt.nfse && opt.nfse.uf_rates) ? opt.nfse.uf_rates : {};
      ufRates = Object.assign({}, rates);
      // Se não houver RJ e tenant for RJ, sugerir 5%
      try {
        const er = await apiRequest('/api/cadastros/empresas?limit=1');
        const ej = await er.json().catch(()=>({}));
        const row = Array.isArray(ej.data) && ej.data.length ? ej.data[0] : null;
        const uf = row && row.estado ? String(row.estado).toUpperCase() : '';
        if (uf === 'RJ' && !ufRates['RJ']) { ufRates['RJ'] = { iss: 5.0 }; }
      } catch(_e){ /* ignore */ }
      renderUfRates();
    } catch(e){
      ufRatesRowsEl.innerHTML = '<tr><td colspan="3" class="text-error">Falha ao carregar configurações</td></tr>';
    }
  }

  btnAddUfEl.addEventListener('click', ()=>{
    const uf = (newUfEl.value||'').toUpperCase();
    const iss = parseFloat(newIssEl.value||'');
    if (!uf || !isFinite(iss)) { alert('Informe UF e alíquota ISS válida.'); return; }
    ufRates[uf] = { iss: iss };
    newIssEl.value = '';
    renderUfRates();
  });

  async function save(){
    try {
      showLoading(); saveStatusEl.textContent = '';
      // Mesclar opções existentes
      const opt = Object.assign({}, currentCfg.options || {});
      opt.nfe = Object.assign({}, opt.nfe || {}, { enabled: !!nfeEnabledEl.checked });
      opt.nfce = Object.assign({}, opt.nfce || {}, { enabled: !!nfceEnabledEl.checked });
      opt.nfse = Object.assign({}, opt.nfse || {}, { enabled: !!nfseEnabledEl.checked, uf_rates: ufRates });
      opt.cancellation = Object.assign({}, opt.cancellation || {}, {
        nfce: {
          min_reason_length: parseInt(nfceMinReasonEl.value || '15', 10),
          window_minutes: parseInt(nfceWindowMinEl.value || '0', 10),
          require_certificate: !!nfceRequireCertEl.checked
        },
        cte: {
          min_reason_length: parseInt(cteMinReasonEl.value || '15', 10),
          window_minutes: parseInt(cteWindowMinEl.value || '0', 10),
          require_certificate: !!cteRequireCertEl.checked
        },
        nfse: {
          min_reason_length: parseInt(nfseMinReasonEl.value || '10', 10)
        }
      });
      // Glossário RT save
      const selectedVersion = rtGlossaryVersionEl.value || 'I-2025-08';
      const customLabel = (rtGlossaryCustomEl.value||'').trim();
      const url = (rtGlossaryUrlEl.value||'').trim();
      opt.rt_glossary = {
        enable: !!rtGlossaryEnableEl.checked,
        version: selectedVersion,
        custom_label: selectedVersion === 'custom' ? (customLabel || undefined) : undefined,
        url: url || undefined
      };
      const body = {
        model_version: modelVersionEl.value || '2024',
        effective_from: (effectiveFromEl.value||'').trim() || null,
        environment: environmentEl.value || 'production',
        options: opt,
      };
      const resp = await apiRequest('/api/fiscal/config', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
      hideLoading();
      if (resp && resp.ok){ saveStatusEl.textContent = 'Configurações salvas com sucesso'; saveStatusEl.className = 'text-success'; }
      else { saveStatusEl.textContent = 'Falha ao salvar'; saveStatusEl.className = 'text-error'; }
    } catch(e){ hideLoading(); saveStatusEl.textContent = 'Erro ao salvar'; saveStatusEl.className = 'text-error'; }
  }

  btnSaveEl.addEventListener('click', save);
  setTimeout(loadConfig, 50);
})();
</script>