// Visão Geral (spec 2026-07-03) — página executiva do menu lateral.
// Corpo: ranking + composições + evolução (componentes existentes) + fileira nova:
// Detalhamento por Funil (FE/BE + receita + AOV) e Top Produtos (com nº de afiliados).
// Dados de funil/top produtos vêm do /products/overview (famílias = funil completo).

// Barras horizontais FE/BE empilhadas por funil (família), com receita e AOV à direita.
const FunnelBreakdownChart = ({ products, productFilter, onOpen }) => {
  let fams = ((products && products.rows) || []).filter(p => p.mapped);
  if (productFilter && productFilter !== 'todos') fams = fams.filter(p => p.key === productFilter);
  fams = fams.slice(0, 6);                                   // overview já vem ordenada por receita
  const max = Math.max(...fams.map(p => p.orders), 1);
  return (
    <div style={ov.panel}>
      <div style={ov.panelHead}>
        <div>
          <div style={ov.panelEye}>Funis</div>
          <div style={ov.panelTitle}>Detalhamento por Funil</div>
        </div>
        <div style={ov.legend}>
          <span><span style={{ ...ov.legSw, background: 'var(--fenix-navy)' }} />FE</span>
          <span><span style={{ ...ov.legSw, background: 'var(--fenix-orange)' }} />BE</span>
        </div>
      </div>
      {fams.length === 0 ? (
        <div style={ov.emptyMsg}>Sem funis no período.</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {fams.map(p => {
            const fe = p.fe.orders, be = p.be.orders;
            return (
              <button key={p.key} style={ov.funRow} onClick={() => onOpen && onOpen(p.key)}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--gray-50)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <span style={ov.funName}>{p.name}</span>
                <div style={ov.funTrack} title={`FE ${NUM(fe)} · BE ${NUM(be)} pedidos`}>
                  <div style={{ ...ov.funSeg, width: (fe / max * 100) + '%', background: 'var(--fenix-navy)' }} />
                  <div style={{ ...ov.funSeg, width: (be / max * 100) + '%', background: 'var(--fenix-orange)' }} />
                </div>
                <span style={ov.funOrders} className="fenix-num">{NUM(fe)}<span style={ov.funSep}>/</span>{NUM(be)}</span>
                <span style={ov.funRev} className="fenix-num">{USDk(p.gross)}</span>
                <span style={ov.funAov} className="fenix-num" title="AOV por checkout = (FE+BE) ÷ ordens FE">{USD(p.aov)}</span>
              </button>
            );
          })}
          <div style={ov.funHeadRow}>
            <span style={ov.funName} />
            <div style={{ flex: 1 }} />
            <span style={{ ...ov.funOrders, ...ov.funColLab }}>FE/BE</span>
            <span style={{ ...ov.funRev, ...ov.funColLab }}>Receita</span>
            <span style={{ ...ov.funAov, ...ov.funColLab }}>AOV</span>
          </div>
        </div>
      )}
    </div>
  );
};

