// ── InovaPED — Retorno da Cotação (cortes / não faturados) ──────────────
// Mostra, por pedido fechado, o que o fornecedor REALMENTE faturou contra o
// que foi pedido na cotação. Destaca cortes (sem estoque, preço, validade,
// lote mínimo, descontinuado), o valor perdido e ação de recotar.
const TopbarRet = window.BuyerParts1.Topbar;
const ICret = window.IC;

const RET_MOTIVO = {
  sem_estoque:   { label: 'Sem estoque',    color: '#FF4D4D', icon: 'box' },
  preco:         { label: 'Preço',          color: '#FFC83D', icon: 'tag' },
  validade:      { label: 'Validade curta', color: '#FF9E80', icon: 'clock' },
  minimo:        { label: 'Lote mínimo',    color: '#4EA8DE', icon: 'list' },
  descontinuado: { label: 'Descontinuado',  color: '#C77DFF', icon: 'x' },
};
function retA(hex, a) { const h=(hex||'#888').replace('#',''); const n=parseInt(h.length===3?h.split('').map(c=>c+c).join(''):h,16); return `rgba(${(n>>16)&255},${(n>>8)&255},${n&255},${a})`; }
const retBRL = n => (n==null||isNaN(n)) ? '—' : n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// agrega um retorno → totais pedido/faturado/corte
function retAgg(r) {
  let vPed = 0, vFat = 0, nCorte = 0, nTotal = r.items.length;
  for (const it of r.items) {
    vPed += it.ped * it.cu;
    vFat += it.fat * it.cu;
    if (it.fat < it.ped) nCorte++;
  }
  return { vPed, vFat, vCorte: vPed - vFat, nCorte, nTotal, pct: vPed ? (vFat / vPed * 100) : 100 };
}

// ── barra faturado x corte ──────────────────────────────────────────────
function RetBar({ ped, fat }) {
  const pct = ped ? Math.round(fat / ped * 100) : 100;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
      <div style={{ flex: 1, height: 7, borderRadius: 99, background: retA('#FF4D4D', 0.25), overflow: 'hidden' }}>
        <div className="dxhbar" style={{ width: pct + '%', height: '100%', borderRadius: 99, background: pct === 100 ? T.green : (pct >= 60 ? '#FFC83D' : '#FF4D4D') }} />
      </div>
      <span style={{ fontFamily: 'var(--mono)', fontSize: 12, fontWeight: 700, color: pct === 100 ? T.green : T.text, width: 38, textAlign: 'right' }}>{pct}%</span>
    </div>
  );
}

