// Módulo RELATÓRIOS — Vendas, RFM (clientes), Lives

const RelatoriosPage = () => {
  const [tab, setTab] = React.useState("vendas");
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <span className="eyebrow"><span className="play"/>Inteligência de negócio</span>
          <h1 style={{marginTop:10}}>Relatórios</h1>
          <p className="lead">Vendas · produtos · clientes · segmentação RFM · comparativo de lives.</p>
        </div>
        <div className="actions">
          <select className="input"><option>1–19 Maio/26</option><option>Abril/26</option><option>1º trim 2026</option></select>
          <button className="btn ghost"><Ic name="download" size={13}/> Exportar PDF</button>
          <button className="btn ghost"><Ic name="download" size={13}/> Excel</button>
        </div>
      </div>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "vendas", label: "Vendas" },
        { id: "rfm", label: "Clientes · RFM" },
        { id: "lives", label: "Lives" },
        { id: "produtos", label: "Produtos" },
        { id: "geografico", label: "Geográfico" },
        { id: "trocas", label: "Trocas/devoluções" },
      ]}/>

      {tab === "vendas" && <RelVendas/>}
      {tab === "rfm" && <RelRfm/>}
      {tab === "lives" && <RelLives/>}
      {tab === "produtos" && <RelProdutos/>}
      {(tab === "geografico" || tab === "trocas") && <Empty icon="map" title="Disponível no produto final"/>}
    </div>
  );
};

const RelVendas = () => (
  <div className="stack">
    <div className="stat-grid cols-4">
      <Stat glow="green" label="Faturamento · período" value={brlNoCents(142840)} delta={18.2}/>
      <Stat label="Pedidos" value="892" delta={22.4}/>
      <Stat label="Ticket médio" value={brl(160.18)} delta={-3.4}/>
      <Stat label="Itens vendidos" value="1.418" delta={19.8}/>
    </div>

    <div className="card">
      <div className="card-head"><h3>Evolução diária · maio 26 vs. abril 26</h3></div>
      <LineChart data={VENDAS_POR_DIA}/>
    </div>

    <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
      <div className="card">
        <div className="card-head"><h3>Por canal</h3><span className="meta">14 dias</span></div>
        <BarH rows={[
          { label: "Live", value: 82847, display: brlNoCents(82847), color: 'var(--accent)' },
          { label: "Loja física", value: 31425, display: brlNoCents(31425), color: 'var(--cyan)' },
          { label: "Site", value: 19998, display: brlNoCents(19998), color: 'var(--green)' },
          { label: "WhatsApp", value: 8570, display: brlNoCents(8570), color: 'var(--purple)' },
        ]}/>
      </div>

      <div className="card">
        <div className="card-head"><h3>Por forma de pagamento</h3></div>
        <BarH rows={[
          { label: "Pix", value: 64280, display: "45%", color: 'var(--accent)' },
          { label: "Cartão crédito", value: 41840, display: "29%", color: 'var(--cyan)' },
          { label: "Cartão débito", value: 18420, display: "13%", color: 'var(--green)' },
          { label: "Crediário", value: 12780, display: "9%", color: 'var(--purple)' },
          { label: "Dinheiro", value: 5520, display: "4%", color: 'var(--text-3)' },
        ]}/>
      </div>
    </div>

    <div className="card">
      <div className="card-head"><h3>Vendas por responsável</h3><span className="meta">comissões aplicadas</span></div>
      <table className="tbl">
        <thead><tr><th>Responsável</th><th>Pedidos</th><th style={{textAlign:'right'}}>Faturamento</th><th style={{textAlign:'right'}}>Ticket médio</th><th style={{textAlign:'right'}}>Meta</th><th>Atingido</th><th style={{textAlign:'right'}}>Comissão</th></tr></thead>
        <tbody>
          <tr><td className="row gap-8"><ClientAvatar name="Letícia Borges"/><span className="strong">Letícia Borges</span><Badge kind="green">Live</Badge></td><td className="num">487</td><td className="num strong">{brl(74820.30)}</td><td className="num">{brl(153.63)}</td><td className="num t-3">{brlNoCents(60000)}</td><td><Badge kind="green" dot>124%</Badge></td><td className="num t-green">{brl(2244.60)}</td></tr>
          <tr><td className="row gap-8"><ClientAvatar name="Bruna Carvalho"/><span className="strong">Bruna Carvalho</span><Badge kind="cyan">PDV</Badge></td><td className="num">214</td><td className="num strong">{brl(31425.80)}</td><td className="num">{brl(146.85)}</td><td className="num t-3">{brlNoCents(30000)}</td><td><Badge kind="green" dot>104%</Badge></td><td className="num t-green">{brl(942.77)}</td></tr>
          <tr><td className="row gap-8"><ClientAvatar name="Janaína Ferreira"/><span className="strong">Janaína Ferreira</span><Badge kind="purple">Site/WPP</Badge></td><td className="num">191</td><td className="num strong">{brl(36594.20)}</td><td className="num">{brl(191.59)}</td><td className="num t-3">{brlNoCents(45000)}</td><td><Badge kind="amber" dot>81%</Badge></td><td className="num">{brl(731.88)}</td></tr>
        </tbody>
      </table>
    </div>
  </div>
);

