// js/components/widgets/vendas/SaleEditModal.jsx
// [Wave 26 v224.7 NUCLEAR] Modal EDIT venda gigante (admin+financeiro only)
// Extraído de Vendas.jsx L810-1022 (literal · saveEdit handler permanece no orquestrador)
//
// CRITICAL: handlers (saveEdit) recebidos como props · NÃO duplicar lógica RPC
// Deps runtime globals: fmt, Modal, SmartSelect, saleFinalTotal, searchProducts, nid
(function(){
  'use strict';

  function SaleEditModal(props){
    const fmt = window.fmt || function(v){return 'R$ '+Number(v||0).toFixed(2);};
    const Modal = window.Modal;
    const SmartSelect = window.SmartSelect;
    const saleFinalTotal = window.saleFinalTotal || function(f){return Number(f.total||0);};
    const searchProducts = window.searchProducts || function(){return [];};
    const nidFn = window.nid || function(a,b){return String(a)===String(b);};

    const {
      open, form, setForm, products,
      prodSearch, setProdSearch, showProdDrop, setShowProdDrop,
      isSavingEdit, onSave, onClose
    } = props;

    if(!open || !Modal) return null;

    return (
      <Modal title={'✏️ Editar Venda — '+(form.number||'')} onClose={onClose} large>
        {/* INFORMAÇÕES BÁSICAS */}
        <div style={{marginBottom:18}}>
          <div style={{fontSize:10,fontWeight:800,color:'#6B7280',letterSpacing:1.5,textTransform:'uppercase',marginBottom:10,paddingBottom:6,borderBottom:'1px solid #F3F4F6'}}>Informações Básicas</div>
          <div className="form-grid">
            <div className="form-group"><label>Data</label><input type="date" value={form.date||''} onChange={function(e){setForm(function(f){return Object.assign({},f,{date:e.target.value});});}}/></div>
            <div className="form-group"><label>Vendedor</label><input value={form.sellerName||''} onChange={function(e){setForm(function(f){return Object.assign({},f,{sellerName:e.target.value});});}}/></div>
            <div className="form-group"><label>Status</label>
              {SmartSelect && <SmartSelect value={form.status||''} onChange={function(val){setForm(function(f){return Object.assign({},f,{status:val});});}} options={['Aberto','Fechado','Em trânsito','Entregue','A receber','Cancelada'].map(function(s){return {value:s,label:s};})}/>}
            </div>
            <div className="form-group"><label>Pagamento</label>
              {SmartSelect && <SmartSelect value={form.paymentStatus||''} onChange={function(val){setForm(function(f){return Object.assign({},f,{paymentStatus:val});});}} options={['Pago','Pendente','Parcial'].map(function(s){return {value:s,label:s};})}/>}
            </div>
            <div className="form-group"><label>Canal</label><input value={form.canal||''} onChange={function(e){setForm(function(f){return Object.assign({},f,{canal:e.target.value});});}}/></div>
            <div className="form-group">
              <label>Forma de Pagamento</label>
              <div style={{display:'flex',gap:6}}>
                {[{k:'Pix',l:'🔵 Pix'},{k:'Dinheiro Vivo',l:'💵 Dinheiro'},{k:'Misto',l:'🔀 Misto'}].map(function(opt){
                  const k = opt.k, l = opt.l;
                  return (
                    <button key={k} onClick={function(){setForm(function(f){
                      // [BUG-FIX 20260507] Preserva pix/cash + auto-fill por método
                      if(f.paymentMethod===k) return Object.assign({},f,{paymentMethod:''});
                      const tot = saleFinalTotal(f) || 0;
                      if(k==='Pix') return Object.assign({},f,{paymentMethod:'Pix', paymentPixValue:tot, paymentCashValue:0});
                      if(k==='Dinheiro Vivo') return Object.assign({},f,{paymentMethod:'Dinheiro Vivo', paymentPixValue:0, paymentCashValue:tot});
                      const curPix = Number(f.paymentPixValue||0);
                      const curCash = Number(f.paymentCashValue||0);
                      if(curPix>0 && curCash>0 && Math.abs((curPix+curCash)-tot)<0.01) return Object.assign({},f,{paymentMethod:'Misto'});
                      const half = Math.round((tot/2)*100)/100;
                      return Object.assign({},f,{paymentMethod:'Misto', paymentPixValue:half, paymentCashValue:Math.round((tot-half)*100)/100});
                    });}}
                      style={{flex:1,padding:'8px 10px',borderRadius:8,border:'2px solid '+(form.paymentMethod===k?'#1B2A4A':'#E4E7EC'),background:form.paymentMethod===k?'#1B2A4A':'#F9FAFB',color:form.paymentMethod===k?'#B89840':'#374151',fontWeight:700,fontSize:12,cursor:'pointer',transition:'all .12s'}}>
                      {l}
                    </button>
                  );
                })}
              </div>
              {form.paymentMethod==='Misto' && (function(){
                const tot = Number(saleFinalTotal(form)||0);
                const pix = Number(form.paymentPixValue||0);
                const cash = Number(form.paymentCashValue||0);
                const sum = Number((pix+cash).toFixed(2));
                const diff = Number((tot-sum).toFixed(2));
                const ok = Math.abs(diff)<0.01 && pix>0 && cash>0;
                function setSplit(pixPct){
                  const pixVal = Math.round((tot*pixPct/100)*100)/100;
                  const cashVal = Math.round((tot-pixVal)*100)/100;
                  setForm(function(f){return Object.assign({},f,{paymentPixValue:pixVal, paymentCashValue:cashVal});});
                }
                return (
                  <div style={{marginTop:8,display:'grid',gridTemplateColumns:'1fr 1fr',gap:6}}>
                    <div style={{gridColumn:'1 / -1',display:'flex',gap:4,marginBottom:2}}>
                      <span style={{fontSize:10,color:'#6B7280',alignSelf:'center',marginRight:4}}>Sugerir:</span>
                      {[[50,'50/50'],[70,'70/30 (mais Pix)'],[30,'30/70 (mais 💵)']].map(function(pair){
                        const pct = pair[0], lbl = pair[1];
                        return <button key={pct} type="button" onClick={function(){setSplit(pct);}} style={{padding:'2px 8px',fontSize:10,border:'1px solid #E4E7EC',background:'#F9FAFB',borderRadius:4,cursor:'pointer',color:'#6B7280'}}>{lbl}</button>;
                      })}
                      {!ok && diff !== 0 && (pix>0||cash>0) && (
                        <button type="button" onClick={function(){
                          if(pix>=cash) setForm(function(f){return Object.assign({},f,{paymentPixValue:Math.round((Number(f.paymentPixValue)+diff)*100)/100});});
                          else setForm(function(f){return Object.assign({},f,{paymentCashValue:Math.round((Number(f.paymentCashValue)+diff)*100)/100});});
                        }} style={{padding:'2px 8px',fontSize:10,border:'1px solid #B89840',background:'#FEF3C7',borderRadius:4,cursor:'pointer',color:'#92400E',fontWeight:600,marginLeft:'auto'}}>⚖ Fechar diferença</button>
                      )}
                    </div>
                    <input type="number" min="0" step="0.01" value={pix||''}
                      onChange={function(e){setForm(function(f){return Object.assign({},f,{paymentPixValue:Number(e.target.value)||0});});}}
                      placeholder="🔵 Pix"
                      style={{padding:'7px 9px',borderRadius:6,border:'1px solid '+(ok?'#10B981':'#E4E7EC'),fontSize:13}}/>
                    <input type="number" min="0" step="0.01" value={cash||''}
                      onChange={function(e){setForm(function(f){return Object.assign({},f,{paymentCashValue:Number(e.target.value)||0});});}}
                      placeholder="💵 Dinheiro"
                      style={{padding:'7px 9px',borderRadius:6,border:'1px solid '+(ok?'#10B981':'#E4E7EC'),fontSize:13}}/>
                    <div style={{gridColumn:'1 / -1',fontSize:11,color:ok?'#065F46':'#991B1B',fontWeight:600}}>
                      {ok?'✅ Total: '+fmt(tot):(diff>0?'⚠️ Falta '+fmt(diff)+' (Total '+fmt(tot)+')':'⚠️ Excedeu '+fmt(Math.abs(diff))+' (Total '+fmt(tot)+')')}
                    </div>
                  </div>
                );
              })()}
            </div>
          </div>
        </div>

        {/* PRODUTOS */}
        <div style={{marginBottom:18}}>
          <div style={{fontSize:10,fontWeight:800,color:'#6B7280',letterSpacing:1.5,textTransform:'uppercase',marginBottom:10,paddingBottom:6,borderBottom:'1px solid #F3F4F6'}}>Produtos</div>
          <table style={{width:'100%',borderCollapse:'collapse',marginBottom:10,fontSize:13}}>
            <thead>
              <tr style={{background:'#F8F9FB'}}>
                <th style={{padding:'7px 8px',textAlign:'left',fontWeight:700,color:'#6B7280',fontSize:11}}>Produto</th>
                <th style={{padding:'7px 8px',textAlign:'center',fontWeight:700,color:'#6B7280',fontSize:11}}>Qtd</th>
                <th style={{padding:'7px 8px',textAlign:'center',fontWeight:700,color:'#6B7280',fontSize:11}}>Preço R$</th>
                <th style={{padding:'7px 8px',textAlign:'center',fontWeight:700,color:'#EA580C',fontSize:11}}>Desc %</th>
                <th style={{padding:'7px 8px',textAlign:'right',fontWeight:700,color:'#1B2A4A',fontSize:11}}>Subtotal</th>
                <th style={{padding:'7px 8px',width:36}}></th>
              </tr>
            </thead>
            <tbody>
              {(form.items||[]).map(function(it, i){
                const p = products.find(function(x){return nidFn(x.id, it.productId);});
                const net = it.qty * (it.price||0) * (1 - (it.discountPct||0)/100);
                return (
                  <tr key={i} style={{borderBottom:'1px solid #F3F4F6'}}>
                    <td style={{padding:'7px 8px'}}>
                      <div style={{fontWeight:600,color:'#1B2A4A',fontSize:13}}>{(p && p.name) || it.name || it.productName || it.product_name || '—'}</div>
                      <div style={{fontSize:11,color:'#9CA3AF'}}>{it.brand || (p && p.brand) || ''}{it.volume?' · '+it.volume:''}</div>
                    </td>
                    <td style={{padding:'7px 8px',textAlign:'center'}}>
                      <input type="number" min="1" value={it.qty}
                        onChange={function(e){setForm(function(f){return Object.assign({},f,{items:f.items.map(function(x,idx){return idx===i?Object.assign({},x,{qty:Math.max(1,parseInt(e.target.value)||1)}):x;})});});}}
                        style={{width:54,textAlign:'center',padding:'5px 4px',borderRadius:6,border:'1.5px solid #D1D5DB',fontSize:13,fontWeight:600}}/>
                    </td>
                    <td style={{padding:'7px 8px',textAlign:'center'}}>
                      <input type="number" min="0" step="0.01" value={it.price}
                        onChange={function(e){setForm(function(f){return Object.assign({},f,{items:f.items.map(function(x,idx){return idx===i?Object.assign({},x,{price:parseFloat(e.target.value)||0}):x;})});});}}
                        style={{width:70,textAlign:'center',padding:'5px 4px',borderRadius:6,border:'1.5px solid #D1D5DB',fontSize:13}}/>
                    </td>
                    <td style={{padding:'7px 8px',textAlign:'center'}}>
                      <input type="number" min="0" max="100" step="0.1" value={it.discountPct||''}
                        onChange={function(e){setForm(function(f){return Object.assign({},f,{items:f.items.map(function(x,idx){return idx===i?Object.assign({},x,{discountPct:Math.min(100,parseFloat(e.target.value)||0)}):x;})});});}}
                        style={{width:54,textAlign:'center',padding:'5px 4px',borderRadius:6,border:'1.5px solid '+(it.discountPct>0?'#EA580C':'#D1D5DB'),fontSize:13,color:it.discountPct>0?'#EA580C':'inherit'}}/>
                    </td>
                    <td style={{padding:'7px 8px',textAlign:'right',fontWeight:700,color:'#B89840',fontSize:13}}>{fmt(net)}</td>
                    <td style={{padding:'7px 8px',textAlign:'center'}}>
                      <button onClick={function(){setForm(function(f){return Object.assign({},f,{items:f.items.filter(function(_,idx){return idx!==i;})});});}}
                        style={{background:'none',border:'none',color:'#DC2626',cursor:'pointer',fontSize:16,padding:'2px',lineHeight:1}}>🗑</button>
                    </td>
                  </tr>
                );
              })}
              {(form.items||[]).length===0 && <tr><td colSpan={6} style={{padding:'14px',textAlign:'center',color:'#9CA3AF',fontSize:13}}>Nenhum produto adicionado</td></tr>}
            </tbody>
          </table>
          {/* Adicionar produto */}
          <div style={{position:'relative'}}>
            <input value={prodSearch} onChange={function(e){setProdSearch(e.target.value); setShowProdDrop(true);}}
              onFocus={function(){setShowProdDrop(true);}}
              onBlur={function(){setTimeout(function(){setShowProdDrop(false);},160);}}
              placeholder="🔍 Buscar produto para adicionar..."
              style={{width:'100%',padding:'9px 14px',borderRadius:8,border:'1.5px solid #D1D5DB',fontSize:13,boxSizing:'border-box',fontFamily:"'Plus Jakarta Sans',sans-serif"}}/>
            {showProdDrop && prodSearch.trim() && (function(){
              const plist = searchProducts(products, prodSearch).slice(0, 10);
              if(!plist.length) return null;
              return (
                <div style={{position:'absolute',top:'calc(100% + 4px)',left:0,right:0,background:'#fff',border:'1.5px solid #1B2A4A44',borderRadius:8,maxHeight:220,overflowY:'auto',zIndex:500,boxShadow:'0 8px 24px rgba(0,0,0,.14)'}}>
                  {plist.map(function(p){
                    return (
                      <div key={p.id}
                        onMouseDown={function(){
                          const idx = (form.items||[]).findIndex(function(x){return nidFn(x.productId, p.id);});
                          if(idx >= 0){
                            setForm(function(f){return Object.assign({},f,{items:f.items.map(function(x,i){return i===idx?Object.assign({},x,{qty:x.qty+1}):x;})});});
                          } else {
                            setForm(function(f){return Object.assign({},f,{items:(f.items||[]).concat([{productId:p.id, qty:1, price:p.salePrice||0, discountPct:0, name:p.name, brand:p.brand, volume:p.volume}])});});
                          }
                          setProdSearch(''); setShowProdDrop(false);
                        }}
                        style={{padding:'9px 14px',cursor:'pointer',borderBottom:'1px solid #F3F4F6',display:'flex',justifyContent:'space-between',alignItems:'center'}}
                        onMouseEnter={function(e){e.currentTarget.style.background='#F8F9FB';}}
                        onMouseLeave={function(e){e.currentTarget.style.background='transparent';}}>
                        <div>
                          <div style={{fontSize:13,fontWeight:600,color:'#1B2A4A'}}>{p.name}</div>
                          <div style={{fontSize:11,color:'#9CA3AF'}}>{p.brand} {p.volume}</div>
                        </div>
                        <div style={{textAlign:'right',flexShrink:0}}>
                          <div style={{fontSize:13,fontWeight:700,color:'#B89840'}}>{fmt(p.salePrice)}</div>
                          <div style={{fontSize:11,color:p.stock>0?'#16A34A':'#DC2626'}}>Estoque: {p.stock}</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              );
            })()}
          </div>
        </div>

        {/* DESCONTO GLOBAL */}
        <div style={{marginBottom:18}}>
          <div style={{fontSize:10,fontWeight:800,color:'#6B7280',letterSpacing:1.5,textTransform:'uppercase',marginBottom:10,paddingBottom:6,borderBottom:'1px solid #F3F4F6'}}>Desconto Global</div>
          <div style={{display:'flex',gap:8,flexWrap:'wrap',alignItems:'center'}}>
            {[{t:'',l:'Sem desconto'},{t:'pct',l:'% Percentual'},{t:'val',l:'R$ Valor fixo'}].map(function(opt){
              const t = opt.t, l = opt.l;
              return (
                <button key={t} onClick={function(){setForm(function(f){return Object.assign({},f,{globalDiscountType:t, globalDiscountValue:0});});}}
                  style={{padding:'8px 14px',borderRadius:8,border:'2px solid '+(form.globalDiscountType===t&&t?'#B89840':'#E4E7EC'),background:form.globalDiscountType===t&&t?'#FFFBEB':'#F9FAFB',color:form.globalDiscountType===t&&t?'#92700A':'#374151',fontWeight:700,fontSize:13,cursor:'pointer',transition:'all .12s'}}>
                  {l}
                </button>
              );
            })}
            {form.globalDiscountType && (
              <input type="number" min="0" max={form.globalDiscountType==='pct'?100:undefined} step={form.globalDiscountType==='pct'?1:10}
                value={form.globalDiscountValue||''} onChange={function(e){setForm(function(f){return Object.assign({},f,{globalDiscountValue:parseFloat(e.target.value)||0});});}}
                placeholder={form.globalDiscountType==='pct'?'Ex: 5':'Ex: 50'}
                style={{width:110,padding:'8px 12px',borderRadius:8,border:'1.5px solid #B89840',fontSize:14,fontWeight:700,color:'#92700A'}}/>
            )}
          </div>
        </div>

        {/* TOTAL */}
        <div style={{background:'#1B2A4A',borderRadius:10,padding:'12px 18px',marginBottom:16,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <span style={{fontWeight:700,color:'#9CA3AF',fontSize:13}}>Total da Venda</span>
          <span style={{fontWeight:900,fontSize:20,color:'#B89840'}}>{fmt(saleFinalTotal(form))}</span>
        </div>

        {/* OBS */}
        <div className="form-group full" style={{marginBottom:16}}>
          <label>Observações</label>
          <textarea rows={3} value={form.obs||''} onChange={function(e){setForm(function(f){return Object.assign({},f,{obs:e.target.value});});}}/>
        </div>

        <div style={{display:'flex',gap:10,justifyContent:'flex-end'}}>
          <button className="btn-outline" onClick={onClose} disabled={isSavingEdit}>Cancelar</button>
          <button className="btn-gold" onClick={onSave} disabled={isSavingEdit} style={{opacity:isSavingEdit?0.6:1,cursor:isSavingEdit?'not-allowed':'pointer'}}>{isSavingEdit?'⏳ Salvando…':'💾 Salvar Alterações'}</button>
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.vendas = window.ZNX.widgets.vendas || {};
  window.ZNX.widgets.vendas.SaleEditModal = SaleEditModal;
  window.SaleEditModal_v224_7_wave26 = true;
})();
