// Blocos de refund reutilizáveis (spec 2026-07-06) — usados na página de Produto E de Afiliado.
// Extraídos do ProductDetail. Reusam PDCard/PDHead/PDLineChart (definidos em ProductDetail.jsx)
// e refundHealth/NUM/USDk/PCT (data.jsx) — resolvidos em tempo de render (pós-load). Expostos
// via window para funcionar independentemente da ordem de carregamento dos scripts.

// Separador de seção numerado das páginas de detalhe (spec 2026-07-17-setorizacao).
// n opcional: com n, eyebrow "SETOR N"; sem n, mesmo visual novo sem o eyebrow (a barra e o
// título escuro valem para todos os usos). A numeração é a ordem fixa de leitura da página.
// first: primeiro setor da página — sem régua/respiro superior.
const SectionTitle = ({ n, first, label, sub }) => (
  <div style={{ marginTop: first ? 0 : 18, marginBottom: 6,
                paddingTop: first ? 0 : 22,
                borderTop: first ? 'none' : '1px solid var(--border-1)' }}>
    <div style={{ borderLeft: '3px solid var(--fenix-orange-600, #E5610E)', paddingLeft: 14 }}>
      {n != null && (
        <div style={{ font: '800 11px/1 var(--font-num, var(--font-mono))', letterSpacing: '.14em',
                      textTransform: 'uppercase', color: 'var(--fenix-orange-600, #E5610E)',
                      marginBottom: 6 }}>
          SETOR {n}
        </div>
      )}
      <div style={{ font: '800 22px/1.1 var(--font-sans)', letterSpacing: '-.01em',
                    color: 'var(--fg-1)' }}>{label}</div>
      {sub && <div style={{ font: '500 13px/1.4 var(--font-sans)', color: 'var(--fg-3)',
                            marginTop: 6 }}>{sub}</div>}
    </div>
  </div>
);

// Coorte por janela — vendas & refund. windows = [{key,label,vendas,receita,refundRate}].
// activeKey/onPick(key): clique-para-filtrar (legado, opcional — a tela de afiliado não usa).
// onRefundClick(window): clique só no VALOR de refund (abre drawer com o breakdown da janela).
const CohortWindows = ({ windows, activeKey, onPick, onRefundClick }) => (
  <PDCard style={{ padding: '18px 22px 20px' }}>
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
      <div style={{ font: '700 15px/1 var(--font-sans)', color: 'var(--fg-1)' }}>Coorte por janela — vendas &amp; refund</div>
      {onPick && <span style={{ font: '500 11.5px/1 var(--font-sans)', color: 'var(--fg-3)' }}>clique numa janela para filtrar</span>}
      {onRefundClick && <span style={{ font: '500 11.5px/1 var(--font-sans)', color: 'var(--fg-3)' }}>clique na taxa de refund para detalhar</span>}
    </div>
    <div style={{ display: 'flex', gap: 14 }}>
      {(windows || []).map(w => {
        const on = activeKey === w.key;
        const wh = refundHealth(w.refundRate);
        return (
          <div key={w.key} onClick={onPick ? () => onPick(w.key) : undefined}
            style={{ flex: 1, background: on ? '#FFE7D4' : '#fff', border: '1px solid ' + (on ? 'var(--fenix-orange)' : 'var(--border-1)'), borderRadius: 'var(--r-lg)', padding: '16px 18px', boxShadow: on ? 'none' : 'var(--shadow-sm)', cursor: onPick ? 'pointer' : 'default', minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: on ? 'var(--fenix-orange)' : wh.color, flex: 'none' }} />
              <span style={{ font: '700 10px/1 var(--font-sans)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>{w.label}</span>
            </div>
            {/* Invertido (spec 2026-07-20): a % de refund é o número grande (cor da régua de
                saúde — semáforo visível de longe), vendas viram a linha pequena de baixo. */}
            <div
              onClick={onRefundClick ? (e) => { e.stopPropagation(); onRefundClick(w); } : undefined}
              style={{ font: '800 24px/1 var(--font-num)', letterSpacing: '-.015em', color: wh.color,
                fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
                cursor: onRefundClick ? 'pointer' : 'inherit',
                ...(onRefundClick ? { textDecoration: 'underline', textDecorationColor: 'var(--border-2)', textUnderlineOffset: 4 } : {}) }}
              title={onRefundClick ? 'Ver detalhe do refund desta janela' : undefined}
              className="fenix-num">
              {PCT(w.refundRate)}
            </div>
            <div style={{ font: 'var(--text-caption)', color: 'var(--fg-3)', marginTop: 7 }}>refund da janela</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 10, marginTop: 12, borderTop: '1px solid var(--border-1)' }}>
              <span style={{ font: '500 10.5px/1 var(--font-sans)', color: 'var(--fg-3)' }}>vendas</span>
              <span style={{ font: '700 12.5px/1 var(--font-mono)', color: 'var(--fg-1)', fontVariantNumeric: 'tabular-nums' }} className="fenix-num">
                {NUM(w.vendas)} · {USDk(w.receita)}
              </span>
            </div>
          </div>
        );
      })}
    </div>
  </PDCard>
);

// Taxa de refund ao longo do tempo — derivada de timeseries = [{sales, refunds}].
const RefundRateOverTime = ({ timeseries, style }) => {
  const ts = timeseries || [];
  const rateSeries = ts.map(t => { const d = (t.sales || 0) + (t.refunds || 0); return d ? (t.refunds || 0) / d * 100 : 0; });
  return (
    <PDCard style={{ flex: 1, minHeight: 260, ...style }}>
      <PDHead title="Taxa de refund ao longo do tempo"
        sub="Como a taxa de estorno evoluiu no período" />
      <PDLineChart n={rateSeries.length}
        series={[{ color: 'var(--fenix-orange)', fill: 'rgba(253,113,25,.10)', values: rateSeries }]}
        xLabels={[]}
        caption={i => `${PCT(rateSeries[i])} de refund`} />
    </PDCard>
  );
};

// Maturação do refund — maturation = { points:[{rate}], halfLifeDays }.
const RefundMaturation = ({ maturation, style }) => {
  const mat = (maturation && maturation.points || []).map(p => p.rate);
  const hl = maturation ? maturation.halfLifeDays : null;
  return (
    <PDCard style={{ flex: 1, minHeight: 260, ...style }}>
      <PDHead title="Maturação do refund"
        sub={`Quando o estorno acontece — ~metade até o dia ${hl != null ? hl : '—'}`} />
      <PDLineChart n={mat.length}
        series={[{ color: 'var(--negative)', fill: 'rgba(216,69,59,.09)', values: mat }]}
        xLabels={['D0', 'D14', 'D45']}
        caption={i => `D${i}: ${PCT(mat[i])} acumulado`} />
    </PDCard>
  );
};

Object.assign(window, { SectionTitle, CohortWindows, RefundRateOverTime, RefundMaturation });