const RelRfm = () => (
  <div className="stack">
    <div className="stat-grid cols-3">
      <Stat glow="green" label="Recência média" value="18 dias" hint="Champions + Leais"/>
      <Stat label="Frequência média" value="4.2 pedidos" hint="por cliente · 90d"/>
      <Stat label="Valor médio (LTV)" value={brl(620.40)}/>
    </div>

    <div className="card">
      <div className="card-head"><h3>Segmentação RFM · 1.304 clientes</h3>
        <div className="row gap-6">
          <button className="btn sm ghost"><Ic name="download" size={11}/></button>
          <button className="btn sm primary"><Ic name="megaphone" size={11}/> Enviar campanha</button>
        </div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(6, 1fr)', gap:10}}>
        {RFM_SEGMENTOS.map((s, i) => (
          <div key={i} className="card tight" style={{padding:14, position:'relative', overflow:'hidden', cursor:'pointer'}}>
            <div style={{position:'absolute', top:0, left:0, width:'4px', height:'100%', background: s.cor}}/>
            <div className="t-mono-label" style={{fontSize:9.5, letterSpacing:'0.14em', color: s.cor, marginBottom:4}}>{s.nome.toUpperCase()}</div>
            <div style={{fontSize:24, fontWeight:500, letterSpacing:'-0.02em', fontFamily:'var(--mono)'}}>{numFmt(s.clientes)}</div>
            <div className="t-3" style={{fontSize:11, marginTop:4}}>{s.desc}</div>
            <div className="t-2 mt-12" style={{fontSize:12, fontWeight:500}}>{brlNoCents(s.valor)} <span className="t-3" style={{fontSize:10.5, fontWeight:400}}>· LTV</span></div>
          </div>
        ))}
      </div>
    </div>

    <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
      <div className="card">
        <div className="card-head"><h3>Champions · 142 · top 10</h3><a className="t-mono-label" style={{cursor:'pointer', color:'var(--text-2)'}}>Ver todos</a></div>
        <table className="tbl">
          <thead><tr><th>Cliente</th><th>Pedidos</th><th style={{textAlign:'right'}}>LTV</th><th>Última</th></tr></thead>
          <tbody>
            {CLIENTES.filter(c => c.rfm === "Champions").concat(CLIENTES.slice(0,4)).slice(0,7).map((c, i) => (
              <tr key={i}>
                <td className="row gap-8"><ClientAvatar name={c.nome}/><span className="strong">{c.nome}</span></td>
                <td className="num">{c.pedidos}</td>
                <td className="num strong">{brl(c.totalGasto)}</td>
                <td className="mono t-3">{c.ultimaCompra}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="card">
        <div className="card-head"><h3>Em risco · 204 clientes</h3><button className="btn sm primary"><Ic name="whatsapp" size={11}/> Reengajar todos</button></div>
        <p className="t-3" style={{fontSize:12, marginTop:0}}>Clientes leais que não compram há 60-90 dias. Receita potencial perdida: <b className="t-2">{brl(64280)}</b></p>
        <BarH rows={[
          { label: "60-90 dias", value: 84, display: '84 cli', color: 'var(--pink)' },
          { label: "90-120 dias", value: 76, display: '76 cli', color: 'var(--pink)' },
          { label: "120-180 dias", value: 44, display: '44 cli', color: 'var(--pink)' },
        ]} max={120}/>
        <div className="t-mono-label mt-16 mb-8">Ação sugerida</div>
        <div style={{padding:10, background:'var(--bg-3)', border:'1px solid var(--line)', borderRadius:6, fontSize:12}} className="t-2">
          💡 Campanha "Voltamos pra você": cupom 15% + frete grátis acima R$ 200. ROI estimado: <b className="t-green">8.2×</b>
        </div>
      </div>
    </div>
  </div>
);

const RelLives = () => (
  <div className="stack">
    <div className="stat-grid cols-4">
      <Stat glow="green" label="Faturamento · lives" value={brlNoCents(82847)} delta={28.4} hint="58% da receita"/>
      <Stat label="Lives realizadas" value="5" hint="período 30d"/>
      <Stat label="Ticket médio · lives" value={brl(166.51)} delta={4.2}/>
      <Stat label="% pedidos pagos" value="84%" delta={6.0}/>
    </div>

    <div className="card">
      <div className="card-head"><h3>Comparativo · 5 últimas lives</h3></div>
      <div style={{display:'flex', alignItems:'flex-end', gap:18, height:200, padding:'0 20px'}}>
        {LIVES_HISTORICO.slice().reverse().map((l, i) => {
          const max = Math.max(...LIVES_HISTORICO.map(x => x.faturamento));
          const h = (l.faturamento / max) * 100;
          const isMax = l.faturamento === max;
          return (
            <div key={i} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:8}}>
              <div className="mono t-2" style={{fontSize:11, fontWeight:600}}>{brlNoCents(l.faturamento)}</div>
              <div style={{width:'100%', height: h + '%', minHeight:8, background: isMax ? 'var(--green)' : 'var(--accent)', borderRadius:'4px 4px 0 0', opacity: isMax ? 1 : 0.85, position:'relative'}}>
                {isMax && <Badge kind="green" style={{position:'absolute', top:-22, left:'50%', transform:'translateX(-50%)'}}>melhor</Badge>}
              </div>
              <div className="t-mono-label" style={{fontSize:9.5, letterSpacing:'0.14em'}}>#{43 + i}</div>
              <div className="t-3" style={{fontSize:10.5}}>{l.data}</div>
            </div>
          );
        })}
      </div>
    </div>

    <div className="card">
      <div className="card-head"><h3>Histórico de lives</h3><button className="btn sm ghost"><Ic name="download" size={11}/></button></div>
      <table className="tbl">
        <thead>
          <tr><th>Live</th><th>Data</th><th>Pedidos</th><th>Clientes únicos</th><th style={{textAlign:'right'}}>Faturamento</th><th style={{textAlign:'right'}}>Ticket médio</th><th>% pagos</th><th></th></tr>
        </thead>
        <tbody>
          {LIVES_HISTORICO.map((l, i) => (
            <tr key={i}>
              <td className="strong">{l.nome}</td>
              <td className="mono">{l.data}</td>
              <td className="num">{l.pedidos}</td>
              <td className="num">{l.clientes}</td>
              <td className="num strong">{brl(l.faturamento)}</td>
              <td className="num">{brl(l.ticket)}</td>
              <td><Badge kind={l.pagos >= 85 ? "green" : l.pagos >= 80 ? "cyan" : "amber"} dot>{l.pagos}%</Badge></td>
              <td className="row-action"><div className="menu-dot">⋯</div></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

const RelProdutos = () => (
  <div className="stack">
    <div className="stat-grid cols-3">
      <Stat label="Produtos vendidos no período" value="284 / 296" hint="96% do catálogo"/>
      <Stat label="Sem venda · 30d" value="12" hint="candidatos a queima"/>
      <Stat glow="green" label="Margem bruta média" value="58.4%"/>
    </div>

    <div className="card">
      <div className="card-head"><h3>Top 10 produtos · período</h3></div>
      <table className="tbl">
        <thead><tr><th>#</th><th>Produto</th><th>Marca</th><th>Categoria</th><th>Qtd</th><th style={{textAlign:'right'}}>Receita</th><th>Margem</th></tr></thead>
        <tbody>
          {PRODUTOS.slice().sort((a,b) => b.vendas30d - a.vendas30d).map((p, i) => (
            <tr key={p.id}>
              <td className="mono t-3" style={{width:30}}>{i+1}</td>
              <td className="row gap-8"><div className="product-thumb">{p.foto}</div><div><div className="strong">{p.nome}</div><div className="t-3 mono" style={{fontSize:10.5}}>{p.id}</div></div></td>
              <td className="t-3">{p.marca}</td>
              <td className="t-3">{p.categoria}</td>
              <td className="num">{p.vendas30d}</td>
              <td className="num strong">{brl(p.preco * p.vendas30d * 0.7)}</td>
              <td><Badge kind="green" dot>{((p.preco / p.custo - 1) * 60).toFixed(0)}%</Badge></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

Object.assign(window, { RelatoriosPage });
