<div class="card">
  <h1>Produtos Críticos</h1>
  <p>Identifique itens com baixo estoque, alta demanda ou rupturas.</p>
  <div class="form-group">
    <label for="crit">Critério</label>
    <select id="crit" name="crit">
      <option value="ruptura">Ruptura</option>
      <option value="baixo_estoque" selected>Baixo estoque</option>
      <option value="alta_demanda">Alta demanda</option>
    </select>
  </div>
  <div class="form-group" style="position:relative;">
    <label for="q">Buscar</label>
    <input id="q" name="q" type="text" placeholder="Código ou descrição" autocomplete="off">
    <div id="qSuggestions" style="position:absolute; top:100%; left:0; right:0; background:#fff; border:1px solid #e5e7eb; border-radius:6px; box-shadow:0 8px 24px rgba(0,0,0,0.08); display:none; z-index:100; max-height:240px; overflow:auto;"></div>
  </div>
  <div class="form-group">
    <label for="days">Janela (dias)</label>
    <select id="days" name="days">
      <option value="7">7</option>
      <option value="14" selected>14</option>
      <option value="30">30</option>
    </select>
  </div>
  <div class="form-group">
    <label for="start">Período</label>
    <div style="display:flex; gap:6px;">
      <input id="start" name="start" type="date">
      <input id="end" name="end" type="date">
    </div>
    <div class="muted" style="font-size:0.85em;">Se preencher datas, usa o período customizado.</div>
  </div>
  <div class="form-group">
    <label for="filterSit">Situação</label>
    <select id="filterSit" name="filterSit">
      <option value="todos" selected>Todos</option>
      <option value="ruptura">Ruptura</option>
      <option value="abaixo_min">Abaixo do mínimo</option>
      <option value="alta_demanda">Alta demanda</option>
      <option value="ok">OK</option>
    </select>
  </div>
  <div class="form-group">
    <button id="applyCrit" class="btn">Aplicar</button>
    <button id="clearFilters" class="btn btn-secondary" title="Resetar critérios e filtros" style="margin-left:8px;">Limpar filtros</button>
    <button id="exportCsv" class="btn btn-secondary" title="Exportar CSV" style="margin-left:8px;">Exportar CSV</button>
    <button id="exportXls" class="btn btn-secondary" title="Exportar Excel" style="margin-left:8px;">Exportar Excel</button>
  </div>

  <div id="results" class="mt-2">
    <div id="winInfo" class="muted" style="margin:4px 0 8px 0;"></div>
    <div id="sitSummary" class="muted" style="margin:4px 0 8px 0;"></div>
    <table class="table" id="critTable" aria-label="Produtos críticos">
      <thead>
        <tr>
          <th data-sort="codigo" style="width: 12%; cursor:pointer">Código <span id="s_codigo"></span></th>
          <th data-sort="descricao" style="width: 38%; cursor:pointer">Descrição <span id="s_descricao"></span></th>
          <th data-sort="level" style="width: 14%; cursor:pointer">Estoque Atual <span id="s_level"></span></th>
          <th data-sort="min" style="width: 14%; cursor:pointer">Mínimo <span id="s_min"></span></th>
          <th data-sort="out_qty" style="width: 12%; cursor:pointer">Demanda <span id="s_out_qty"></span></th>
          <th style="width: 18%">Situação</th>
        </tr>
      </thead>
      <tbody id="critRows">
        <tr><td colspan="6" class="muted">Selecione um critério e aplique</td></tr>
      </tbody>
    </table>
    <div class="pagination" id="critPager" style="display:flex; gap:8px; align-items:center;">
      <button id="prevPage" class="btn" disabled>Anterior</button>
      <span id="pageInfo" class="muted"></span>
      <button id="nextPage" class="btn" disabled>Próxima</button>
      <label style="margin-left:auto">por página
        <select id="perPage">
          <option value="10">10</option>
          <option value="25" selected>25</option>
          <option value="50">50</option>
        </select>
      </label>
    </div>
  </div>
