// js/components/widgets/depositos/MovimentacoesProdutoPage.jsx
// [Wave 3 KIMI 2026-05-15] Extraído de Depositos.jsx — refactor mecânico zero-lógica.
// Self-contained: zero closures escopo pai.
// Globals runtime: window.sb (Supabase).
//
// Props (preservadas byte-by-byte):
//   product_id, products, onClose
(function() {
  'use strict';
  const {useState, useEffect, useMemo} = React;

  function MovimentacoesProdutoPage({product_id, products, onClose}){
    const sb = window.sb;
    const [loading, setLoading] = useState(true);
    const [moves, setMoves] = useState([]);
    const [err, setErr] = useState(null);

    const product = useMemo(()=>(products||[]).find(p=>p.id===product_id), [products, product_id]);

    useEffect(()=>{
      let cancelled = false;
      (async ()=>{
        setLoading(true); setErr(null);
        try{
          const {data, error} = await sb.rpc('product_movement_history', {
            p_product_id: product_id,
            p_limit: 200
          });
          if(error) throw error;
          if(!cancelled) setMoves(data || []);
        }catch(e){
          if(!cancelled) setErr(e?.message || 'erro');
          console.error('[Movimentacoes]', e);
        }
        if(!cancelled) setLoading(false);
      })();
      return ()=>{cancelled=true;};
    }, [product_id]);

    const tipoConfig = {
      TRANSFERENCIA_ENVIO: {icon:'📤', color:'#B45309', bg:'#FEF3C7', label:'Envio'},
      TRANSFERENCIA_RECEBIMENTO: {icon:'📥', color:'#15803D', bg:'#DCFCE7', label:'Recebimento'},
      TRANSFERENCIA_CANCELADA: {icon:'↩️', color:'#6B7280', bg:'#F3F4F6', label:'Transf. cancelada'},
      COMPRA_RECEBIDA: {icon:'📦', color:'#1E40AF', bg:'#DBEAFE', label:'Compra recebida'},
      VENDA: {icon:'💰', color:'#B91C1C', bg:'#FEE2E2', label:'Venda'},
      DEVOLUCAO: {icon:'🔄', color:'#7C3AED', bg:'#EDE9FE', label:'Devolução'},
      AJUSTE_MANUAL: {icon:'⚙️', color:'#374151', bg:'#F3F4F6', label:'Ajuste manual'}
    };

    const fmtDate = (iso)=>{
      try{ return new Date(iso).toLocaleString('pt-BR',{dateStyle:'short',timeStyle:'short'}); }
      catch{ return iso; }
    };

    return (
      <div style={{display:'flex', flexDirection:'column', background:'#FAFAF7', minHeight:'calc(100vh - 80px)', margin:'-20px'}}>
          {/* HEADER FULL-WIDTH */}
          <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"
                  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}}>HISTÓRICO DO PRODUTO</div>
                  <h2 style={{margin:'2px 0 0 0', fontSize:22, fontWeight:800}}>
                    🕐 {product ? `${product.brand||''} ${product.name||''}`.trim() : '...'}
                  </h2>
                  <div style={{fontSize:12, color:'#9CA3AF', marginTop:4}}>
                    {moves.length} movimentação{moves.length===1?'':'s'} {loading && '· carregando...'}
                    {product && (product.code || product.volume) && (
                      <span style={{marginLeft:8}}>
                        {product.volume && <span>· {product.volume}</span>}
                        {product.code && <span style={{fontFamily:'monospace',marginLeft:6}}>#{product.code}</span>}
                      </span>
                    )}
                  </div>
                </div>
              </div>
              {product && (
                <div style={{textAlign:'right'}}>
                  <div style={{fontSize:10,color:'#9CA3AF',fontWeight:600,letterSpacing:0.5}}>ESTOQUE TOTAL</div>
                  <div style={{fontSize:24,fontWeight:800,color:'#fff',marginTop:2}}>{Number(product.stock || 0).toLocaleString('pt-BR')} <span style={{fontSize:11,color:'#9CA3AF',fontWeight:600}}>UN.</span></div>
                </div>
              )}
            </div>
          </div>

          {/* TIMELINE FULL-WIDTH */}
          <div style={{flex:1, overflow:'auto', padding:'20px 28px', background:'#FAFAF7'}}>
            {loading ? (
              <div style={{padding:40,textAlign:'center',color:'#6B7280'}}>Carregando histórico...</div>
            ) : err ? (
              <div style={{padding:20,background:'#FEE2E2',color:'#991B1B',borderRadius:6,fontSize:13}}>Erro: {err}</div>
            ) : moves.length === 0 ? (
              <div style={{padding:40,textAlign:'center',color:'#9CA3AF',fontSize:14}}>
                📭 Nenhuma movimentação registrada pra este produto
              </div>
            ) : (
              <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {moves.map((m, idx)=>{
                  const cfg = tipoConfig[m.tipo] || {icon:'•', color:'#374151', bg:'#F3F4F6', label:m.tipo};
                  const qty = Number(m.qty || 0);
                  const isPositive = qty > 0;
                  return (
                    <div key={idx} style={{
                      background:'#fff', border:'1px solid #E5E7EB', borderLeft:`5px solid ${cfg.color}`,
                      borderRadius:8, padding:'16px 20px',
                      display:'grid', gridTemplateColumns:'auto 1fr auto auto', gap:18, alignItems:'center',
                      boxShadow:'0 1px 3px rgba(0,0,0,.04)'
                    }}>
                      <div style={{fontSize:30}}>{cfg.icon}</div>
                      <div>
                        <div style={{display:'flex',gap:10,alignItems:'center',marginBottom:6}}>
                          <span style={{background:cfg.bg, color:cfg.color, padding:'3px 10px', borderRadius:12, fontSize:11, fontWeight:700, letterSpacing:0.5}}>
                            {cfg.label}
                          </span>
                          {m.ref_number && (
                            <span style={{fontFamily:'monospace', fontSize:12, color:'#374151', fontWeight:700, background:'#F3F4F6', padding:'2px 8px', borderRadius:4}}>{m.ref_number}</span>
                          )}
                        </div>
                        <div style={{fontSize:14, color:'#1B2A4A', lineHeight:1.4}}>
                          {m.warehouse_from && m.warehouse_to ? (
                            <span><strong>{m.warehouse_from}</strong> <span style={{color:'#9CA3AF'}}>→</span> <strong>{m.warehouse_to}</strong></span>
                          ) : m.warehouse_to ? (
                            <span><span style={{color:'#9CA3AF'}}>→</span> <strong>{m.warehouse_to}</strong></span>
                          ) : m.warehouse_from ? (
                            <span><strong>{m.warehouse_from}</strong></span>
                          ) : <span style={{color:'#9CA3AF'}}>—</span>}
                          {m.ator && <span style={{color:'#6B7280',marginLeft:10,fontSize:12}}>👤 {m.ator}</span>}
                        </div>
                        {m.notes && (
                          <div style={{fontSize:12, color:'#6B7280', marginTop:6, fontStyle:'italic', background:'#FAFAF7', padding:'6px 10px', borderRadius:4, display:'inline-block'}}>{m.notes}</div>
                        )}
                      </div>
                      <div style={{textAlign:'right',padding:'8px 14px',background: isPositive?'#F0FDF4':qty<0?'#FEF2F2':'#F9FAFB',borderRadius:8,minWidth:70}}>
                        <div style={{
                          fontSize:24, fontWeight:800, lineHeight:1,
                          color: isPositive ? '#15803D' : qty < 0 ? '#B91C1C' : '#6B7280'
                        }}>
                          {isPositive ? '+' : ''}{qty}
                        </div>
                        <div style={{fontSize:10, color: isPositive ? '#15803D' : qty < 0 ? '#B91C1C' : '#6B7280', fontWeight:600, marginTop:2, opacity:0.8}}>UN.</div>
                      </div>
                      <div style={{textAlign:'right',fontSize:12,color:'#6B7280',whiteSpace:'nowrap',minWidth:130,fontWeight:500}}>
                        {fmtDate(m.data)}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
      </div>
    );
  }

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