// Top 5 produtos: Receita · Pedidos · Refund % · Afiliados rodando. Linha clicável → página do produto.
const TopProductsTable = ({ products, productFilter, onOpen }) => {
  let fams = ((products && products.rows) || []).filter(p => p.mapped);
  if (productFilter && productFilter !== 'todos') fams = fams.filter(p => p.key === productFilter);
  fams = fams.slice(0, 5);
  return (
    <div style={{ ...ov.panel, height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={ov.panelHead}>
        <div>
          <div style={ov.panelEye}>Ranking</div>
          <div style={ov.panelTitle}>Top Produtos</div>
        </div>
      </div>
      {fams.length === 0 ? (
        <div style={ov.emptyMsg}>Sem produtos no período.</div>
      ) : (
        <div style={{ flex: 1 }}>
        <table style={ov.tbl}>
          <thead>
            <tr>
              <th style={{ ...ov.th, textAlign: 'left' }}>Produto</th>
              <th style={ov.th}>Receita</th>
              <th style={ov.th}>Pedidos</th>
              <th style={ov.th}>Refund</th>
              <th style={ov.th} title="Afiliados com venda do produto no período">Afiliados</th>
            </tr>
          </thead>
          <tbody>
            {fams.map(p => {
              const rh = refundHealth(p.refundRate);
              return (
                <tr key={p.key} style={{ cursor: 'pointer' }} onClick={() => onOpen && onOpen(p.key)}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--gray-50)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ ...ov.td, textAlign: 'left', fontWeight: 700 }}>{p.name}</td>
                  <td style={ov.td} className="fenix-num">{USDk(p.gross)}</td>
                  <td style={ov.td} className="fenix-num">{NUM(p.orders)}</td>
                  <td style={{ ...ov.td, color: rh.color, fontWeight: 700 }} className="fenix-num">{PCT(p.refundRate)}</td>
                  <td style={ov.td} className="fenix-num">{NUM(p.nAffiliates != null ? p.nAffiliates : 0)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
      )}
    </div>
  );
};

// Página Visão Geral: fileiras existentes + a fileira nova de funil/top produtos.
const OverviewView = ({ rows, sourceSeg, platSeg, trend, t, period, products, productFilter,
                        onSelectAffiliate, onOpenProduct }) => (
  <>
    {/* Série temporal full-width no topo (spec 2026-07-13) */}
    <div className="section-gap">
      <RevenueTrend trend={trend} mode={t.trendMode} period={period} />
    </div>
    {/* Rankings pareados: Top 10 afiliados | Top produtos (spec 2026-07-20) */}
    <div className="cpa-aov section-gap" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'stretch' }}>
      <TopAffiliates rows={rows} onSelect={onSelectAffiliate} />
      <TopProductsTable products={products} productFilter={productFilter} onOpen={onOpenProduct} />
    </div>
    {/* Composições lado a lado: Fonte | Plataforma */}
    <div className="cpa-aov section-gap" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'start' }}>
      <CleanDonut eyebrow="Composição" title="Receita por Fonte" segments={sourceSeg} />
      <CleanDonut eyebrow="Composição" title="Receita por Plataforma" segments={platSeg} />
    </div>
    {/* Detalhamento por Funil — largura cheia no fim */}
    <div className="section-gap">
      <FunnelBreakdownChart products={products} productFilter={productFilter} onOpen={onOpenProduct} />
    </div>
  </>
);

const ov = {
  panel: { background: '#fff', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', padding: '20px 22px', boxShadow: 'var(--shadow-sm)' },
  panelHead: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14, gap: 16 },
  panelEye: { font: 'var(--text-label)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)' },
  panelTitle: { font: 'var(--text-h3)', color: 'var(--fg-1)', marginTop: 4 },
  legend: { display: 'flex', gap: 12, font: '500 11px/1 var(--font-sans)', color: 'var(--fg-3)', alignItems: 'center' },
  legSw: { display: 'inline-block', width: 10, height: 10, borderRadius: 3, marginRight: 5, verticalAlign: '-1px' },
  emptyMsg: { font: '500 12.5px/1.4 var(--font-sans)', color: 'var(--fg-4)', padding: '8px 0 4px' },

  funRow: { display: 'flex', alignItems: 'center', gap: 10, width: '100%', border: 0, background: 'transparent', borderRadius: 'var(--r-sm)', padding: '7px 8px', cursor: 'pointer', transition: 'background .12s', textAlign: 'left' },
  funHeadRow: { display: 'flex', alignItems: 'center', gap: 10, padding: '2px 8px 0' },
  funName: { font: '700 12.5px/1 var(--font-mono)', color: 'var(--fg-1)', width: 104, flex: 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
  funTrack: { flex: 1, height: 14, background: 'var(--gray-100)', borderRadius: 'var(--r-pill)', overflow: 'hidden', display: 'flex' },
  funSeg: { height: '100%', transition: 'width .5s var(--ease)' },
  funOrders: { font: '600 11.5px/1 var(--font-mono)', color: 'var(--fg-2)', width: 86, textAlign: 'right', flex: 'none', whiteSpace: 'nowrap' },
  funSep: { color: 'var(--fg-4)', margin: '0 2px' },
  funRev: { font: '700 12px/1 var(--font-mono)', color: 'var(--fg-1)', width: 64, textAlign: 'right', flex: 'none' },
  funAov: { font: '600 11.5px/1 var(--font-mono)', color: 'var(--fg-3)', width: 56, textAlign: 'right', flex: 'none' },
  funColLab: { font: '600 9.5px/1 var(--font-sans)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-4)' },

  tbl: { width: '100%', borderCollapse: 'collapse' },
  th: { font: '600 10px/1 var(--font-sans)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-4)', textAlign: 'right', padding: '6px 8px', borderBottom: '1px solid var(--border-1)' },
  td: { font: '600 12.5px/1 var(--font-num)', color: 'var(--fg-1)', textAlign: 'right', padding: '11px 8px', borderBottom: '1px solid var(--border-1)', fontVariantNumeric: 'tabular-nums' },
};

Object.assign(window, { OverviewView, FunnelBreakdownChart, TopProductsTable });
