// js/components/widgets/depositos/DepositoInventarioPage.jsx
// [Wave 3 KIMI 2026-05-15] Extraído de Depositos.jsx — refactor mecânico zero-lógica.
// Self-contained: zero closures escopo pai. Não chama RPC — só UI/filtros/CSV export.
// Globals runtime: toast (em exportCSV).
//
// Props (preservadas byte-by-byte):
//   warehouse (alias w), warehouses, products, isAdmin, onClose, onAjustar, onMovimentacoes
(function() {
  'use strict';
  const {useState, useMemo} = React;

  function DepositoInventarioPage({warehouse: w, warehouses, products, isAdmin, onClose, onAjustar, onMovimentacoes}){
    const [search, setSearch] = useState('');
    const [filterMarca, setFilterMarca] = useState('');
    const [filterCategoria, setFilterCategoria] = useState('');
    const [showOnlyStock, setShowOnlyStock] = useState(true);  // padrão: só com estoque
    const [showOnlyAbaixoMin, setShowOnlyAbaixoMin] = useState(false);
    const [sortBy, setSortBy] = useState('name');  // name | qty | valor | brand
    const [sortDir, setSortDir] = useState('asc');

    // Lista produtos com qty no warehouse (todos)
    const allRows = useMemo(()=>{
      return (products||[]).map(p=>{
        const bd = p.stock_breakdown || p.stockBreakdown || {};
        const qty = Number(bd[w.id] || 0);
        const price = Number(p.sale_price || p.salePrice || 0);
        const min = Number(p.estoque_min || p.estoqueMin || 0);
        return {
          id: p.id,
          name: p.name || '(sem nome)',
          brand: p.brand || '',
          code: p.code || '',
          volume: p.volume || '',
          categoria: p.categoria || p.category || '',
          qty, price, min,
          valor: qty * price,
          status: qty === 0 ? 'ZERO' : (min > 0 && qty < min ? 'BAIXO' : 'OK')
        };
      });
    },[products, w.id]);

    // Listas para os selects de filtro (marcas/categorias únicos)
    const marcas = useMemo(
      ()=>[...new Set(allRows.map(r=>r.brand).filter(Boolean))].sort(),
      [allRows]
    );
    const categorias = useMemo(
      ()=>[...new Set(allRows.map(r=>r.categoria).filter(Boolean))].sort(),
      [allRows]
    );

    // Aplica filtros + busca + ordenação
    const rows = useMemo(()=>{
      const q = search.trim().toLowerCase();
      let out = allRows.filter(r=>{
        if(showOnlyStock && r.qty <= 0) return false;
        if(showOnlyAbaixoMin && !(r.min > 0 && r.qty < r.min)) return false;
        if(filterMarca && r.brand !== filterMarca) return false;
        if(filterCategoria && r.categoria !== filterCategoria) return false;
        if(q){
          const blob = (r.name+' '+r.brand+' '+r.code+' '+r.volume).toLowerCase();
          if(!blob.includes(q)) return false;
        }
        return true;
      });
      out.sort((a,b)=>{
        let av = a[sortBy], bv = b[sortBy];
        if(typeof av === 'string'){ av = av.toLowerCase(); bv = (bv||'').toLowerCase(); }
        if(av < bv) return sortDir==='asc' ? -1 : 1;
        if(av > bv) return sortDir==='asc' ? 1 : -1;
        return 0;
      });
      return out;
    },[allRows, search, filterMarca, filterCategoria, showOnlyStock, showOnlyAbaixoMin, sortBy, sortDir]);

    const totals = useMemo(()=>({
      skus: rows.length,
      un: rows.reduce((s,r)=>s+r.qty, 0),
      valor: rows.reduce((s,r)=>s+r.valor, 0),
      abaixoMin: rows.filter(r=>r.status==='BAIXO').length,
      zero: rows.filter(r=>r.status==='ZERO').length
    }),[rows]);

    const toggleSort = (col)=>{
      if(sortBy === col) setSortDir(d=>d==='asc'?'desc':'asc');
      else { setSortBy(col); setSortDir('asc'); }
    };

    // [DEP100-O1-C] Export CSV (abre direto no Excel)
    const exportCSV = ()=>{
      const headers = ['Marca','Nome','Volume','Código','Categoria','Quantidade','Mínimo','Preço unit.','Valor total','Status'];
      const csvRows = [headers.join(';')];
      rows.forEach(r=>{
        const cells = [
          r.brand, r.name, r.volume, r.code, r.categoria,
          r.qty,
          r.min,
          r.price.toFixed(2).replace('.', ','),
          r.valor.toFixed(2).replace('.', ','),
          r.status
        ].map(v=>{
          const s = String(v ?? '');
          // Escape aspas + delimitar com aspas se contém ; , " ou \n
          return /[;,"\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
        });
        csvRows.push(cells.join(';'));
      });
      // Footer com totais
      csvRows.push(['','','','','TOTAL', totals.un, '', '', totals.valor.toFixed(2).replace('.', ','), ''].join(';'));
      const csv = '﻿' + csvRows.join('\n');  // BOM pra Excel detectar UTF-8
      const blob = new Blob([csv], {type:'text/csv;charset=utf-8;'});
      const url = URL.createObjectURL(blob);
      const date = new Date().toISOString().slice(0,10);
      const a = document.createElement('a');
      a.href = url;
      a.download = `inventario_${(w.code||w.name||'deposito').replace(/[^\w-]/g,'_')}_${date}.csv`;
      document.body.appendChild(a); a.click(); document.body.removeChild(a);
      URL.revokeObjectURL(url);
      if(typeof toast === 'function') toast('📊 CSV baixado: '+rows.length+' SKUs','success');
    };

    // Cores por status
    const statusColor = (st)=>({
      OK: {bg:'#DCFCE7', fg:'#166534', border:'#86EFAC', label:'OK'},
      BAIXO: {bg:'#FEF3C7', fg:'#92400E', border:'#FCD34D', label:'BAIXO'},
      ZERO: {bg:'#FEE2E2', fg:'#991B1B', border:'#FCA5A5', label:'ZERO'}
    })[st];
    const qtyColor = (st)=>({OK:'#15803D', BAIXO:'#B45309', ZERO:'#B91C1C'})[st];

    return (
      <div style={{display:'flex', flexDirection:'column', background:'#FAFAF7', minHeight:'calc(100vh - 80px)', margin:'-20px', borderRadius:0}}>
          {/* HEADER DOURADO COM BOTÃO VOLTAR */}
          <div style={{
            background:'linear-gradient(135deg, #1B2A4A 0%, #2A3F66 100%)',
            color:'#fff', padding:'18px 22px',
            borderBottom:'3px solid #B89840'
          }}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12}}>
              <div style={{display:'flex',alignItems:'center',gap:14}}>
                <button onClick={onClose}
                  title="Voltar para Depósitos"
                  style={{background:'rgba(255,255,255,.1)',color:'#fff',border:'1px solid rgba(255,255,255,.3)',padding:'8px 14px',borderRadius:6,cursor:'pointer',fontSize:13,fontWeight:600,whiteSpace:'nowrap'}}>
                  ← Voltar
                </button>
                <div>
                  <div style={{fontSize:11,color:'#B89840',fontWeight:700,letterSpacing:1,marginBottom:2}}>INVENTÁRIO POR DEPÓSITO</div>
                  <h2 style={{margin:0, fontSize:22, fontWeight:800, display:'flex', alignItems:'center', gap:10}}>
                    📦 {w.name}
                    {w.is_principal && (
                      <span style={{background:'#B89840',color:'#fff',padding:'3px 10px',borderRadius:4,fontSize:10,fontWeight:700,letterSpacing:0.5}}>PRINCIPAL</span>
                    )}
                  </h2>
                  <div style={{fontSize:12, color:'#9CA3AF', marginTop:4}}>{w.code}</div>
                </div>
              </div>
              <button onClick={exportCSV}
                style={{background:'#15803D',color:'#fff',border:'none',padding:'10px 18px',borderRadius:6,fontWeight:700,cursor:'pointer',fontSize:13,boxShadow:'0 2px 4px rgba(0,0,0,.2)',whiteSpace:'nowrap'}}>
                ⬇ Exportar Excel ({rows.length})
              </button>
            </div>
          </div>

          {/* STATS GRANDES */}
          <div style={{display:'grid',gridTemplateColumns:'repeat(4, 1fr)',gap:1,background:'#E5E7EB',borderBottom:'1px solid #E5E7EB'}}>
            <div style={{background:'#fff',padding:'14px 16px'}}>
              <div style={{fontSize:10,color:'#6B7280',fontWeight:600,letterSpacing:0.5}}>SKUs FILTRADOS</div>
              <div style={{fontSize:24,fontWeight:800,color:'#1B2A4A',marginTop:2}}>{totals.skus.toLocaleString('pt-BR')}</div>
            </div>
            <div style={{background:'#fff',padding:'14px 16px'}}>
              <div style={{fontSize:10,color:'#6B7280',fontWeight:600,letterSpacing:0.5}}>TOTAL UNIDADES</div>
              <div style={{fontSize:24,fontWeight:800,color:'#1B2A4A',marginTop:2}}>{totals.un.toLocaleString('pt-BR')}</div>
            </div>
            <div style={{background:'#F0FDF4',padding:'14px 16px'}}>
              <div style={{fontSize:10,color:'#15803D',fontWeight:600,letterSpacing:0.5}}>VALOR TOTAL</div>
              <div style={{fontSize:20,fontWeight:800,color:'#15803D',marginTop:2}}>R$ {totals.valor.toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})}</div>
            </div>
            <div style={{background: totals.abaixoMin>0 ? '#FEF2F2' : '#fff', padding:'14px 16px'}}>
              <div style={{fontSize:10,color:totals.abaixoMin>0?'#B91C1C':'#6B7280',fontWeight:600,letterSpacing:0.5}}>ALERTAS</div>
              <div style={{fontSize:14,fontWeight:700,color:totals.abaixoMin>0?'#B91C1C':'#6B7280',marginTop:6}}>
                {totals.abaixoMin > 0 && <span style={{display:'inline-block',marginRight:10}}>⚠️ {totals.abaixoMin} baixo</span>}
                {totals.zero > 0 && <span>⛔ {totals.zero} zerado</span>}
                {totals.abaixoMin === 0 && totals.zero === 0 && <span style={{color:'#15803D'}}>✓ Tudo OK</span>}
              </div>
            </div>
          </div>

          {/* FILTROS COMO CHIPS */}
          <div style={{padding:'12px 16px', background:'#fff', borderBottom:'1px solid #E5E7EB'}}>
            <div style={{display:'flex',gap:8,flexWrap:'wrap',alignItems:'center'}}>
              <input type="text" value={search} onChange={e=>setSearch(e.target.value)}
                placeholder="🔍 Buscar produto, marca, código..."
                style={{flex:'1 1 280px',padding:'9px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:13,outline:'none'}}/>
              <select value={filterMarca} onChange={e=>setFilterMarca(e.target.value)}
                style={{padding:'9px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:13,background:'#fff',cursor:'pointer'}}>
                <option value="">📋 Todas marcas ({marcas.length})</option>
                {marcas.map(m=><option key={m} value={m}>{m}</option>)}
              </select>
              <select value={filterCategoria} onChange={e=>setFilterCategoria(e.target.value)}
                style={{padding:'9px 12px',border:'1px solid #D1D5DB',borderRadius:6,fontSize:13,background:'#fff',cursor:'pointer'}}>
                <option value="">📂 Todas categorias</option>
                {categorias.map(c=><option key={c} value={c}>{c}</option>)}
              </select>
              <label style={{display:'flex',alignItems:'center',gap:6,padding:'8px 12px',background:showOnlyStock?'#DBEAFE':'#F3F4F6',borderRadius:6,cursor:'pointer',fontSize:12,fontWeight:600,color:showOnlyStock?'#1E40AF':'#6B7280',userSelect:'none'}}>
                <input type="checkbox" checked={showOnlyStock} onChange={e=>setShowOnlyStock(e.target.checked)} style={{cursor:'pointer'}}/> 📦 Só com estoque
              </label>
              <label style={{display:'flex',alignItems:'center',gap:6,padding:'8px 12px',background:showOnlyAbaixoMin?'#FEE2E2':'#F3F4F6',borderRadius:6,cursor:'pointer',fontSize:12,fontWeight:600,color:showOnlyAbaixoMin?'#B91C1C':'#6B7280',userSelect:'none'}}>
                <input type="checkbox" checked={showOnlyAbaixoMin} onChange={e=>setShowOnlyAbaixoMin(e.target.checked)} style={{cursor:'pointer'}}/> ⚠️ Abaixo mínimo
              </label>
            </div>
          </div>

          {/* TABELA — qty bem destacada */}
          <div style={{flex:1, overflow:'auto', background:'#fff'}}>
            <table style={{width:'100%',borderCollapse:'collapse',fontSize:13}}>
              <thead style={{background:'#1B2A4A', color:'#fff', position:'sticky', top:0, zIndex:2}}>
                <tr>
                  <th onClick={()=>toggleSort('brand')} style={{padding:'12px 14px',fontWeight:700,fontSize:11,textAlign:'left',cursor:'pointer',userSelect:'none',letterSpacing:0.5,whiteSpace:'nowrap'}}>
                    MARCA{sortBy==='brand' && (sortDir==='asc'?' ↑':' ↓')}
                  </th>
                  <th onClick={()=>toggleSort('name')} style={{padding:'12px 14px',fontWeight:700,fontSize:11,textAlign:'left',cursor:'pointer',userSelect:'none',letterSpacing:0.5}}>
                    PRODUTO{sortBy==='name' && (sortDir==='asc'?' ↑':' ↓')}
                  </th>
                  <th onClick={()=>toggleSort('qty')} style={{padding:'12px 14px',fontWeight:700,fontSize:11,textAlign:'center',cursor:'pointer',userSelect:'none',letterSpacing:0.5,minWidth:90,background:'#B89840'}}>
                    QUANTIDADE{sortBy==='qty' && (sortDir==='asc'?' ↑':' ↓')}
                  </th>
                  <th onClick={()=>toggleSort('min')} style={{padding:'12px 14px',fontWeight:700,fontSize:11,textAlign:'center',cursor:'pointer',userSelect:'none',letterSpacing:0.5}}>
                    MÍNIMO{sortBy==='min' && (sortDir==='asc'?' ↑':' ↓')}
                  </th>
                  <th onClick={()=>toggleSort('valor')} style={{padding:'12px 14px',fontWeight:700,fontSize:11,textAlign:'right',cursor:'pointer',userSelect:'none',letterSpacing:0.5,whiteSpace:'nowrap'}}>
                    VALOR R${sortBy==='valor' && (sortDir==='asc'?' ↑':' ↓')}
                  </th>
                  <th style={{padding:'12px 14px',fontWeight:700,fontSize:11,textAlign:'center',letterSpacing:0.5}}>
                    STATUS
                  </th>
                  <th style={{padding:'12px 14px',width:90,textAlign:'center'}}>HISTÓRICO</th>
                  {isAdmin && <th style={{padding:'12px 14px',width:80}}></th>}
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr><td colSpan={isAdmin?8:7} style={{padding:60,textAlign:'center',color:'#9CA3AF',fontSize:14}}>
                    🔍 Nenhum produto com os filtros atuais
                  </td></tr>
                ) : rows.map((r, idx)=>{
                  const sc = statusColor(r.status);
                  const qc = qtyColor(r.status);
                  return (
                    <tr key={r.id} style={{
                      borderTop:'1px solid #F3F4F6',
                      background: idx % 2 === 0 ? '#fff' : '#FAFAF7',
                      transition:'background .15s'
                    }}
                    onMouseEnter={e=>e.currentTarget.style.background='#FEF9E7'}
                    onMouseLeave={e=>e.currentTarget.style.background = idx % 2 === 0 ? '#fff' : '#FAFAF7'}>
                      <td style={{padding:'14px',color:'#374151',fontWeight:600,fontSize:12,whiteSpace:'nowrap'}}>
                        {r.brand || <span style={{color:'#9CA3AF'}}>—</span>}
                      </td>
                      <td style={{padding:'14px'}}>
                        <div style={{color:'#1B2A4A',fontWeight:600,fontSize:13,lineHeight:1.3}}>{r.name}</div>
                        <div style={{display:'flex',gap:8,marginTop:4,fontSize:10,color:'#6B7280'}}>
                          {r.volume && <span style={{background:'#F3F4F6',padding:'2px 6px',borderRadius:3,fontWeight:600}}>{r.volume}</span>}
                          {r.categoria && <span style={{background:'#F3F4F6',padding:'2px 6px',borderRadius:3}}>{r.categoria}</span>}
                          {r.code && <span style={{color:'#9CA3AF',fontFamily:'monospace'}}>#{r.code}</span>}
                        </div>
                      </td>
                      <td style={{padding:'14px',textAlign:'center'}}>
                        <div style={{
                          display:'inline-block',
                          background: r.status==='ZERO'?'#FEE2E2':r.status==='BAIXO'?'#FEF3C7':'#F0FDF4',
                          padding:'8px 14px',
                          borderRadius:8,
                          minWidth:60,
                          border:`2px solid ${r.status==='ZERO'?'#FCA5A5':r.status==='BAIXO'?'#FCD34D':'#86EFAC'}`
                        }}>
                          <div style={{fontSize:22,fontWeight:800,color:qc,lineHeight:1}}>{r.qty}</div>
                          <div style={{fontSize:9,color:qc,opacity:0.8,marginTop:2,fontWeight:600}}>UN.</div>
                        </div>
                      </td>
                      <td style={{padding:'14px',textAlign:'center',color:'#6B7280',fontSize:12}}>
                        {r.min > 0 ? <strong style={{color:'#374151'}}>{r.min}</strong> : <span style={{color:'#D1D5DB'}}>—</span>}
                      </td>
                      <td style={{padding:'14px',textAlign:'right'}}>
                        <div style={{fontWeight:700,color:'#15803D',fontSize:14}}>R$ {r.valor.toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})}</div>
                        <div style={{fontSize:10,color:'#9CA3AF',marginTop:2}}>R$ {r.price.toLocaleString('pt-BR',{minimumFractionDigits:2})}/un</div>
                      </td>
                      <td style={{padding:'14px',textAlign:'center'}}>
                        <span style={{
                          background: sc.bg, color: sc.fg, border:`1px solid ${sc.border}`,
                          padding:'4px 10px', borderRadius:12, fontSize:10, fontWeight:700, letterSpacing:0.5
                        }}>{sc.label}</span>
                      </td>
                      <td style={{padding:'12px',textAlign:'center'}}>
                        <button onClick={()=>onMovimentacoes(r.id)}
                          title="Ver movimentações do produto"
                          style={{background:'transparent',color:'#1B2A4A',border:'1px solid #D1D5DB',padding:'6px 10px',borderRadius:5,fontSize:10,fontWeight:600,cursor:'pointer',whiteSpace:'nowrap'}}>
                          🕐 Histórico
                        </button>
                      </td>
                      {isAdmin && (
                        <td style={{padding:'12px',textAlign:'center'}}>
                          <button onClick={()=>onAjustar(r.id)}
                            title="Ajustar inventário"
                            style={{background:'#1B2A4A',color:'#fff',border:'none',padding:'6px 10px',borderRadius:5,fontSize:10,fontWeight:600,cursor:'pointer',whiteSpace:'nowrap'}}>
                            ⚙️ Ajustar
                          </button>
                        </td>
                      )}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* FOOTER */}
          <div style={{padding:'10px 16px',background:'#fff',borderTop:'1px solid #E5E7EB',display:'flex',justifyContent:'space-between',alignItems:'center',fontSize:11,color:'#6B7280'}}>
            <span>Mostrando <strong style={{color:'#1B2A4A'}}>{rows.length}</strong> de <strong style={{color:'#1B2A4A'}}>{allRows.length}</strong> produtos</span>
            <span>Clique nos cabeçalhos pra ordenar · Clique no botão verde pra exportar Excel</span>
          </div>
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.depositos = window.ZNX.widgets.depositos || {};
  window.ZNX.widgets.depositos.DepositoInventarioPage = DepositoInventarioPage;
})();
