// Tabela de monitoramento de afiliados (spec 2026-07-13) — mesmo visual da tabela de Produtos:
// avatar colorido + nome, colunas ordenáveis, busca própria, refund com cor de saúde, linha
// clicável → detalhe. Substitui as linhas de mini-KPIs (AffiliateRows, descartado).
const { useState: useStateA, useMemo: useMemoA } = React;

const AMT_PALETTE = ['#FD7119', '#303880', '#1F9D6B', '#8A5BD6', '#2C9CC4', '#E0922B', '#D8453B', '#16315C'];
const _amtLog = (a) => (a.logicall || 0) + (a.logicallRateio || 0);
const _amtTk = (a) => (a.tauk || 0) + (a.taukRateio || 0);
const _amtSb = (a) => (a.salesbound || 0) + (a.sbRateio || 0);
const _amtRate = (a) => (a.directRefunds && a.directRefunds.rate != null) ? a.directRefunds.rate : (a.refundRate || 0);

const AMT_COLS = [
  ['direct', 'Receita Direta'], ['logicall', 'Logicall'], ['tauk', 'Tauk'],
  ['salesbound', 'Salesbound'], ['aov', 'AOV'], ['refundRate', 'Taxa Refund'], ['total', 'Total'],
];

const AffiliateMonitorTable = ({ rows, onSelect }) => {
  const [sortKey, setSortKey] = useStateA('total');
  const [dir, setDir] = useStateA(-1);
  const [q, setQ] = useStateA('');
  const sortBy = (k) => k === sortKey ? setDir(-dir) : (setSortKey(k), setDir(-1));
  const val = (r, k) => k === 'logicall' ? _amtLog(r) : k === 'tauk' ? _amtTk(r) : k === 'salesbound' ? _amtSb(r)
    : k === 'refundRate' ? _amtRate(r) : (r[k] || 0);

  const list = useMemoA(() => {
    let l = (rows || []).filter(a => a.name !== 'Não atribuído');
    const s = q.trim().toLowerCase();
    if (s) l = l.filter(r => r.name.toLowerCase().includes(s) || (r.id || '').toLowerCase().includes(s));
    l = l.slice().sort((a, b) => sortKey === 'name' ? a.name.localeCompare(b.name) * (-dir) : (val(a, sortKey) - val(b, sortKey)) * dir);
    return l;
  }, [rows, q, sortKey, dir]);

  const ind = (k) => sortKey === k ? (dir < 0 ? ' ▾' : ' ▴') : '';
  const th = (k, label, left) => (
    <th key={k} onClick={() => sortBy(k)} style={{ position: left ? 'sticky' : 'static', left: left ? 0 : 'auto', zIndex: left ? 2 : 1, background: '#fff',
      textAlign: left ? 'left' : 'right', font: '600 11px/1 var(--font-sans)', letterSpacing: '.03em', textTransform: 'uppercase',
      color: 'var(--fg-3)', padding: '13px 14px', borderBottom: '1px solid var(--border-2)', whiteSpace: 'nowrap', cursor: 'pointer', userSelect: 'none' }}>
      {label}{ind(k)}</th>
  );
  const td = { padding: '11px 14px', borderBottom: '1px solid var(--border-1)', textAlign: 'right', whiteSpace: 'nowrap', font: 'var(--text-body-sm)', fontFamily: 'var(--font-num)', fontVariantNumeric: 'tabular-nums' };

  return (
    <div style={{ background: '#fff', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 18px', borderBottom: '1px solid var(--border-1)', gap: 16 }}>
        <div>
          <div style={{ font: '600 10px/1 var(--font-sans)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>Detalhe consolidado</div>
          <div style={{ font: 'var(--text-h3)', color: 'var(--fg-1)', marginTop: 4 }}>Performance por Afiliado</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, border: '1px solid var(--border-2)', borderRadius: 'var(--r-md)', padding: '9px 12px', width: 260 }}>
          <Icon name="search" size={15} color="var(--fg-3)" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar afiliado…"
            style={{ border: 0, outline: 0, font: 'var(--text-body-sm)', color: 'var(--fg-1)', flex: 1, background: 'transparent' }} />
        </div>
      </div>
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 900 }}>
          <thead><tr>
            {th('name', 'Afiliado', true)}
            {AMT_COLS.map(([k, l]) => th(k, l))}
          </tr></thead>
          <tbody>
            {list.map((a, i) => {
              const rate = _amtRate(a);
              const rh = refundHealth(rate);
              return (
                <tr key={a.platform + '·' + a.name} onClick={() => onSelect && onSelect(a)}
                  style={{ cursor: 'pointer', background: '#fff' }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--gray-50)'}
                  onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                  <td style={{ position: 'sticky', left: 0, zIndex: 1, background: 'inherit', padding: '10px 14px', whiteSpace: 'nowrap' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                      <div style={{ width: 32, height: 32, borderRadius: 9, background: a.avatar || AMT_PALETTE[i % AMT_PALETTE.length], color: '#fff', font: '800 11px/1 var(--font-sans)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>{initials(a.name)}</div>
                      <div style={{ font: 'var(--text-h4)', color: 'var(--fg-1)', lineHeight: 1.15 }}>{a.name}</div>
                    </div>
                  </td>
                  <td style={{ ...td, font: '700 13px/1 var(--font-num)', color: 'var(--fg-1)' }} className="fenix-num">{USD(a.direct || 0)}</td>
                  <td style={{ ...td, color: 'var(--fg-2)' }} className="fenix-num">{USD(_amtLog(a))}</td>
                  <td style={{ ...td, color: 'var(--fg-2)' }} className="fenix-num">{USD(_amtTk(a))}</td>
                  <td style={{ ...td, color: 'var(--fg-2)' }} className="fenix-num">{USD(_amtSb(a))}</td>
                  <td style={{ ...td, color: 'var(--fg-2)' }} className="fenix-num">{USD(a.aov || 0)}</td>
                  <td style={{ ...td, color: rh.color, fontWeight: 700 }} className="fenix-num">{PCT(rate)}</td>
                  <td style={{ ...td, color: 'var(--fg-1)', fontWeight: 800 }} className="fenix-num">{USD(a.total || 0)}</td>
                </tr>
              );
            })}
            {list.length === 0 && (
              <tr><td colSpan={8} style={{ padding: '34px 22px', textAlign: 'center', font: 'var(--text-body-sm)', color: 'var(--fg-4)' }}>
                {q ? 'Nenhum afiliado casa com a busca.' : 'Sem afiliados no período.'}
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

window.AffiliateMonitorTable = AffiliateMonitorTable;
