// Alertas de estoque com níveis de urgência e links rápidos
// initStockAlerts(state, { fmtBRL })

export function initStockAlerts(state, { fmtBRL }){
  const list = document.getElementById('stockList');
  const empty = document.getElementById('stockEmpty');
  if (!list) return;

  let abort = null;

  function urgency(item){
    const min = Number(item.min_stock ?? item.min ?? 0) || 0;
    const cur = Number(item.stock ?? item.qty ?? 0) || 0;
    if (min <= 0) return { level: 'ok', ratio: 1 };
    const ratio = cur / min;
    if (ratio <= 0.25) return { level: 'crítico', ratio };
    if (ratio <= 0.6) return { level: 'baixo', ratio };
    return { level: 'ok', ratio };
  }

  function badge(level){
    const color = level === 'crítico' ? '#ef4444' : (level === 'baixo' ? '#f59e0b' : '#16a34a');
    return `<span aria-label="${level}" title="${level}" style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${color};margin-right:6px;vertical-align:middle;"></span>`;
  }

  function render(items){
    if (!Array.isArray(items) || items.length === 0){
      list.innerHTML = '';
      if (empty) empty.style.display = 'block';
      return;
    }
    if (empty) empty.style.display = 'none';
    const fmt = (window && window.fmtQty) ? window.fmtQty : (n => String(Math.trunc(Number(n||0))));
    const html = items.map(it => {
      const u = urgency(it);
      const name = escapeHtml(it.product_name || it.name || `#${it.product_id||''}`);
      const curNum = Number(it.stock ?? it.qty ?? 0) || 0;
      const minNum = Number(it.min_stock ?? it.min ?? 0) || 0;
      const cur = fmt(curNum);
      const min = fmt(minNum);
      const toBuy = Math.max(0, (Math.trunc(minNum)*2) - Math.trunc(curNum));
      const replenishHref = `/compras`; // link genérico para reposição
      const productHref = `/produtos`;
      return `<li style="display:flex;justify-content:space-between;align-items:center;gap:0.5rem;padding:0.5rem;border:1px solid var(--border-muted);border-radius:8px;">
        <div>
          ${badge(u.level)} <strong>${name}</strong>
          <div class="muted" style="font-size:0.9em;">Estoque: ${cur} • Mín: ${min} • Urgência: ${u.level}</div>
        </div>
        <div style="display:flex;gap:0.5rem;">
          <a class="btn btn-secondary" href="${productHref}" aria-label="Abrir produto ${name}">Produto</a>
          <a class="btn" href="${replenishHref}" aria-label="Repor ${name}">Reposição (+${toBuy})</a>
        </div>
      </li>`;
    }).join('');
    list.innerHTML = html;
  }

  function escapeHtml(s){
    return (s||'').toString().replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[m]));
  }

  async function fetchJson(url, { signal }){
    try {
      const res = await fetch(url, { credentials:'include', signal });
      if (!res.ok) throw new Error(String(res.status));
      return await res.json();
    } catch(e){
      return { data: [] };
    }
  }

  async function load(){
    if (abort) abort.abort();
    abort = new AbortController();
    const json = await fetchJson('/api/stock/low?limit=50', { signal: abort.signal });
    const items = json.data || json.items || [];
    // sort by urgency
    items.sort((a,b)=>{
      const ra = (a.stock ?? 0) / Math.max(1, (a.min_stock ?? 1));
      const rb = (b.stock ?? 0) / Math.max(1, (b.min_stock ?? 1));
      return ra - rb;
    });
    render(items);
  }

  load();
}