</div>

<script>
  (function(){
    const $ = (id) => document.getElementById(id);
    const fmtQty = (n) => {
      const v = Number(n||0);
      if (Number.isNaN(v)) return '-';
      return String(Math.trunc(v));
    };
    const LSKEY = 'prodCrit.config';
    const state = {
      crit: 'baixo_estoque',
      sort: 'level',
      dir: 'asc',
      page: 1,
      per_page: 25,
      q: '',
      days: 14,
      start: '',
      end: '',
      filter_sit: 'todos'
    };
    function loadState(){
      try{ const raw = localStorage.getItem(LSKEY); if(raw){ const s = JSON.parse(raw); Object.assign(state, s||{}); } }catch(_){}
      if ($('crit')) $('crit').value = state.crit || 'baixo_estoque';
      if ($('perPage')) $('perPage').value = String(state.per_page||25);
      if ($('q')) $('q').value = state.q||'';
      if ($('days')) $('days').value = String(state.days||14);
      if ($('start')) $('start').value = state.start||'';
      if ($('end')) $('end').value = state.end||'';
      if ($('filterSit')) $('filterSit').value = state.filter_sit||'todos';
      updateSortIndicators();
    }
    function saveState(){ try{ localStorage.setItem(LSKEY, JSON.stringify(state)); }catch(_){} }
    function updateSortIndicators(){
      ['codigo','descricao','level','min','out_qty'].forEach(k=>{ const el = $('s_'+k); if(!el) return; el.textContent = (state.sort===k) ? (state.dir==='asc'?'▲':'▼') : ''; });
    }
    function attachHeaderSort(){
      const ths = document.querySelectorAll('#critTable thead th[data-sort]');
      ths.forEach(th => {
        th.addEventListener('click', ()=>{
          const k = th.getAttribute('data-sort');
          if (state.sort === k) { state.dir = (state.dir==='asc'?'desc':'asc'); } else { state.sort = k; state.dir = 'asc'; }
          state.page = 1; updateSortIndicators(); saveState(); carregar();
        });
      });
    }
    // Autocomplete (>=3 caracteres) para campo de busca
    let qDebounce;
    $('q').addEventListener('input', () => {
      const inp = $('q'); const sug = $('qSuggestions'); const term = inp.value.trim();
      clearTimeout(qDebounce);
      if (term.length < 3) { sug.style.display='none'; sug.innerHTML=''; return; }
      qDebounce = setTimeout(async () => {
        try {
          const res = await apiRequest(`/api/produtos?q=${encodeURIComponent(term)}&per_page=10`);
          if (!res.ok) { sug.style.display='none'; sug.innerHTML=''; return; }
          const js = await res.json(); const list = js.data || [];
          if (!list.length) { sug.style.display='none'; sug.innerHTML=''; return; }
          sug.innerHTML = list.map(p => {
            const code = (p.codigo || '').toString();
            const name = (p.nome || p.descricao || '').toString();
            const stk = (p.estoque != null) ? Number(p.estoque) : '';
            return `<div class="list-item" data-code="${code}" style="padding:0.5rem; cursor:pointer; display:flex; justify-content:space-between; gap:0.5rem;">
              <div><strong>${code}</strong> — ${name}</div>
              <div class="muted">${stk!==''?('Estoque: '+stk):''}</div>
            </div>`;
          }).join('');
          sug.style.display='block';
          Array.from(sug.querySelectorAll('.list-item')).forEach(el => {
            el.addEventListener('click', () => {
              const code = el.getAttribute('data-code') || '';
              $('q').value = code;
              state.q = code; state.page = 1; saveState(); sug.style.display='none'; sug.innerHTML=''; carregar();
            });
          });
        } catch (_) { sug.style.display='none'; sug.innerHTML=''; }
      }, 220);
    });
    document.addEventListener('click', (ev) => {
      const sug = $('qSuggestions');
      if (!sug) return;
      const within = sug.contains(ev.target) || $('q').contains(ev.target);
      if (!within) { sug.style.display='none'; }
    });

    async function carregar(){
      const criterio = $('crit').value;
      const tbody = $('critRows');
      tbody.innerHTML = '<tr><td colspan="6">Carregando...</td></tr>';
      try {
        state.crit = criterio; state.q = $('q').value.trim(); state.per_page = parseInt($('perPage').value||'25'); saveState();
        const qs = new URLSearchParams({ crit: state.crit, sort: state.sort, dir: state.dir, page: String(state.page), per_page: String(state.per_page) });
        if (state.q) qs.set('q', state.q);
        // Janela de alta demanda: se datas estiverem preenchidas, usar; senão usar days
        const startVal = $('start').value || ''; const endVal = $('end').value || '';
        state.start = startVal; state.end = endVal; state.days = parseInt($('days').value||'14'); saveState();
        if (state.crit === 'alta_demanda') {
          if (startVal !== '' && endVal !== '') { qs.set('start', startVal); qs.set('end', endVal); }
          else { qs.set('days', String(state.days)); }
        }
        const resp = await apiRequest('/estoque/thresholds/report?'+qs.toString());
        // 501 não deve ocorrer mais; manter fallback silencioso
        const js = await resp.json();
        const rows = Array.isArray(js.data) ? js.data : [];
        const total = parseInt(js.total||0); const totalPages = parseInt(js.total_pages||1);
        $('pageInfo').textContent = `Página ${js.page||1} de ${totalPages||1} (${total||0} itens)`;
        // Info da janela ativa para alta demanda
        const winInfoEl = document.getElementById('winInfo');
        if (state.crit === 'alta_demanda') {
          if (state.start && state.end) {
            winInfoEl.textContent = `Janela: Período ${state.start} a ${state.end}`;
          } else {
            winInfoEl.textContent = `Janela: Últimos ${state.days} dias`;
          }
        } else {
          winInfoEl.textContent = '';
        }
        $('prevPage').disabled = (state.page<=1);
        $('nextPage').disabled = (state.page>=totalPages);
        if (!rows.length) { tbody.innerHTML = '<tr><td colspan="6" class="muted">Sem itens para o critério selecionado</td></tr>'; return; }
        let count = { ruptura:0, abaixo_min:0, alta_demanda:0, ok:0 };
        const html = rows.map(r => {
          const cod = r.codigo || '-';
          const desc = r.descricao || '-';
          const lvl = fmtQty(r.level);
          const min = fmtQty(r.min);
          const dem = (r.out_qty != null) ? fmtQty(r.out_qty) : '-';
          let sit = (Number(r.level||0) <= 0) ? 'Ruptura'
            : (Number(r.level||0) < Number(r.min||0) ? 'Abaixo do mínimo' : 'OK');
          if (sit === 'OK' && state.crit === 'alta_demanda') {
            const outq = Number(r.out_qty||0), lvlN = Number(r.level||0), minN = Number(r.min||0);
            if ((outq >= minN) || ((lvlN - outq) < minN)) { sit = 'Alta demanda'; }
          }
          const sitKey = (sit==='Ruptura')?'ruptura':(sit==='Abaixo do mínimo')?'abaixo_min':(sit==='Alta demanda')?'alta_demanda':'ok';
          if (state.filter_sit && state.filter_sit !== 'todos' && state.filter_sit !== sitKey) { return ''; }
          let bg = '#dcfce7', fg = '#166534'; // OK
          if (sit === 'Ruptura') { bg = '#fee2e2'; fg = '#b91c1c'; }
          else if (sit === 'Abaixo do mínimo') { bg = '#ffedd5'; fg = '#c2410c'; }
          else if (sit === 'Alta demanda') { bg = '#fef3c7'; fg = '#b45309'; }
          count[sitKey]++;
          return `<tr style="background:${bg}; color:${fg};">
            <td>${cod}</td>
            <td>${desc}</td>
            <td>${lvl}</td>
            <td>${min}</td>
            <td>${dem}</td>
            <td><span style="display:inline-block;padding:2px 6px;border-radius:10px;background:${bg};color:${fg};font-size:12px;">${sit}</span></td>
          </tr>`;
        }).join('');
        tbody.innerHTML = html;
        const sumEl = document.getElementById('sitSummary');
        sumEl.textContent = `Resumo: Ruptura ${count.ruptura} | Abaixo do mínimo ${count.abaixo_min} | Alta demanda ${count.alta_demanda} | OK ${count.ok}`;
      } catch (e) {
        console.error('Falha ao carregar produtos críticos', e);
        $('critRows').innerHTML = '<tr><td colspan="6" class="muted">Erro ao carregar</td></tr>';
      }
    }

    $('applyCrit').addEventListener('click', ()=>{ state.page=1; carregar(); });
    $('prevPage').addEventListener('click', ()=>{ if(state.page>1){ state.page--; saveState(); carregar(); } });
    $('nextPage').addEventListener('click', ()=>{ state.page++; saveState(); carregar(); });
    $('perPage').addEventListener('change', ()=>{ state.page=1; saveState(); carregar(); });
    $('filterSit').addEventListener('change', ()=>{ state.filter_sit = $('filterSit').value || 'todos'; state.page=1; saveState(); carregar(); });
    // Limpar filtros
    $('clearFilters').addEventListener('click', ()=>{
      try{ localStorage.removeItem(LSKEY); }catch(_){}
      state.crit = 'baixo_estoque';
      state.q = '';
      state.sort = 'level';
      state.dir = 'asc';
      state.page = 1;
      state.per_page = 25;
      state.days = 14;
      state.start = '';
      state.end = '';
      // Atualizar UI
      if ($('crit')) $('crit').value = state.crit;
      if ($('q')) $('q').value = '';
      if ($('days')) $('days').value = String(state.days);
      if ($('start')) $('start').value = '';
      if ($('end')) $('end').value = '';
      if ($('perPage')) $('perPage').value = String(state.per_page);
      if ($('filterSit')) $('filterSit').value = 'todos'; state.filter_sit = 'todos';
      updateSortIndicators(); saveState(); carregar();
    });
    async function exportCSV(){
      try {
        const qsBase = new URLSearchParams({ crit: state.crit, sort: state.sort, dir: state.dir, per_page: '500' });
        if (state.q) qsBase.set('q', state.q);
        if (state.crit === 'alta_demanda') {
          if (state.start && state.end) { qsBase.set('start', state.start); qsBase.set('end', state.end); }
          else { qsBase.set('days', String(state.days)); }
        }
        qsBase.set('page','1');
        const resp1 = await apiRequest('/estoque/thresholds/report?'+qsBase.toString());
        const js1 = await resp1.json();
        const totalPages = parseInt(js1.total_pages||1);
        const all = Array.isArray(js1.data) ? js1.data.slice() : [];
        for (let p=2; p<=totalPages; p++) {
          qsBase.set('page', String(p));
          const rp = await apiRequest('/estoque/thresholds/report?'+qsBase.toString());
          const jsp = await rp.json();
          if (Array.isArray(jsp.data)) all.push(...jsp.data);
        }
        const rows = all.map(r => {
          let sit = (Number(r.level||0) <= 0) ? 'Ruptura'
            : (Number(r.level||0) < Number(r.min||0) ? 'Abaixo do mínimo' : 'OK');
          if (sit === 'OK' && state.crit === 'alta_demanda') {
            const outq = Number(r.out_qty||0), lvlN = Number(r.level||0), minN = Number(r.min||0);
            if ((outq >= minN) || ((lvlN - outq) < minN)) { sit = 'Alta demanda'; }
          }
          return {
            codigo: r.codigo||'',
            descricao: r.descricao||'',
            level: String(r.level||''),
            min: String(r.min||''),
            demanda: (r.out_qty!=null)?String(r.out_qty):'',
            situacao: sit
          };
        });
        const header = ['codigo','descricao','level','min','demanda','situacao'];
        const csv = [header.join(',')].concat(rows.map(o => header.map(h => {
          const v = (o[h]||'').toString().replace(/"/g,'""');
          return /[",\n]/.test(v) ? '"'+v+'"' : v;
        }).join(','))).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 = 'produtos_criticos.csv'; a.id = 'csvDl';
        document.body.appendChild(a);
        a.click();
        setTimeout(()=>{ URL.revokeObjectURL(url); a.remove(); }, 500);
      } catch(e) {
        console.error('Falha exportando CSV', e);
      }
    }
    $('exportCsv').addEventListener('click', exportCSV);
    async function exportXLS(){
      try {
        const qsBase = new URLSearchParams({ crit: state.crit, sort: state.sort, dir: state.dir, per_page: '500' });
        if (state.q) qsBase.set('q', state.q);
        if (state.crit === 'alta_demanda') {
          if (state.start && state.end) { qsBase.set('start', state.start); qsBase.set('end', state.end); }
          else { qsBase.set('days', String(state.days)); }
        }
        qsBase.set('page','1');
        const resp1 = await apiRequest('/estoque/thresholds/report?'+qsBase.toString());
        const js1 = await resp1.json();
        const totalPages = parseInt(js1.total_pages||1);
        const all = Array.isArray(js1.data) ? js1.data.slice() : [];
        for (let p=2; p<=totalPages; p++) {
          qsBase.set('page', String(p));
          const rp = await apiRequest('/estoque/thresholds/report?'+qsBase.toString());
          const jsp = await rp.json();
          if (Array.isArray(jsp.data)) all.push(...jsp.data);
        }
        const rows = all.map(r => {
          let sit = (Number(r.level||0) <= 0) ? 'Ruptura'
            : (Number(r.level||0) < Number(r.min||0) ? 'Abaixo do mínimo' : 'OK');
          if (sit === 'OK' && state.crit === 'alta_demanda') {
            const outq = Number(r.out_qty||0), lvlN = Number(r.level||0), minN = Number(r.min||0);
            if ((outq >= minN) || ((lvlN - outq) < minN)) { sit = 'Alta demanda'; }
          }
          return {
            codigo: r.codigo||'',
            descricao: r.descricao||'',
            level: String(r.level||''),
            min: String(r.min||''),
            demanda: (r.out_qty!=null)?String(r.out_qty):'',
            situacao: sit
          };
        });
        const header = ['Código','Descrição','Estoque Atual','Mínimo','Demanda','Situação'];
        const bodyRows = rows.map(o => `<tr>
          <td>${o.codigo}</td>
          <td>${o.descricao}</td>
          <td>${o.level}</td>
          <td>${o.min}</td>
          <td>${o.demanda}</td>
          <td>${o.situacao}</td>
        </tr>`).join('');
        const html = `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
          <table border="1">
            <thead><tr>${header.map(h=>`<th>${h}</th>`).join('')}</tr></thead>
            <tbody>${bodyRows}</tbody>
          </table>
        </body></html>`;
        const blob = new Blob([html], { type: 'application/vnd.ms-excel;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url; a.download = 'produtos_criticos.xls'; a.id = 'xlsDl';
        document.body.appendChild(a);
        a.click();
        setTimeout(()=>{ URL.revokeObjectURL(url); a.remove(); }, 500);
      } catch(e) {
        console.error('Falha exportando Excel', e);
      }
    }
    $('exportXls').addEventListener('click', exportXLS);
    document.addEventListener('DOMContentLoaded', ()=>{ loadState(); attachHeaderSort(); carregar(); });
  })();
</script>