// js/components/widgets/app/DriftModal.jsx
// [Wave 5 MEDIUM 2026-05-16] Extraído de App.jsx L1335-1401 — refactor zero-lógica.
// Padrão: IIFE + window.ZNX.widgets.app.DriftModal namespace + props injection.
//
// Modal admin/financeiro "Drift Radar" — mostra inconsistências relacional vs JSONB:
// quotes/sales/devolucoes/purchases com total>0 mas sem items + orphan_quotes Convertido sem venda.
// Render-only (read-only), gate `showDriftModal && driftDetails` aplicado no caller.
//
// Props (validados FASE 1.5 = 4 props, ajustado de 3 pra incluir driftSummary do footer):
//   showDriftModal: bool (used in caller gate, recebido aqui pra completude)
//   setShowDriftModal: setter — close modal
//   driftDetails: object {quotes, sales, devolucoes, purchases, orphan_quotes} — content
//   driftSummary: object {checked_at, pending_discount_requests} — footer last check
//
// Deps runtime globals: Modal (window.Modal componente), fmt (window.fmt).
(function() {
  'use strict';

  function DriftModal({setShowDriftModal, driftDetails, driftSummary}){
    return (
      <Modal title="🔍 Drift Radar — Inconsistências detectadas" onClose={()=>setShowDriftModal(false)} large>
        <div style={{fontSize:13,color:'#374151',marginBottom:16}}>
          Sistema de monitoramento contínuo. Cada item abaixo precisa atenção:
        </div>
        {(driftDetails.quotes||[]).length>0&&(
          <div style={{marginBottom:14}}>
            <h4 style={{fontSize:13,color:'#DC2626',marginBottom:6}}>⚠ Orçamentos com total &gt; 0 mas sem items ({driftDetails.quotes.length})</h4>
            <table style={{fontSize:12}}>
              <thead><tr><th>Nº</th><th>Status</th><th>Total</th><th>Vendedor</th></tr></thead>
              <tbody>{driftDetails.quotes.map(q=>(
                <tr key={q.id}><td>{q.number}</td><td>{q.status}</td><td>{fmt(q.total)}</td><td>{q.seller_name}</td></tr>
              ))}</tbody>
            </table>
          </div>
        )}
        {(driftDetails.sales||[]).length>0&&(
          <div style={{marginBottom:14}}>
            <h4 style={{fontSize:13,color:'#DC2626',marginBottom:6}}>⚠ Vendas com subtotal &gt; 0 mas sem items ({driftDetails.sales.length})</h4>
            <table style={{fontSize:12}}>
              <thead><tr><th>Nº</th><th>Status</th><th>Subtotal</th><th>Vendedor</th></tr></thead>
              <tbody>{driftDetails.sales.map(s=>(
                <tr key={s.id}><td>{s.number}</td><td>{s.status}</td><td>{fmt(s.subtotal)}</td><td>{s.seller_name}</td></tr>
              ))}</tbody>
            </table>
          </div>
        )}
        {(driftDetails.devolucoes||[]).length>0&&(
          <div style={{marginBottom:14}}>
            <h4 style={{fontSize:13,color:'#DC2626',marginBottom:6}}>⚠ Devoluções com total &gt; 0 mas sem items ({driftDetails.devolucoes.length})</h4>
            <table style={{fontSize:12}}>
              <thead><tr><th>Nº</th><th>Sale ID</th><th>Total</th></tr></thead>
              <tbody>{driftDetails.devolucoes.map(d=>(
                <tr key={d.id}><td>{d.number}</td><td>{d.sale_id}</td><td>{fmt(d.total)}</td></tr>
              ))}</tbody>
            </table>
          </div>
        )}
        {(driftDetails.purchases||[]).length>0&&(
          <div style={{marginBottom:14}}>
            <h4 style={{fontSize:13,color:'#DC2626',marginBottom:6}}>⚠ Compras com total &gt; 0 mas sem items ({driftDetails.purchases.length})</h4>
            <table style={{fontSize:12}}>
              <thead><tr><th>Nº</th><th>Status</th><th>Total</th></tr></thead>
              <tbody>{driftDetails.purchases.map(p=>(
                <tr key={p.id}><td>{p.number}</td><td>{p.status}</td><td>{fmt(p.total)}</td></tr>
              ))}</tbody>
            </table>
          </div>
        )}
        {(driftDetails.orphan_quotes||[]).length>0&&(
          <div style={{marginBottom:14}}>
            <h4 style={{fontSize:13,color:'#EA580C',marginBottom:6}}>⚠ Orçamentos Convertido sem venda ({driftDetails.orphan_quotes.length})</h4>
            <div style={{fontSize:11,color:'#6B7280',marginBottom:6}}>Vendedor precisa reabrir e converter de novo.</div>
            <table style={{fontSize:12}}>
              <thead><tr><th>Nº</th><th>Sale Number alegado</th><th>Vendedor</th><th>Total</th></tr></thead>
              <tbody>{driftDetails.orphan_quotes.map(q=>(
                <tr key={q.id}><td>{q.number}</td><td>{q.sale_number||'—'}</td><td>{q.seller_name}</td><td>{fmt(q.total)}</td></tr>
              ))}</tbody>
            </table>
          </div>
        )}
        <div style={{marginTop:18,padding:'10px 14px',background:'#ECFDF5',borderRadius:8,fontSize:12,color:'#065F46'}}>
          Última checagem: {driftSummary?.checked_at?new Date(driftSummary.checked_at).toLocaleString('pt-BR'):'agora'}<br/>
          Re-check automático a cada 5 minutos. Pendências de desconto: {driftSummary?.pending_discount_requests||0}.
        </div>
      </Modal>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.app = window.ZNX.widgets.app || {};
  window.ZNX.widgets.app.DriftModal = DriftModal;
})();
