// js/components/widgets/VendaItemsTable.jsx
// [Wave 15 v223.40 20260520] Extraído de VendaTimeline.jsx L282-320
// Tabela items da venda — qtd × produto × unit × total
//
// Props: sale, products
// Deps runtime: window.fmtMoney/fmt + window.itemNet
(function(){
  'use strict';

  function VendaItemsTable(props){
    const sale = props.sale;
    const products = props.products || [];
    const fmtMoney = typeof window.fmtMoney === 'function' ? window.fmtMoney
                   : typeof window.fmt === 'function' ? window.fmt
                   : function(v){ return 'R$ '+Number(v||0).toFixed(2); };
    const itemNet = typeof window.itemNet === 'function' ? window.itemNet : function(it){ return Number((it && it.price) || 0); };

    if (!sale) return null;
    const items = sale.items || [];

    return (
      <div className="card">
        <div style={{fontSize:13,fontWeight:700,color:'#9CA3AF',marginBottom:12,textTransform:'uppercase',letterSpacing:1}}>
          📦 Items ({items.length})
        </div>
        {items.length === 0 ? (
          <div style={{color:'#6B7280',fontSize:13,padding:14,textAlign:'center'}}>Nenhum item.</div>
        ) : (
          <table>
            <thead>
              <tr>
                <th style={{width:50}}>Qtd</th>
                <th>Produto</th>
                <th style={{textAlign:'right'}}>Unit.</th>
                <th style={{textAlign:'right'}}>Total</th>
              </tr>
            </thead>
            <tbody>
              {items.map(function(it, i){
                const prod = products.find(function(p){ return p.id === it.productId; });
                const nm = it.name || it.productName || it.product_name || (prod && prod.name) || '—';
                const discountPct = it.discountPct || it.discount_pct;
                return (
                  <tr key={i}>
                    <td style={{fontWeight:600,color:'#1B2A4A'}}>{it.qty}×</td>
                    <td>
                      <div style={{fontSize:13,fontWeight:500}}>{nm}</div>
                      {discountPct > 0 && (
                        <div style={{fontSize:10,color:'#EA580C'}}>−{discountPct}%</div>
                      )}
                    </td>
                    <td style={{textAlign:'right',fontVariantNumeric:'tabular-nums'}}>{fmtMoney(it.price)}</td>
                    <td style={{textAlign:'right',fontVariantNumeric:'tabular-nums',fontWeight:600,color:'#16A34A'}}>
                      {fmtMoney(it.qty * itemNet(it))}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.VendaItemsTable = VendaItemsTable;
  window.VendaItemsTable = VendaItemsTable;
})();