// ── card de KPI topo ────────────────────────────────────────────────────
function RetKpi({ label, value, sub, color, icon }) {
  const c = color || T.red;
  return (
    <Glass pad={16} style={{ position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: `linear-gradient(90deg, ${c}, ${retA(c,0)})` }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ fontSize: 12, color: T.mute, fontWeight: 600 }}>{label}</div>
        {icon && <div style={{ width: 30, height: 30, borderRadius: 8, background: retA(c, 0.15), display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={icon} size={15} color={c} /></div>}
      </div>
      <div style={{ fontSize: 25, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.5, marginTop: 9, color: c }}>{value}</div>
      {sub && <div style={{ fontSize: 11.5, color: T.mute2, marginTop: 3 }}>{sub}</div>}
    </Glass>
  );
}

// ── detalhe de um retorno ───────────────────────────────────────────────
function RetDetail({ r, onRequote }) {
  const cat = ICret.CATEGORIES.find(c => c.id === r.cat) || {};
  const rep = ICret.REPS.find(x => x.id === r.rep) || {};
  const ag = retAgg(r);
  return (
    <Glass style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, background: T.redBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="receipt" size={20} color={T.redBright} /></div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 800, fontSize: 16, fontFamily: 'var(--display)' }}>{r.id} <span style={{ color: T.mute2, fontWeight: 500, fontSize: 13 }}>· cotação {r.quote}</span></div>
            <div style={{ fontSize: 12.5, color: T.mute }}>{r.date} · {cat.name || r.cat} · {rep.name || r.rep}</div>
          </div>
        </div>
        {ag.nCorte === 0
          ? <Pill tone="green"><Icon name="check" size={13} color={T.green} /> Faturado integral</Pill>
          : <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 12px', borderRadius: 99, fontSize: 12.5, fontWeight: 700, background: retA('#FF4D4D', 0.13), color: '#FF6B6B', border: `1px solid ${retA('#FF4D4D',0.32)}` }}><Icon name="bolt" size={13} color="#FF6B6B" /> {ag.nCorte} de {ag.nTotal} itens com corte</span>}
      </div>

      {/* resumo financeiro */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 10, marginBottom: 16 }}>
        <div style={{ padding: '11px 14px', borderRadius: 11, background: T.panel, border: `1px solid ${T.border}` }}>
          <div style={{ fontSize: 11, color: T.mute, fontWeight: 600 }}>Pedido</div>
          <div style={{ fontSize: 18, fontWeight: 800, fontFamily: 'var(--mono)' }}>R$ {retBRL(ag.vPed)}</div>
        </div>
        <div style={{ padding: '11px 14px', borderRadius: 11, background: retA(T.green, 0.07), border: `1px solid ${retA(T.green,0.25)}` }}>
          <div style={{ fontSize: 11, color: T.mute, fontWeight: 600 }}>Faturado</div>
          <div style={{ fontSize: 18, fontWeight: 800, fontFamily: 'var(--mono)', color: T.green }}>R$ {retBRL(ag.vFat)}</div>
        </div>
        <div style={{ padding: '11px 14px', borderRadius: 11, background: retA('#FF4D4D', 0.07), border: `1px solid ${retA('#FF4D4D',0.25)}` }}>
          <div style={{ fontSize: 11, color: T.mute, fontWeight: 600 }}>Corte (não faturado)</div>
          <div style={{ fontSize: 18, fontWeight: 800, fontFamily: 'var(--mono)', color: '#FF6B6B' }}>R$ {retBRL(ag.vCorte)}</div>
        </div>
        <div style={{ padding: '11px 14px', borderRadius: 11, background: T.panel, border: `1px solid ${T.border}` }}>
          <div style={{ fontSize: 11, color: T.mute, fontWeight: 600 }}>Atendimento</div>
          <div style={{ fontSize: 18, fontWeight: 800, fontFamily: 'var(--mono)', color: ag.pct === 100 ? T.green : T.text }}>{ag.pct.toFixed(0)}%</div>
        </div>
      </div>

      {/* tabela de itens */}
      <div style={{ overflowX: 'auto', margin: '0 -4px' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 620 }}>
          <thead><tr style={{ color: T.mute, textAlign: 'left', fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.4 }}>
            <th style={{ padding: '8px 10px', fontWeight: 700 }}>Item</th>
            <th style={{ padding: '8px 10px', fontWeight: 700, textAlign: 'center' }}>Pedido</th>
            <th style={{ padding: '8px 10px', fontWeight: 700, textAlign: 'center' }}>Faturado</th>
            <th style={{ padding: '8px 10px', fontWeight: 700, minWidth: 120 }}>Atendimento</th>
            <th style={{ padding: '8px 10px', fontWeight: 700, textAlign: 'right' }}>Corte R$</th>
            <th style={{ padding: '8px 10px', fontWeight: 700 }}>Motivo</th>
          </tr></thead>
          <tbody>
            {r.items.map((it, i) => {
              const corte = (it.ped - it.fat) * it.cu;
              const m = it.motivo ? RET_MOTIVO[it.motivo] : null;
              const full = it.fat >= it.ped;
              return (
                <tr key={i} style={{ borderTop: `1px solid ${T.border}`, background: full ? 'transparent' : retA('#FF4D4D', 0.04) }}>
                  <td style={{ padding: '10px', fontWeight: 600, maxWidth: 240, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.n}</td>
                  <td style={{ padding: '10px', textAlign: 'center', fontFamily: 'var(--mono)', color: T.mute }}>{it.ped}</td>
                  <td style={{ padding: '10px', textAlign: 'center', fontFamily: 'var(--mono)', fontWeight: 700, color: it.fat === 0 ? '#FF6B6B' : (full ? T.green : T.text) }}>{it.fat}</td>
                  <td style={{ padding: '10px' }}><RetBar ped={it.ped} fat={it.fat} /></td>
                  <td style={{ padding: '10px', textAlign: 'right', fontFamily: 'var(--mono)', fontWeight: 700, color: corte > 0 ? '#FF6B6B' : T.mute2 }}>{corte > 0 ? 'R$ ' + retBRL(corte) : '—'}</td>
                  <td style={{ padding: '10px' }}>
                    {m
                      ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px', borderRadius: 99, fontSize: 11.5, fontWeight: 700, background: retA(m.color, 0.13), color: m.color }}><Icon name={m.icon} size={12} color={m.color} /> {m.label}</span>
                      : <span style={{ color: T.green, fontSize: 12, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="check" size={13} color={T.green} /> OK</span>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {ag.nCorte > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 12, marginTop: 16, padding: '12px 16px', borderRadius: 12, background: T.panel, border: `1px solid ${T.border}` }}>
          <Icon name="bolt" size={18} color={T.yellow} />
          <div style={{ flex: 1, minWidth: 200, fontSize: 13, color: T.text }}>
            <b style={{ color: '#FF6B6B' }}>R$ {retBRL(ag.vCorte)}</b> ficaram sem faturar. Recote os itens cortados para não ficar com ruptura.
          </div>
          <button onClick={() => onRequote(r)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '10px 18px', borderRadius: 11, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 4px 14px rgba(255,19,48,0.3)' }}>
            <Icon name="refresh" size={15} color="#fff" /> Recotar itens cortados
          </button>
        </div>
      )}
    </Glass>
  );
}

// ── VIEW PRINCIPAL ──────────────────────────────────────────────────────
function RetornoCotacao() {
  const RET = ICret.RETURNS || [];
  const [toast, setToast] = React.useState(null);
  const [filter, setFilter] = React.useState('all'); // all | corte | full

  const totals = React.useMemo(() => {
    let vPed = 0, vFat = 0, nCorte = 0;
    for (const r of RET) { const a = retAgg(r); vPed += a.vPed; vFat += a.vFat; nCorte += a.nCorte; }
    return { vPed, vFat, vCorte: vPed - vFat, nCorte, pct: vPed ? vFat / vPed * 100 : 100 };
  }, []);

  const shown = RET.filter(r => {
    const a = retAgg(r);
    if (filter === 'corte') return a.nCorte > 0;
    if (filter === 'full') return a.nCorte === 0;
    return true;
  });

  const onRequote = (r) => { setToast('Itens cortados de ' + r.id + ' enviados para nova cotação de ' + (ICret.CATEGORIES.find(c=>c.id===r.cat)||{}).name + '.'); setTimeout(() => setToast(null), 3200); };

  return (
    <div>
      <TopbarRet title="Retorno da Cotação" sub="O que o fornecedor faturou × o que foi pedido — cortes e não faturados" />

      {/* KPIs */}
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))' }}>
        <RetKpi label="Total pedido" value={'R$ ' + retBRL(totals.vPed)} sub={RET.length + ' pedidos no período'} color={T.blue} icon="receipt" />
        <RetKpi label="Faturado" value={'R$ ' + retBRL(totals.vFat)} sub={totals.pct.toFixed(0) + '% de atendimento'} color={T.green} icon="check" />
        <RetKpi label="Corte total" value={'R$ ' + retBRL(totals.vCorte)} sub="dinheiro não faturado" color="#FF4D4D" icon="bolt" />
        <RetKpi label="Itens cortados" value={totals.nCorte} sub="precisam de recompra" color={T.yellow} icon="box" />
      </div>

      {/* filtros */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
        {[['all','Todos'],['corte','Com corte'],['full','Faturados 100%']].map(([id, label]) => {
          const on = filter === id;
          return (
            <button key={id} onClick={() => setFilter(id)} style={{ padding: '7px 14px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 600,
              background: on ? retA(T.red, 0.16) : T.panel, color: on ? T.redBright : T.mute, border: `1px solid ${on ? retA(T.red,0.45) : T.border}` }}>{label}</button>
          );
        })}
      </div>

      {shown.map(r => <RetDetail key={r.id} r={r} onRequote={onRequote} />)}
      {shown.length === 0 && <Glass><div style={{ padding: 30, textAlign: 'center', color: T.mute }}>Nenhum pedido neste filtro.</div></Glass>}

      {toast && (
        <div style={{ position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 200, display: 'flex', alignItems: 'center', gap: 10, padding: '13px 20px', borderRadius: 13, background: T.surface, border: `1px solid ${retA(T.green,0.4)}`, boxShadow: '0 18px 50px rgba(0,0,0,0.5)', animation: 'icScaleIn .2s ease both' }}>
          <Icon name="check" size={18} color={T.green} /><span style={{ fontSize: 13.5, fontWeight: 600 }}>{toast}</span>
        </div>
      )}
    </div>
  );
}

window.BuyerRetorno = { RetornoCotacao };
