<div class="card">
  <h1>Apuração de Impostos</h1>
  <p class="muted">Resumo e cálculo de tributos por período.</p>

  <!-- Filtros e ações -->
  <div style="display:flex;gap:1rem;flex-wrap:wrap;align-items:center;margin:0.5rem 0;">
    <div class="form-group">
      <label for="periodInput">Período</label>
      <input id="periodInput" class="input" type="month" />
    </div>
    <div class="form-group">
      <label for="regimeSelect">Regime</label>
      <select id="regimeSelect" class="input">
        <option value="simples">Simples Nacional</option>
        <option value="presumido">Lucro Presumido</option>
        <option value="real">Lucro Real</option>
      </select>
    </div>
    <button id="btnCalcular" class="btn">Calcular</button>
    <div class="form-inline" style="display:flex;gap:0.25rem;align-items:center;">
      <label for="sepSelect" style="font-size:0.9rem;color:#555;">CSV:</label>
      <select id="sepSelect" class="input" style="width:110px;">
        <option value=";">Ponto e vírgula</option>
        <option value=",">Vírgula</option>
        <option value="\t">Tabulação</option>
      </select>
      <button id="btnExportCsv" class="btn btn-secondary" disabled>Exportar</button>
    </div>
  </div>

  <div id="apuracaoStatus" class="muted" style="margin:0.5rem 0;"></div>

  <!-- Resultados -->
  <div id="apuracaoResultados" style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));margin-top:0.5rem;">
    <div class="card" id="cardIcms" style="border:1px solid #e5e7eb;">
      <h3>ICMS</h3>
      <div style="display:grid;grid-template-columns:1fr 1fr;column-gap:0.75rem;row-gap:0.25rem;">
        <div class="muted">Débitos</div><div id="icmsDebitos">–</div>
        <div class="muted">Créditos</div><div id="icmsCreditos">–</div>
        <div class="muted">Saldo apurado</div><div id="icmsSaldo">–</div>
        <div class="muted">Recolher</div><div id="icmsRecolher">–</div>
        <div class="muted">Credor a transportar</div><div id="icmsCredor">–</div>
        <div class="muted">Substituição Tributária (ST)</div><div id="icmsSt">–</div>
      </div>
      <hr />
      <div>
        <h4 style="margin:0.25rem 0;">Bases</h4>
        <div id="icmsBases" class="muted">–</div>
      </div>
    </div>
    <div class="card" id="cardPisCofinsIpi" style="border:1px solid #e5e7eb;">
      <h3>PIS / COFINS / IPI</h3>
      <div style="display:grid;grid-template-columns:1fr 1fr;column-gap:0.75rem;row-gap:0.25rem;">
        <div class="muted">PIS</div><div id="pisTotal">–</div>
        <div class="muted">COFINS</div><div id="cofinsTotal">–</div>
        <div class="muted">IPI</div><div id="ipiTotal">–</div>
      </div>
    </div>
  </div>

  <script>
    (function(){
      const periodInput = document.getElementById('periodInput');
      const regimeSelect = document.getElementById('regimeSelect');
      const btnCalcular = document.getElementById('btnCalcular');
      const btnExportCsv = document.getElementById('btnExportCsv');
      const sepSelect = document.getElementById('sepSelect');
      const statusEl = document.getElementById('apuracaoStatus');

      const icmsDebitos = document.getElementById('icmsDebitos');
      const icmsCreditos = document.getElementById('icmsCreditos');
      const icmsSaldo = document.getElementById('icmsSaldo');
      const icmsRecolher = document.getElementById('icmsRecolher');
      const icmsCredor = document.getElementById('icmsCredor');
      const icmsSt = document.getElementById('icmsSt');
      const icmsBases = document.getElementById('icmsBases');

      const pisTotal = document.getElementById('pisTotal');
      const cofinsTotal = document.getElementById('cofinsTotal');
      const ipiTotal = document.getElementById('ipiTotal');

      let lastResult = null;

      function formatNumber(n){
        try { return new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(Number(n)); }
        catch(e){ return (Number(n)||0).toFixed(2); }
      }

      function setLoading(loading){
        btnCalcular.disabled = loading;
        statusEl.textContent = loading ? 'Calculando apuração…' : '';
      }

      function ensurePeriodDefault(){
        if (!periodInput.value) {
          const d = new Date();
          const ym = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0');
          periodInput.value = ym;
        }
      }

      async function calcular(){
        ensurePeriodDefault();
        const period = periodInput.value; // YYYY-MM
        if (!period) {
          statusEl.textContent = 'Selecione o período antes de calcular.';
          return;
        }
        const [yearStr, monthStr] = period.split('-');
        const year = parseInt(yearStr, 10);
        const month = parseInt(monthStr, 10);
        const regime = regimeSelect.value || 'simples';

        setLoading(true);
        try {
          const resp = await fetch('/api/fiscal/apuracao', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ year, month, regime, perfil: 'A', ind_ativ: 1, cod_fin: 0 })
          });
          const data = await resp.json();
          if (!resp.ok || !data.ok) {
            throw new Error(data && data.message ? data.message : 'Falha na apuração');
          }

          lastResult = data;
          renderResultados(data);
          statusEl.textContent = `Apuração de ${String(data.period.month).padStart(2,'0')}/${data.period.year} (${data.regime}) concluída.`;
          btnExportCsv.disabled = false;
        } catch (err) {
          statusEl.textContent = 'Erro: ' + (err && err.message ? err.message : String(err));
        } finally {
          setLoading(false);
        }
      }

      function renderResultados(data){
        const t = data.totals || {};
        const icms = t.icms || {};
        icmsDebitos.textContent = formatNumber(icms.debitos || 0);
        icmsCreditos.textContent = formatNumber(icms.creditos || 0);
        icmsSaldo.textContent = formatNumber(icms.saldo_apurado || 0);
        icmsRecolher.textContent = formatNumber(icms.recolher || 0);
        icmsCredor.textContent = formatNumber(icms.credor_transportar || 0);
        icmsSt.textContent = formatNumber(icms.st || 0);

        const bases = icms.bases || {};
        const entries = Object.entries(bases);
        if (!entries.length) {
          icmsBases.textContent = '—';
        } else {
          const frag = document.createDocumentFragment();
          const table = document.createElement('table');
          table.className = 'table';
          const thead = document.createElement('thead');
          thead.innerHTML = '<tr><th>Base</th><th>Valor</th></tr>';
          const tbody = document.createElement('tbody');
          entries.forEach(([name, value]) => {
            const tr = document.createElement('tr');
            const td1 = document.createElement('td'); td1.textContent = name;
            const td2 = document.createElement('td'); td2.textContent = formatNumber(value);
            tr.appendChild(td1); tr.appendChild(td2);
            tbody.appendChild(tr);
          });
          table.appendChild(thead); table.appendChild(tbody);
          frag.appendChild(table);
          icmsBases.innerHTML = '';
          icmsBases.appendChild(frag);
        }

        pisTotal.textContent = formatNumber(t.pis || 0);
        cofinsTotal.textContent = formatNumber(t.cofins || 0);
        ipiTotal.textContent = formatNumber(t.ipi || 0);
      }

      function exportCsv(){
        if (!lastResult) return;
        const sep = sepSelect.value || ';';
        const period = lastResult.period || { year: '', month: '' };
        const mm = String(period.month || '').padStart(2,'0');
        const yyyy = String(period.year || '');

        const t = lastResult.totals || {};
        const icms = t.icms || {};
        const lines = [];
        lines.push(['Imposto','Campo','Valor'].join(sep));
        lines.push(['ICMS','Debitos', icms.debitos ?? 0].join(sep));
        lines.push(['ICMS','Creditos', icms.creditos ?? 0].join(sep));
        lines.push(['ICMS','Saldo Apurado', icms.saldo_apurado ?? 0].join(sep));
        lines.push(['ICMS','Recolher', icms.recolher ?? 0].join(sep));
        lines.push(['ICMS','Credor a Transportar', icms.credor_transportar ?? 0].join(sep));
        lines.push(['ICMS','ST', icms.st ?? 0].join(sep));

        const bases = icms.bases || {};
        Object.entries(bases).forEach(([name, value]) => {
          lines.push(['ICMS Base', name, value ?? 0].join(sep));
        });

        lines.push(['PIS','Total', t.pis ?? 0].join(sep));
        lines.push(['COFINS','Total', t.cofins ?? 0].join(sep));
        lines.push(['IPI','Total', t.ipi ?? 0].join(sep));

        const csv = lines.join('\n');
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `apuracao_${yyyy}-${mm}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }

      btnCalcular.addEventListener('click', calcular);
      btnExportCsv.addEventListener('click', exportCsv);
      ensurePeriodDefault();
    })();
  </script>
</div>