/* global React, Card, Badge, Button, Avatar, Icon, ICONS, sb */
const { useState, useEffect } = React;

const CHART_COLORS = ['#1D39C4','#36CFC9','#FA541C','#7C3AED','#22C55E','#FADB14'];
const MONTHS_PT    = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];

function fmtBRL(n) {
  if (!n || n === 0) return 'R$ 0';
  return 'R$ ' + Math.abs(n).toLocaleString('pt-BR', { minimumFractionDigits:0, maximumFractionDigits:0 });
}

function buildChart(finances, from, to) {
  const fromD = new Date(from), toD = new Date(to);
  const diffDays = Math.round((toD - fromD) / 864e5);
  const buckets = [], labels = [];
  if (diffDays <= 45) {
    const n = Math.max(1, Math.ceil(diffDays / 7));
    for (let w = 0; w < n; w++) {
      const s = new Date(fromD); s.setDate(s.getDate() + w * 7);
      const e = new Date(fromD); e.setDate(e.getDate() + (w + 1) * 7 - 1);
      labels.push(`S${w + 1}`);
      buckets.push(finances.filter(f => f.type === 'receita' && new Date(f.date) >= s && new Date(f.date) <= e)
        .reduce((s, f) => s + parseFloat(f.amount || 0), 0));
    }
  } else {
    let cur = new Date(fromD.getFullYear(), fromD.getMonth(), 1);
    const end = new Date(toD.getFullYear(), toD.getMonth() + 1, 0);
    while (cur <= end) {
      const y = cur.getFullYear(), m = cur.getMonth();
      labels.push(MONTHS_PT[m]);
      buckets.push(finances.filter(f => {
        const fd = new Date(f.date);
        return f.type === 'receita' && fd.getFullYear() === y && fd.getMonth() === m;
      }).reduce((s, f) => s + parseFloat(f.amount || 0), 0));
      cur = new Date(y, m + 1, 1);
    }
  }
  const badge = diffDays <= 35 ? 'Últimos 30 dias' : diffDays <= 95 ? 'Trimestre' : `${labels.length} meses`;
  return { data: buckets, labels, badge };
}

// ─── KPI Card ─────────────────────────────────────────────────────────────────
function KpiCard({ label, value, sub, tone, color }) {
  return (
    <Card>
      <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)' }}>{label}</div>
      <div style={{ fontFamily:'var(--font-display)', fontSize:30, fontWeight:700, letterSpacing:'-0.03em', marginTop:8, color: color || 'var(--fg-primary)' }}>{value}</div>
      <div style={{ marginTop:10 }}><Badge tone={tone||'neutral'} dot={false}>{sub}</Badge></div>
    </Card>
  );
}

// ─── Mini bar chart ───────────────────────────────────────────────────────────
function MiniBar({ data, labels, color='var(--primary)', height=80 }) {
  const max = Math.max(...data) || 1;
  return (
    <div style={{ display:'grid', gridTemplateColumns:`repeat(${data.length},1fr)`, gap:4, alignItems:'end', height }}>
      {data.map((v,i)=>(
        <div key={i} style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:4, height:'100%' }}>
          <div style={{ flex:1, width:'100%', display:'flex', alignItems:'flex-end' }}>
            <div style={{ width:'100%', height:(v/max*100)+'%', background:`linear-gradient(180deg,${color},${color}88)`, borderRadius:'4px 4px 0 0', minHeight:v>0?3:0 }}/>
          </div>
          {labels && <span style={{ fontSize:9, color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>{labels[i]}</span>}
        </div>
      ))}
    </div>
  );
}

// ─── Status badge (projects) ──────────────────────────────────────────────────
function ProjStatusBadge({ status }) {
  const map = { concluido:['success','Concluído'], andamento:['brand','Em andamento'], ativo:['brand','Ativo'], planejamento:['neutral','Planejamento'], pausado:['warning','Pausado'], atrasado:['danger','Atrasado'] };
  const [tone,label] = map[status] || ['neutral', status || '—'];
  return <Badge tone={tone} dot={false}>{label}</Badge>;
}

// ─── Export PDF Modal ─────────────────────────────────────────────────────────
function ExportarPDFModal({ onClose, d, periodoLabel }) {
  const [view, setView] = useState('choose');
  const today = new Date().toLocaleDateString('pt-BR', { day:'2-digit', month:'long', year:'numeric' });
  const maxC = Math.max(1, ...d.clientes.map(c => c.raw));

  function handleDownload() {
    window.__toast?.('PDF gerado e baixado com sucesso!', { tone:'success' });
    onClose();
  }

  return (
    <div onClick={view==='choose'?onClose:undefined} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.65)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24, overflow:'auto' }}>
      {view === 'choose' ? (
        <div onClick={e=>e.stopPropagation()} style={{ width:'min(440px,100%)', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>
          <div style={{ padding:'20px 24px 18px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <div>
              <h2 style={{ margin:0, fontSize:17, fontWeight:700 }}>Exportar Relatório</h2>
              <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:3 }}>{periodoLabel} · {today}</div>
            </div>
            <button onClick={onClose} style={{ background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', width:32, height:32, borderRadius:8, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon d={ICONS.x} size={16}/></button>
          </div>
          <div style={{ padding:24, display:'flex', flexDirection:'column', gap:12 }}>
            <div style={{ fontSize:13, color:'var(--fg-muted)', marginBottom:4 }}>Como deseja acessar o relatório?</div>
            {[
              { label:'Visualizar online', sub:'Veja o relatório completo aqui mesmo, sem baixar nenhum arquivo', icon:'eye', action:()=>setView('preview') },
              { label:'Baixar PDF', sub:'Salve o arquivo em formato PDF no seu dispositivo', icon:'download', action:handleDownload },
            ].map(btn => (
              <button key={btn.label} onClick={btn.action} style={{ padding:'16px 20px', borderRadius:12, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', cursor:'pointer', textAlign:'left', display:'flex', alignItems:'center', gap:14 }}
                onMouseEnter={e=>{ e.currentTarget.style.borderColor='var(--primary)'; e.currentTarget.style.background='var(--primary-soft)'; }}
                onMouseLeave={e=>{ e.currentTarget.style.borderColor='var(--border-subtle)'; e.currentTarget.style.background='var(--bg-elevated)'; }}>
                <div style={{ width:40, height:40, borderRadius:10, background:'var(--primary-soft)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--primary)', flexShrink:0 }}><Icon d={ICONS[btn.icon]} size={20}/></div>
                <div><div style={{ fontSize:14, fontWeight:700, marginBottom:2 }}>{btn.label}</div><div style={{ fontSize:12, color:'var(--fg-muted)' }}>{btn.sub}</div></div>
              </button>
            ))}
          </div>
        </div>
      ) : (
        <div onClick={e=>e.stopPropagation()} style={{ width:'min(760px,100%)', maxHeight:'90vh', display:'flex', flexDirection:'column', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>
          <div style={{ padding:'12px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:10, background:'var(--bg-surface)', flexShrink:0 }}>
            <span style={{ flex:1, fontSize:13, fontWeight:700, color:'var(--fg-muted)' }}>Pré-visualização · {periodoLabel}</span>
            <button onClick={handleDownload} style={{ padding:'7px 16px', borderRadius:8, background:'var(--primary)', border:'none', color:'#fff', cursor:'pointer', fontSize:12, fontWeight:700, fontFamily:'inherit', display:'flex', alignItems:'center', gap:6 }}><Icon d={ICONS.download} size={13}/> Baixar PDF</button>
            <button onClick={onClose} style={{ background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', width:30, height:30, borderRadius:7, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon d={ICONS.x} size={14}/></button>
          </div>
          <div style={{ flex:1, overflow:'auto', padding:24, background:'var(--bg-elevated)' }}>
            <div style={{ maxWidth:680, margin:'0 auto', background:'#fff', borderRadius:8, overflow:'hidden', boxShadow:'0 4px 24px rgba(0,0,0,0.15)' }}>
              <div style={{ background:'linear-gradient(135deg,#1D39C4,#36CFC9)', padding:'28px 32px 20px' }}>
                <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'rgba(255,255,255,0.7)', marginBottom:6 }}>Relatório de Performance</div>
                <div style={{ fontSize:22, fontWeight:800, color:'#fff', lineHeight:1.2 }}>inBrivvo</div>
                <div style={{ fontSize:13, color:'rgba(255,255,255,0.75)', marginTop:6 }}>{periodoLabel} · Gerado em {today}</div>
              </div>
              <div style={{ padding:'24px 32px 0', display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
                {d.kpis.map((k,i)=>(
                  <div key={i} style={{ padding:'12px 14px', borderRadius:8, background:'#f8f9fc', border:'1px solid #e8eaf0' }}>
                    <div style={{ fontSize:9, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'#888', marginBottom:6 }}>{k.l}</div>
                    <div style={{ fontSize:20, fontWeight:800, color:'#1a1a2e', letterSpacing:'-0.02em' }}>{k.v}</div>
                    <div style={{ fontSize:10, color: k.tone==='success'?'#22C55E':k.tone==='warning'?'#FA8C16':'#6b7280', marginTop:4, fontWeight:600 }}>{k.d}</div>
                  </div>
                ))}
              </div>
              {d.clientes.length > 0 && (
                <div style={{ padding:'20px 32px 0' }}>
                  <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'#888', marginBottom:14 }}>Receita por cliente</div>
                  {d.clientes.map((c,i)=>(
                    <div key={i} style={{ display:'flex', alignItems:'center', gap:12, marginBottom:10 }}>
                      <div style={{ fontSize:12, fontWeight:600, width:130, color:'#1a1a2e', flexShrink:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{c.n}</div>
                      <div style={{ flex:1, height:8, background:'#f0f0f0', borderRadius:999, overflow:'hidden' }}>
                        <div style={{ width:`${(c.raw/maxC)*100}%`, height:'100%', background:c.c, borderRadius:999 }}/>
                      </div>
                      <div style={{ fontSize:11, fontFamily:'monospace', color:'#666', minWidth:70, textAlign:'right' }}>{c.v}</div>
                    </div>
                  ))}
                </div>
              )}
              <div style={{ padding:'20px 32px 28px' }}>
                <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'#888', marginBottom:10 }}>Projetos</div>
                <table style={{ width:'100%', borderCollapse:'collapse' }}>
                  <thead><tr style={{ background:'#f8f9fc' }}>{['Projeto','Receita','Orçamento','Margem','Status'].map(h=><th key={h} style={{ textAlign:'left', padding:'8px 10px', fontSize:9, fontWeight:700, color:'#888', textTransform:'uppercase', letterSpacing:'0.06em', border:'1px solid #e8eaf0' }}>{h}</th>)}</tr></thead>
                  <tbody>{d.projetos.map((p,i)=>(
                    <tr key={i}>
                      <td style={{ padding:'9px 10px', fontSize:12, fontWeight:600, color:'#1a1a2e', border:'1px solid #e8eaf0' }}>{p.t}</td>
                      <td style={{ padding:'9px 10px', fontSize:12, fontFamily:'monospace', color:'#333', border:'1px solid #e8eaf0' }}>{fmtBRL(p.rev)}</td>
                      <td style={{ padding:'9px 10px', fontSize:12, fontFamily:'monospace', color:'#888', border:'1px solid #e8eaf0' }}>{p.bud > 0 ? fmtBRL(p.bud) : '—'}</td>
                      <td style={{ padding:'9px 10px', fontSize:12, fontFamily:'monospace', fontWeight:600, color:p.m<0?'#EF4444':'#1a1a2e', border:'1px solid #e8eaf0' }}>{fmtBRL(p.m)}</td>
                      <td style={{ padding:'9px 10px', border:'1px solid #e8eaf0' }}>
                        <span style={{ fontSize:10, fontWeight:700, padding:'2px 8px', borderRadius:999, background:p.tone==='success'?'#dcfce7':p.tone==='warning'?'#fef3c7':p.tone==='danger'?'#fee2e2':'#f3f4f6', color:p.tone==='success'?'#16a34a':p.tone==='warning'?'#92400e':p.tone==='danger'?'#b91c1c':'#374151' }}>
                          {p.tone==='success'?'Saudável':p.tone==='warning'?'Atenção':p.tone==='danger'?'Prejuízo':'Neutro'}
                        </span>
                      </td>
                    </tr>
                  ))}</tbody>
                </table>
              </div>
              <div style={{ padding:'14px 32px', background:'#f8f9fc', borderTop:'1px solid #e8eaf0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                <span style={{ fontSize:10, color:'#aaa' }}>Gerado por inBrivvo · {today}</span>
                <span style={{ fontSize:10, color:'#aaa' }}>Confidencial</span>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── IA Análise Modal ─────────────────────────────────────────────────────────
function IaAnaliseModal({ onClose, d, periodoLabel }) {
  const [ready, setReady] = useState(false);
  useEffect(() => { const t = setTimeout(() => setReady(true), 1600); return () => clearTimeout(t); }, []);

  const melhorCliente = d.clientes.length ? d.clientes.reduce((a,b)=>a.raw>b.raw?a:b) : null;
  const piorProjeto   = d.projetos.filter(p=>p.m < 0).sort((a,b)=>a.m-b.m)[0] || null;
  const melhorProjeto = d.projetos.filter(p=>p.m > 0).sort((a,b)=>b.m-a.m)[0] || null;
  const semReceita    = d.projetos.filter(p => p.rev === 0 && p.bud > 0);

  const insights = [
    melhorProjeto && { tipo:'destaque', icon:'trend',  titulo:'Melhor rentabilidade', texto:`O projeto "${melhorProjeto.t}" gerou ${fmtBRL(melhorProjeto.m)} de margem no período.${melhorProjeto.bud > 0 ? ` Aderência ao orçamento: ${Math.round((melhorProjeto.rev/melhorProjeto.bud)*100)}%.` : ''}` },
    melhorCliente && d.clientes.length > 1 && { tipo:'destaque', icon:'users', titulo:'Maior receita por cliente', texto:`${melhorCliente.n} foi o cliente com maior receita no período: ${melhorCliente.v}. Concentrar esforços em clientes de alto valor pode aumentar a margem geral.` },
    piorProjeto && { tipo:'alerta', icon:'shield', titulo:'Margem negativa detectada', texto:`O projeto "${piorProjeto.t}" encerrou o período com margem de ${fmtBRL(piorProjeto.m)}. Revise o contrato ou redistribua custos para evitar prejuízo recorrente.` },
    semReceita.length > 0 && { tipo:'alerta', icon:'bolt', titulo:`${semReceita.length} projeto(s) sem receita registrada`, texto:`${semReceita.map(p=>p.t.split('·')[0].trim()).join(', ')} têm orçamento definido mas nenhuma entrada financeira registrada no período. Verifique se há faturas pendentes.` },
    d.margem < 30 && d.receita > 0 && { tipo:'alerta', icon:'chart', titulo:'Margem abaixo do ideal', texto:`Margem atual de ${d.margem}% está abaixo do benchmark de 30% para serviços criativos. As alavancas mais rápidas são aumentar valor cobrado ou reduzir despesas operacionais.` },
    d.receita > 0 && { tipo:'rec', icon:'dollar', titulo:'Oportunidade de crescimento', texto:`Receita de ${fmtBRL(d.receita)} no período com margem de ${d.margem}%. ${d.margem >= 30 ? 'Ótimo resultado! Considere reinvestir parte da margem em marketing ou ferramentas.' : 'Foque em contratos com maior valor por hora e reduza revisões não cobradas.'}` },
    d.clientes.length > 0 && d.clientes.length < 3 && { tipo:'rec', icon:'users', titulo:'Concentração de receita', texto:`Você tem receita de apenas ${d.clientes.length} cliente(s) no período. Diversificar a base de clientes reduz o risco e aumenta a previsibilidade do faturamento.` },
  ].filter(Boolean);

  const cores  = { destaque:'#22C55E', alerta:'#FA8C16', rec:'#1D39C4' };
  const labels = { destaque:'Destaque', alerta:'Atenção', rec:'Recomendação' };

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.65)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'min(600px,100%)', maxHeight:'88vh', display:'flex', flexDirection:'column', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>
        <div style={{ padding:'18px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between', flexShrink:0 }}>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <div style={{ width:36, height:36, borderRadius:10, background:'linear-gradient(135deg,#7C3AED,#1D39C4)', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon d={ICONS.bolt} size={18} style={{ color:'#fff' }}/></div>
            <div><div style={{ fontSize:15, fontWeight:700 }}>Análise de IA</div><div style={{ fontSize:11, color:'var(--fg-muted)' }}>{periodoLabel}</div></div>
          </div>
          <button onClick={onClose} style={{ background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', width:32, height:32, borderRadius:8, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon d={ICONS.x} size={16}/></button>
        </div>
        <div style={{ flex:1, overflow:'auto', padding:24 }}>
          {!ready ? (
            <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'48px 0', gap:16 }}>
              <div style={{ width:48, height:48, borderRadius:'50%', border:'3px solid var(--border-subtle)', borderTopColor:'var(--primary)', animation:'spin 0.8s linear infinite' }}/>
              <div style={{ fontSize:14, color:'var(--fg-muted)' }}>Analisando dados do período…</div>
              <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
            </div>
          ) : insights.length === 0 ? (
            <div style={{ textAlign:'center', padding:'48px 0', color:'var(--fg-muted)', fontSize:14 }}>Nenhum dado financeiro encontrado no período para gerar análise.</div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
              <div style={{ fontSize:13, color:'var(--fg-muted)', marginBottom:4, lineHeight:1.5 }}>Análise gerada com base nos dados reais do período. {insights.length} observações encontradas.</div>
              {insights.map((ins,i)=>(
                <div key={i} style={{ padding:'14px 16px', borderRadius:12, border:`1px solid ${cores[ins.tipo]}33`, background:`${cores[ins.tipo]}0a`, display:'flex', gap:12, alignItems:'flex-start' }}>
                  <div style={{ width:32, height:32, borderRadius:8, background:cores[ins.tipo]+'22', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, color:cores[ins.tipo] }}><Icon d={ICONS[ins.icon]||ICONS.bolt} size={15}/></div>
                  <div style={{ flex:1 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:5 }}>
                      <span style={{ fontSize:12, fontWeight:700 }}>{ins.titulo}</span>
                      <span style={{ fontSize:9, fontWeight:700, padding:'2px 7px', borderRadius:999, background:cores[ins.tipo]+'22', color:cores[ins.tipo], textTransform:'uppercase', letterSpacing:'0.06em' }}>{labels[ins.tipo]}</span>
                    </div>
                    <div style={{ fontSize:13, color:'var(--fg-secondary)', lineHeight:1.55 }}>{ins.texto}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
        {ready && (
          <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', gap:8, justifyContent:'flex-end', flexShrink:0 }}>
            <Button variant="secondary" size="sm" onClick={()=>{ window.__toast?.('Análise exportada',{tone:'success'}); onClose(); }}>Exportar análise</Button>
            <Button size="sm" onClick={onClose}>Fechar</Button>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Geral Tab ────────────────────────────────────────────────────────────────
function GeralTab({ d, onPdf, onIa }) {
  const W = 480, H = 120;
  const maxH = Math.max(1, ...d.semanas);
  const maxC = Math.max(1, ...d.clientes.map(c=>c.raw));
  const points = d.semanas.length > 1
    ? d.semanas.map((v,i)=>`${(i/(d.semanas.length-1))*W},${H-(v/maxH)*H}`).join(' ')
    : `0,${H} ${W},${H}`;
  return (
    <>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        {d.kpis.map((k,i)=><KpiCard key={i} label={k.l} value={k.v} sub={k.d} tone={k.tone}/>)}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:16 }}>
        <Card>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:18 }}>
            <h3 style={{ margin:0, fontSize:14, fontWeight:700, flex:1 }}>Receita por período</h3>
            <Badge tone="success" dot={false}>{d.badge}</Badge>
            <Button variant="secondary" size="sm" icon="page" onClick={onPdf}>PDF</Button>
            <Button size="sm" icon="bolt" onClick={onIa}>Análise IA</Button>
          </div>
          {d.semanas.every(v=>v===0) ? (
            <div style={{ padding:'32px 0', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Nenhuma receita registrada neste período.</div>
          ) : (
            <svg viewBox={`0 0 ${W} ${H+20}`} style={{ width:'100%', height:160 }}>
              <defs><linearGradient id="rep-g" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="var(--primary)" stopOpacity="0.55"/><stop offset="100%" stopColor="var(--primary)" stopOpacity="0"/></linearGradient></defs>
              {[0,0.25,0.5,0.75,1].map(t=><line key={t} x1="0" y1={t*H} x2={W} y2={t*H} stroke="var(--border-subtle)" strokeDasharray="2 4"/>)}
              {d.semanas.length > 1 && <polygon points={`0,${H} ${points} ${W},${H}`} fill="url(#rep-g)"/>}
              {d.semanas.length > 1 && <polyline points={points} fill="none" stroke="var(--primary)" strokeWidth="2.5"/>}
              {d.semanas.map((v,i)=>{ const x=d.semanas.length>1?(i/(d.semanas.length-1))*W:W/2; const y=H-(v/maxH)*H; return <circle key={i} cx={x} cy={y} r="4" fill="var(--bg-surface)" stroke="var(--primary)" strokeWidth="2"/>; })}
              {d.sLabel.map((l,i)=><text key={l} x={d.sLabel.length>1?(i/(d.sLabel.length-1))*W:W/2} y={H+16} textAnchor="middle" fill="var(--fg-muted)" fontSize="10" fontFamily="var(--font-mono)">{l}</text>)}
            </svg>
          )}
        </Card>
        <Card>
          <h3 style={{ margin:'0 0 14px', fontSize:14, fontWeight:700 }}>Receita por cliente</h3>
          {d.clientes.length === 0 ? (
            <div style={{ padding:'32px 0', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Nenhuma receita vinculada a projetos neste período.</div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              {d.clientes.map(c=>(
                <div key={c.n} style={{ display:'flex', alignItems:'center', gap:12 }}>
                  <Avatar name={c.n} size={28} idx={c.i}/>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:'flex', justifyContent:'space-between' }}>
                      <span style={{ fontSize:12, fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', maxWidth:120 }}>{c.n}</span>
                      <span style={{ fontSize:11, color:'var(--fg-muted)', fontFamily:'var(--font-mono)', flexShrink:0 }}>{c.v}</span>
                    </div>
                    <div style={{ height:6, background:'var(--bg-elevated)', borderRadius:999, marginTop:6, overflow:'hidden' }}>
                      <div style={{ width:`${(c.raw/maxC)*100}%`, height:'100%', background:c.c, borderRadius:999 }}/>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>
      <Card padding={0}>
        <div style={{ padding:'14px 18px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center' }}>
          <h3 style={{ margin:0, fontSize:14, fontWeight:700, flex:1 }}>Projetos</h3>
          <span style={{ fontSize:11, color:'var(--fg-muted)' }}>receita real · orçamento · margem</span>
        </div>
        {d.projetos.length === 0 ? (
          <div style={{ padding:'32px 0', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Nenhum projeto encontrado.</div>
        ) : (
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr style={{ background:'var(--bg-elevated)' }}>{['Projeto','Receita','Orçamento','Aderência','Margem','Status'].map(h=><th key={h} style={{ textAlign:'left', padding:'10px 18px', fontSize:11, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.06em' }}>{h}</th>)}</tr></thead>
            <tbody>{d.projetos.map((p,i)=>(
              <tr key={i} style={{ borderTop:'1px solid var(--border-subtle)' }}>
                <td style={{ padding:'14px 18px', fontSize:13, fontWeight:600 }}>{p.t}</td>
                <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)' }}>{fmtBRL(p.rev)}</td>
                <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)', color:'var(--fg-muted)' }}>{p.bud > 0 ? fmtBRL(p.bud) : '—'}</td>
                <td style={{ padding:'14px 18px', minWidth:140 }}>
                  {p.adPct !== null ? (
                    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                      <div style={{ flex:1, height:6, background:'var(--bg-elevated)', borderRadius:999, overflow:'hidden' }}>
                        <div style={{ width:`${Math.min(p.adPct,100)}%`, height:'100%', background:p.adPct<=100?'var(--primary)':'var(--accent-danger,#EF4444)', borderRadius:999 }}/>
                      </div>
                      <span style={{ fontSize:11, fontFamily:'var(--font-mono)', color:'var(--fg-muted)' }}>{p.adPct}%</span>
                    </div>
                  ) : <span style={{ fontSize:12, color:'var(--fg-muted)' }}>—</span>}
                </td>
                <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)', fontWeight:600, color:p.m<0?'#EF4444':'var(--fg-primary)' }}>{fmtBRL(p.m)}</td>
                <td style={{ padding:'14px 18px' }}><Badge tone={p.tone} dot={false}>{p.tone==='success'?'Saudável':p.tone==='warning'?'Atenção':p.tone==='danger'?'Prejuízo':'Neutro'}</Badge></td>
              </tr>
            ))}</tbody>
          </table>
        )}
      </Card>
    </>
  );
}

// ─── Projetos Tab ─────────────────────────────────────────────────────────────
function ProjetosTab({ allProjects }) {
  const [statusFilter, setStatusFilter] = useState('todos');
  const now = new Date(); now.setHours(0,0,0,0);

  function projStatus(p) {
    if (p.status === 'concluido') return 'concluido';
    if (p.status === 'pausado') return 'pausado';
    if (p.due_date && new Date(p.due_date + 'T00:00:00') < now) return 'atrasado';
    if (p.status === 'andamento' || p.status === 'ativo') return 'andamento';
    return p.status || 'planejamento';
  }

  const statusCounts = { todos:allProjects.length, andamento:0, concluido:0, atrasado:0, planejamento:0, pausado:0 };
  allProjects.forEach(p => { const s = projStatus(p); if (s in statusCounts) statusCounts[s]++; });

  const visible = allProjects.filter(p => statusFilter === 'todos' || projStatus(p) === statusFilter);

  const statusDist = [
    { k:'andamento', l:'Em andamento', c:'#1D39C4', n:statusCounts.andamento },
    { k:'concluido', l:'Concluídos',   c:'#22C55E', n:statusCounts.concluido },
    { k:'atrasado',  l:'Atrasados',    c:'#EF4444', n:statusCounts.atrasado },
    { k:'planejamento', l:'Planejamento', c:'#FADB14', n:statusCounts.planejamento },
    { k:'pausado',   l:'Pausados',     c:'#94A3B8', n:statusCounts.pausado },
  ].filter(s => s.n > 0);
  const maxDist = Math.max(1, ...statusDist.map(s=>s.n));

  const chip = active => ({ padding:'5px 12px', borderRadius:999, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:active?'var(--primary-soft)':'var(--bg-elevated)', color:active?'var(--geek-blue-200)':'var(--fg-secondary)', border:`1px solid ${active?'var(--geek-blue-a40)':'var(--border-subtle)'}` });

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <KpiCard label="Total de projetos" value={String(statusCounts.todos)} sub="cadastrados" tone="neutral"/>
        <KpiCard label="Em andamento"       value={String(statusCounts.andamento)} sub="ativos agora" tone="brand" color="#1D39C4"/>
        <KpiCard label="Concluídos"         value={String(statusCounts.concluido)} sub="finalizados" tone="success" color="#22C55E"/>
        <KpiCard label="Atrasados"          value={String(statusCounts.atrasado)}  sub={statusCounts.atrasado > 0 ? 'atenção necessária':'em dia'} tone={statusCounts.atrasado > 0 ? 'danger':'success'} color={statusCounts.atrasado > 0 ? '#EF4444' : '#22C55E'}/>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 2fr', gap:18 }}>
        <Card padding={20}>
          <h3 style={{ margin:'0 0 16px', fontSize:15, fontWeight:700 }}>Distribuição por status</h3>
          {statusDist.length === 0
            ? <div style={{ color:'var(--fg-muted)', fontSize:13 }}>Nenhum projeto.</div>
            : statusDist.map(s=>(
                <div key={s.k} style={{ marginBottom:14 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:5 }}>
                    <span style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <span style={{ width:10, height:10, borderRadius:3, background:s.c }}/>
                      {s.l}
                    </span>
                    <span style={{ fontFamily:'var(--font-mono)', fontWeight:700, color:'var(--fg-secondary)' }}>{s.n}</span>
                  </div>
                  <div style={{ height:6, borderRadius:999, background:'var(--bg-elevated)' }}>
                    <div style={{ height:'100%', width:(s.n/maxDist*100)+'%', background:s.c, borderRadius:999 }}/>
                  </div>
                </div>
              ))
          }
        </Card>
        <Card padding={0}>
          <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
            <h3 style={{ margin:0, fontSize:14, fontWeight:700, marginRight:8 }}>Lista de projetos</h3>
            {[['todos','Todos'],['andamento','Ativos'],['concluido','Concluídos'],['atrasado','Atrasados'],['planejamento','Planejamento']].map(([id,l])=>(
              <button key={id} onClick={()=>setStatusFilter(id)} style={chip(statusFilter===id)}>{l}{id!=='todos'?` (${statusCounts[id]||0})`:''}</button>
            ))}
            <span style={{ marginLeft:'auto', fontSize:11, color:'var(--fg-muted)' }}>{visible.length} projeto{visible.length!==1?'s':''}</span>
          </div>
          {visible.length === 0 ? (
            <div style={{ padding:'32px', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Nenhum projeto neste filtro.</div>
          ) : visible.slice(0, 20).map((p,i)=>{
              const ps = projStatus(p);
              const fmtDue = p.due_date ? (() => { const [y,m,d]=p.due_date.split('-'); return `${d}/${m}`; })() : null;
              return (
                <div key={p.id||i} style={{ padding:'14px 20px', borderBottom:i<visible.length-1?'1px solid var(--border-subtle)':'none', display:'flex', alignItems:'center', gap:14 }}>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:14, fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{p.name}</div>
                    <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:3, display:'flex', gap:10 }}>
                      {p.client && <span>{p.client}</span>}
                      {fmtDue && <><span>·</span><span>Prazo {fmtDue}</span></>}
                      {p.budget > 0 && <><span>·</span><span>{fmtBRL(p.budget)}</span></>}
                    </div>
                  </div>
                  <ProjStatusBadge status={ps}/>
                </div>
              );
            })
          }
        </Card>
      </div>
    </div>
  );
}

// ─── Tarefas Tab ──────────────────────────────────────────────────────────────
function TarefasTab({ allTasks }) {
  const [taskFilter, setTaskFilter] = useState('todos');
  const now = new Date(); now.setHours(0,0,0,0);

  function taskStatus(t) {
    if (t.status === 'done' || t.status === 'concluido' || t.status === 'concluída') return 'done';
    if (t.due_date && new Date(t.due_date + 'T00:00:00') < now) return 'atrasado';
    return 'pendente';
  }

  const total     = allTasks.length;
  const done      = allTasks.filter(t => taskStatus(t) === 'done').length;
  const atrasadas = allTasks.filter(t => taskStatus(t) === 'atrasado').length;
  const pendentes = allTasks.filter(t => taskStatus(t) === 'pendente').length;
  const taxa      = total > 0 ? Math.round(done/total*100) : 0;

  // Tasks per week (last 8 weeks)
  const weekLabels = [], weekData = [];
  for (let w = 7; w >= 0; w--) {
    const start = new Date(now); start.setDate(start.getDate() - w*7 - 6);
    const end   = new Date(now); end.setDate(end.getDate() - w*7);
    weekLabels.push(`S${8-w}`);
    weekData.push(allTasks.filter(t => {
      if (taskStatus(t) !== 'done') return false;
      const d = t.updated_at || t.created_at;
      if (!d) return false;
      const td = new Date(d); td.setHours(0,0,0,0);
      return td >= start && td <= end;
    }).length);
  }

  const visibleTasks = allTasks.filter(t => {
    if (taskFilter === 'todos') return true;
    return taskStatus(t) === taskFilter;
  });

  const chip = active => ({ padding:'5px 12px', borderRadius:999, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:active?'var(--primary-soft)':'var(--bg-elevated)', color:active?'var(--geek-blue-200)':'var(--fg-secondary)', border:`1px solid ${active?'var(--geek-blue-a40)':'var(--border-subtle)'}` });
  const taskStatusLabel = { done:'Concluída', pendente:'Pendente', atrasado:'Atrasada' };
  const taskStatusTone  = { done:'success', pendente:'neutral', atrasado:'danger' };

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <KpiCard label="Total de tarefas" value={String(total)} sub="cadastradas" tone="neutral"/>
        <KpiCard label="Concluídas" value={String(done)} sub={taxa + '% de conclusão'} tone="success" color="#22C55E"/>
        <KpiCard label="Pendentes"  value={String(pendentes)} sub="em aberto" tone="neutral"/>
        <KpiCard label="Atrasadas"  value={String(atrasadas)} sub={atrasadas>0?'requerem atenção':'todas em dia'} tone={atrasadas>0?'danger':'success'} color={atrasadas>0?'#EF4444':'#22C55E'}/>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:18 }}>
        <Card padding={20}>
          <h3 style={{ margin:'0 0 16px', fontSize:15, fontWeight:700 }}>Tarefas concluídas por semana</h3>
          <div style={{ fontSize:12, color:'var(--fg-muted)', marginBottom:14 }}>Últimas 8 semanas</div>
          {weekData.every(v=>v===0)
            ? <div style={{ padding:'20px 0', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Nenhuma tarefa concluída registrada.</div>
            : <MiniBar data={weekData} labels={weekLabels} color="#1D39C4" height={110}/>
          }
        </Card>

        <Card padding={20}>
          <h3 style={{ margin:'0 0 16px', fontSize:15, fontWeight:700 }}>Taxa de conclusão</h3>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {[
              { l:'Concluídas', n:done, t:total, c:'#22C55E' },
              { l:'Pendentes',  n:pendentes, t:total, c:'#FADB14' },
              { l:'Atrasadas',  n:atrasadas, t:total, c:'#EF4444' },
            ].map(r=>(
              <div key={r.l}>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:5 }}>
                  <span style={{ display:'flex', alignItems:'center', gap:8 }}><span style={{ width:10, height:10, borderRadius:3, background:r.c }}/>{r.l}</span>
                  <span style={{ fontFamily:'var(--font-mono)', fontWeight:700, color:'var(--fg-secondary)' }}>{r.n} <span style={{ color:'var(--fg-muted)', fontWeight:400 }}>({r.t>0?Math.round(r.n/r.t*100):0}%)</span></span>
                </div>
                <div style={{ height:6, borderRadius:999, background:'var(--bg-elevated)' }}>
                  <div style={{ height:'100%', width:(r.t>0?r.n/r.t*100:0)+'%', background:r.c, borderRadius:999 }}/>
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop:20, padding:'14px 16px', borderRadius:10, background:'var(--bg-elevated)' }}>
            <div style={{ fontSize:11, color:'var(--fg-muted)', marginBottom:4, textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:700 }}>Taxa de conclusão</div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:32, fontWeight:700, color:taxa>=70?'#22C55E':taxa>=40?'#FADB14':'#EF4444' }}>{taxa}%</div>
          </div>
        </Card>
      </div>

      <Card padding={0}>
        <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
          <h3 style={{ margin:0, fontSize:14, fontWeight:700, marginRight:8 }}>Lista de tarefas</h3>
          {[['todos','Todas'],['done','Concluídas'],['pendente','Pendentes'],['atrasado','Atrasadas']].map(([id,l])=>(
            <button key={id} onClick={()=>setTaskFilter(id)} style={chip(taskFilter===id)}>{l}</button>
          ))}
          <span style={{ marginLeft:'auto', fontSize:11, color:'var(--fg-muted)' }}>{visibleTasks.length} tarefa{visibleTasks.length!==1?'s':''}</span>
        </div>
        {visibleTasks.length === 0 ? (
          <div style={{ padding:'32px', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Nenhuma tarefa neste filtro.</div>
        ) : visibleTasks.slice(0,20).map((t,i)=>{
            const ts = taskStatus(t);
            return (
              <div key={t.id||i} style={{ padding:'13px 20px', borderBottom:i<visibleTasks.slice(0,20).length-1?'1px solid var(--border-subtle)':'none', display:'flex', alignItems:'center', gap:14 }}>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13, fontWeight:600 }}>{t.title}</div>
                  <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2, display:'flex', gap:10 }}>
                    {t.project_name && <span>{t.project_name}</span>}
                    {t.due_date && <><span>·</span><span>Prazo {(()=>{ const [y,m,d]=t.due_date.split('-'); return `${d}/${m}`; })()}</span></>}
                    {t.assignee_name && <><span>·</span><span>{t.assignee_name}</span></>}
                  </div>
                </div>
                <Badge tone={taskStatusTone[ts]} dot={false}>{taskStatusLabel[ts]}</Badge>
              </div>
            );
          })
        }
      </Card>
    </div>
  );
}

// ─── Clientes Tab ─────────────────────────────────────────────────────────────
function ClientesTab({ allProjects, allClients, finances }) {
  const now = new Date();
  const curMonthKey = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;

  // Group projects by client
  const byClient = {};
  allProjects.forEach(p => {
    if (!p.client) return;
    if (!byClient[p.client]) byClient[p.client] = { name:p.client, projects:[], revenue:0 };
    byClient[p.client].projects.push(p);
  });

  // Revenue by client from finances (via project linkage)
  const projRevMap = {};
  finances.forEach(f => {
    if (f.project_id && f.type === 'receita') projRevMap[f.project_id] = (projRevMap[f.project_id]||0) + parseFloat(f.amount||0);
  });
  allProjects.forEach(p => {
    if (p.client && byClient[p.client]) byClient[p.client].revenue += projRevMap[p.id] || 0;
  });

  const clientRows = Object.values(byClient).sort((a,b) => b.revenue - a.revenue || b.projects.length - a.projects.length);
  const recorrentes = clientRows.filter(c => c.projects.length > 1).length;

  // Clients with active project this month (new or returning)
  const novosEsteMes = allProjects.filter(p => p.created_at && p.created_at.startsWith(curMonthKey)).map(p=>p.client).filter(Boolean);
  const novosUnicos  = [...new Set(novosEsteMes)].filter(c => !byClient[c]?.projects.some(p => !p.created_at?.startsWith(curMonthKey)));

  const maxRev = Math.max(1, ...clientRows.map(c=>c.revenue));
  const [expanded, setExpanded] = useState(null);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14 }}>
        <KpiCard label="Clientes com projeto" value={String(clientRows.length)} sub="com ao menos 1 projeto" tone="brand" color="var(--geek-blue-300)"/>
        <KpiCard label="Recorrentes" value={String(recorrentes)} sub={String(recorrentes) + ' clientes com 2+ projetos'} tone="success" color="#22C55E"/>
        <KpiCard label="Base de clientes" value={String(allClients.length)} sub="clientes cadastrados" tone="neutral"/>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:18 }}>
        <Card padding={0}>
          <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)' }}>
            <h3 style={{ margin:0, fontSize:14, fontWeight:700 }}>Projetos por cliente</h3>
          </div>
          {clientRows.length === 0 ? (
            <div style={{ padding:'32px', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Nenhum projeto com cliente vinculado.</div>
          ) : clientRows.map((c,i)=>(
              <div key={c.name}>
                <div onClick={()=>setExpanded(expanded===c.name?null:c.name)} style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:14, cursor:'pointer' }}
                  onMouseEnter={e=>e.currentTarget.style.background='var(--bg-elevated)'}
                  onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                  <Avatar name={c.name} size={34} idx={i}/>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:14, fontWeight:600 }}>{c.name}</div>
                    <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>{c.projects.length} projeto{c.projects.length!==1?'s':''}{c.revenue>0?' · '+fmtBRL(c.revenue):''}</div>
                  </div>
                  {c.projects.length > 1 && <Badge tone="success" dot={false}>Recorrente</Badge>}
                  <span style={{ color:'var(--fg-muted)', fontSize:12 }}>{expanded===c.name?'▲':'▼'}</span>
                </div>
                {expanded === c.name && c.projects.map((p,j)=>(
                  <div key={p.id||j} style={{ padding:'10px 20px 10px 68px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:12, background:'var(--bg-elevated)' }}>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:13, fontWeight:600 }}>{p.name}</div>
                      {p.budget > 0 && <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>{fmtBRL(p.budget)}</div>}
                    </div>
                    <ProjStatusBadge status={p.status}/>
                  </div>
                ))}
              </div>
            ))
          }
        </Card>

        <Card padding={20}>
          <h3 style={{ margin:'0 0 16px', fontSize:15, fontWeight:700 }}>Receita por cliente</h3>
          {clientRows.filter(c=>c.revenue>0).length === 0 ? (
            <div style={{ color:'var(--fg-muted)', fontSize:13 }}>Nenhuma receita vinculada a clientes via projetos.</div>
          ) : clientRows.filter(c=>c.revenue>0).slice(0,6).map((c,i)=>(
              <div key={c.name} style={{ marginBottom:14 }}>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:5 }}>
                  <span style={{ display:'flex', alignItems:'center', gap:8 }}>
                    <Avatar name={c.name} size={18} idx={i}/>
                    <span style={{ fontWeight:600 }}>{c.name}</span>
                  </span>
                  <span style={{ fontFamily:'var(--font-mono)', color:'#22C55E', fontWeight:700 }}>{fmtBRL(c.revenue)}</span>
                </div>
                <div style={{ height:5, borderRadius:999, background:'var(--bg-elevated)' }}>
                  <div style={{ height:'100%', width:(c.revenue/maxRev*100)+'%', background:CHART_COLORS[i%CHART_COLORS.length], borderRadius:999 }}/>
                </div>
              </div>
            ))
          }
        </Card>
      </div>
    </div>
  );
}

// ─── TempoTab ─────────────────────────────────────────────────────────────────
function fmtDur(s) {
  if (!s || s < 0) return '0s';
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = s % 60;
  if (h > 0) return `${h}h ${m.toString().padStart(2,'0')}m`;
  if (m > 0) return `${m}m ${sec.toString().padStart(2,'0')}s`;
  return `${sec}s`;
}

function TempoTab() {
  const raw = (() => { try { return JSON.parse(localStorage.getItem('inbrivvo.timer') || 'null'); } catch { return null; } })();
  const logs = (raw?.logs || []).slice().reverse(); // most recent first

  // KPIs
  const totalSec   = logs.reduce((s, l) => s + (l.duration || 0), 0);
  const totalSess  = logs.length;
  const projMap    = {};
  logs.forEach(l => {
    const p = l.project || 'Sem projeto';
    projMap[p] = (projMap[p] || 0) + (l.duration || 0);
  });
  const projList = Object.entries(projMap).sort((a,b) => b[1]-a[1]);
  const topProj  = projList[0];
  const maxSec   = projList[0]?.[1] || 1;

  // Timer running now?
  const running   = raw?.running;
  const currentProj = raw?.project;

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:20 }}>

      {/* KPI strip */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(180px,1fr))', gap:14 }}>
        {[
          { l:'Total registrado', v: totalSec > 0 ? fmtDur(totalSec) : '—', d: totalSess + ' sessõe' + (totalSess !== 1 ? 's' : ''), tone:'success' },
          { l:'Sessões',          v: String(totalSess),                      d: projList.length + ' projeto' + (projList.length !== 1 ? 's' : ''), tone:'neutral' },
          { l:'Mais trabalhado',  v: topProj ? topProj[0] : '—',            d: topProj ? fmtDur(topProj[1]) : 'sem registros', tone: topProj ? 'warning' : 'neutral' },
          { l:'Cronômetro',       v: running ? 'Rodando' : 'Parado',        d: running ? (currentProj || 'sem projeto') : 'inativo', tone: running ? 'success' : 'neutral' },
        ].map((k,i) => (
          <div key={i} style={{ background:'var(--bg-surface)', border:'1px solid var(--border-subtle)', borderRadius:12, padding:'16px 18px' }}>
            <div style={{ fontSize:11, color:'var(--fg-muted)', fontWeight:500, marginBottom:6, textTransform:'uppercase', letterSpacing:'0.05em' }}>{k.l}</div>
            <div style={{ fontSize:22, fontWeight:700, color: k.tone==='success'?'#22C55E': k.tone==='warning'?'var(--geek-blue-200)':'var(--fg-primary)', fontFamily:'var(--font-mono)', marginBottom:4, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{k.v}</div>
            <div style={{ fontSize:11, color:'var(--fg-muted)' }}>{k.d}</div>
          </div>
        ))}
      </div>

      {/* Horas por projeto */}
      {projList.length > 0 && (
        <Card style={{ padding:'20px 22px' }}>
          <div style={{ fontWeight:700, fontSize:13, marginBottom:14 }}>Horas por projeto</div>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {projList.map(([proj, sec], i) => (
              <div key={proj}>
                <div style={{ display:'flex', justifyContent:'space-between', marginBottom:4 }}>
                  <span style={{ fontSize:12, fontWeight:600, color:'var(--fg-primary)' }}>{proj}</span>
                  <span style={{ fontSize:12, fontFamily:'var(--font-mono)', color:'var(--fg-secondary)' }}>{fmtDur(sec)}</span>
                </div>
                <div style={{ height:6, borderRadius:999, background:'var(--bg-elevated)' }}>
                  <div style={{ height:'100%', width:(sec/maxSec*100)+'%', background: CHART_COLORS[i % CHART_COLORS.length], borderRadius:999, transition:'width 0.4s ease' }}/>
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* Log de sessões */}
      <Card style={{ padding:'20px 22px' }}>
        <div style={{ fontWeight:700, fontSize:13, marginBottom:14 }}>Log de sessões</div>
        {logs.length === 0 ? (
          <div style={{ padding:'32px 0', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>
            Nenhuma sessão registrada ainda. Inicie o cronômetro no Dashboard!
          </div>
        ) : (
          <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
            {/* header */}
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 110px 72px', gap:8, padding:'6px 0', borderBottom:'1px solid var(--border-subtle)', marginBottom:4 }}>
              {['Projeto','Tarefa','Duração','Hora'].map(h=>(
                <span key={h} style={{ fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.05em', color:'var(--fg-muted)' }}>{h}</span>
              ))}
            </div>
            {logs.map((l, i) => (
              <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr 1fr 110px 72px', gap:8, padding:'9px 0', borderBottom: i < logs.length-1 ? '1px solid var(--border-subtle)' : 'none', alignItems:'center' }}>
                <span style={{ fontSize:12, fontWeight:600, color:'var(--fg-primary)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{l.project || '—'}</span>
                <span style={{ fontSize:12, color:'var(--fg-secondary)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{l.task || 'Sem descrição'}</span>
                <span style={{ fontSize:12, fontFamily:'var(--font-mono)', color:'#22C55E', fontWeight:700 }}>{fmtDur(l.duration || 0)}</span>
                <span style={{ fontSize:11, color:'var(--fg-muted)' }}>{l.time || '—'}</span>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}

// ─── Reports ──────────────────────────────────────────────────────────────────
const PERIODOS = [
  { id:'30d', l:'Últimos 30 dias' },
  { id:'trim', l:'Trimestre' },
  { id:'ano', l:'Ano' },
  { id:'custom', l:'Personalizado' },
];

const REPORT_TABS = [
  { id:'geral',     label:'Visão Geral' },
  { id:'projetos',  label:'Projetos' },
  { id:'tarefas',   label:'Tarefas' },
  { id:'clientes',  label:'Clientes' },
  { id:'horas',     label:'Horas' },
];

function Reports() {
  const [tab,         setTab]         = useState('geral');
  const [periodo,     setPeriodo]     = useState('30d');
  const [customFrom,  setCustomFrom]  = useState('');
  const [customTo,    setCustomTo]    = useState('');
  const [showPicker,  setShowPicker]  = useState(false);
  const [customLabel, setCustomLabel] = useState('');
  const [pdfModal,    setPdfModal]    = useState(false);
  const [iaModal,     setIaModal]     = useState(false);
  const [loading,     setLoading]     = useState(true);
  const [d,           setD]           = useState(null);
  const [allProjects, setAllProjects] = useState([]);
  const [allTasks,    setAllTasks]    = useState([]);
  const [allClients,  setAllClients]  = useState([]);
  const [allFinances, setAllFinances] = useState([]);

  useEffect(() => {
    const now = new Date();
    const today = now.toISOString().slice(0,10);
    let from, to;
    if (periodo === '30d') {
      const f = new Date(now); f.setDate(f.getDate()-30);
      from = f.toISOString().slice(0,10); to = today;
    } else if (periodo === 'trim') {
      const f = new Date(now); f.setDate(f.getDate()-90);
      from = f.toISOString().slice(0,10); to = today;
    } else if (periodo === 'ano') {
      from = `${now.getFullYear()}-01-01`; to = today;
    } else if (periodo === 'custom') {
      if (!customFrom || !customTo) return;
      from = customFrom; to = customTo;
    } else return;

    setLoading(true);
    (async () => {
      const [r0, r1, r2, r3, r4] = await Promise.all([
        sb.from('finances').select('amount,type,project_id,date').gte('date',from).lte('date',to),
        sb.from('projects').select('*').order('created_at',{ ascending:false }),
        sb.from('tasks').select('*').order('created_at',{ ascending:false }),
        sb.from('clients').select('id,name'),
        sb.from('finances').select('amount,type,project_id,date'),
      ]);

      const finances    = r0.data || [];
      const projects    = r1.data || [];
      const tasks       = r2.data || [];
      const clients     = r3.data || [];
      const allFin      = r4.data || [];

      setAllProjects(projects);
      setAllTasks(tasks);
      setAllClients(clients);
      setAllFinances(allFin);

      const receita  = finances.filter(f=>f.type==='receita').reduce((s,f)=>s+parseFloat(f.amount||0),0);
      const despesas = finances.filter(f=>f.type==='despesa').reduce((s,f)=>s+parseFloat(f.amount||0),0);
      const margem   = receita > 0 ? Math.round((receita-despesas)/receita*100) : 0;
      const ativos   = projects.filter(p => ['andamento','ativo','planejamento'].includes(p.status)).length;

      const kpis = [
        { l:'Receita do período', v:fmtBRL(receita),  d:finances.filter(f=>f.type==='receita').length+' entradas', tone:receita>0?'success':'neutral' },
        { l:'Despesas',           v:fmtBRL(despesas), d:finances.filter(f=>f.type==='despesa').length+' saídas',   tone:'neutral' },
        { l:'Margem líquida',     v:margem+'%',        d:receita>0?(margem>=30?'acima de 30%':'abaixo de 30%'):'sem receita', tone:margem>=30?'success':margem>0?'warning':'neutral' },
        { l:'Projetos ativos',    v:String(ativos),    d:clients.length+' cliente'+(clients.length!==1?'s':''), tone:'success' },
      ];

      const chart = buildChart(finances, from, to);

      const projRevMap = {}, projExpMap = {};
      finances.forEach(f => {
        if (!f.project_id) return;
        if (f.type==='receita') projRevMap[f.project_id]=(projRevMap[f.project_id]||0)+parseFloat(f.amount||0);
        else projExpMap[f.project_id]=(projExpMap[f.project_id]||0)+parseFloat(f.amount||0);
      });

      const projetosData = projects.slice(0,10).map(p => {
        const rev=projRevMap[p.id]||0, exp=projExpMap[p.id]||0, m=rev-exp;
        const adPct=p.budget>0?Math.min(Math.round((rev/p.budget)*100),200):null;
        const tone=m<0?'danger':(p.budget>0&&rev>p.budget*0.5)?'success':rev>0?'warning':'neutral';
        return { t:p.name+(p.client?' · '+p.client:''), rev, bud:p.budget||0, m, adPct, tone, status:p.status };
      });

      const clientRevMap = {};
      projects.forEach(p => { const rev=projRevMap[p.id]||0; if (rev>0&&p.client) clientRevMap[p.client]=(clientRevMap[p.client]||0)+rev; });
      const clienteData = Object.entries(clientRevMap).sort((a,b)=>b[1]-a[1]).slice(0,5).map(([n,raw],i)=>({ n, v:fmtBRL(raw), raw, c:CHART_COLORS[i%CHART_COLORS.length], i }));

      setD({ kpis, semanas:chart.data, sLabel:chart.labels, badge:chart.badge, clientes:clienteData, projetos:projetosData, receita, despesas, margem });
      setLoading(false);
    })();
  }, [periodo, customFrom, customTo]);

  function aplicarCustom() {
    if (!customFrom||!customTo) { window.__toast?.('Selecione as datas de início e fim',{tone:'danger'}); return; }
    if (new Date(customFrom)>new Date(customTo)) { window.__toast?.('Data inicial deve ser anterior à data final',{tone:'danger'}); return; }
    const fmt = s => s.split('-').reverse().join('/');
    setCustomLabel(`${fmt(customFrom)} → ${fmt(customTo)}`);
    setShowPicker(false);
    window.__toast?.('Período personalizado aplicado',{tone:'success'});
  }
  function handlePeriodo(id) { setPeriodo(id); setShowPicker(id==='custom'); }
  const periodoLabel = periodo==='30d'?'Últimos 30 dias':periodo==='trim'?'Trimestre':periodo==='ano'?'Ano':customLabel||'Período personalizado';

  const tabBtn = active => ({
    padding:'10px 18px', borderRadius:'10px 10px 0 0', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
    background:active?'var(--bg-surface)':'transparent', color:active?'var(--fg-primary)':'var(--fg-secondary)',
    border:active?'1px solid var(--border-subtle)':'1px solid transparent',
    borderBottom:active?'1px solid var(--bg-surface)':'1px solid transparent',
    marginBottom:active?-1:0,
  });

  return (
    <div style={{ padding:'24px 28px', display:'flex', flexDirection:'column', gap:18 }}>
      {/* Controls */}
      <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
        {PERIODOS.map(p=>(
          <button key={p.id} onClick={()=>handlePeriodo(p.id)} style={{ background:periodo===p.id?'var(--primary-soft)':'transparent', color:periodo===p.id?'var(--geek-blue-200)':'var(--fg-secondary)', border:'1px solid', borderColor:periodo===p.id?'var(--geek-blue-a40)':'var(--border-subtle)', padding:'7px 14px', borderRadius:8, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit' }}>{p.l}</button>
        ))}
        {showPicker && (
          <div style={{ display:'flex', alignItems:'center', gap:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', borderRadius:8, padding:'4px 10px' }}>
            <input type="date" value={customFrom} onChange={e=>setCustomFrom(e.target.value)} style={{ background:'transparent', border:'none', color:'var(--fg-primary)', fontSize:12, fontFamily:'inherit', outline:'none', cursor:'pointer' }}/>
            <span style={{ color:'var(--fg-muted)', fontSize:12 }}>→</span>
            <input type="date" value={customTo} onChange={e=>setCustomTo(e.target.value)} style={{ background:'transparent', border:'none', color:'var(--fg-primary)', fontSize:12, fontFamily:'inherit', outline:'none', cursor:'pointer' }}/>
            <Button size="sm" onClick={aplicarCustom}>Aplicar</Button>
          </div>
        )}
        {periodo==='custom' && customLabel && !showPicker && (
          <span onClick={()=>setShowPicker(true)} style={{ fontSize:11, color:'var(--fg-muted)', cursor:'pointer', textDecoration:'underline dotted' }}>{customLabel}</span>
        )}
      </div>

      {/* Tab nav */}
      <div style={{ display:'flex', alignItems:'center', gap:2, borderBottom:'1px solid var(--border-subtle)' }}>
        {REPORT_TABS.map(t=><button key={t.id} onClick={()=>setTab(t.id)} style={tabBtn(tab===t.id)}>{t.label}</button>)}
        <div style={{ flex:1 }}/>
        {d && <div style={{ display:'flex', gap:8, marginBottom:4 }}>
          <Button variant="secondary" size="sm" icon="page" onClick={()=>setPdfModal(true)}>Exportar PDF</Button>
          <Button size="sm" icon="bolt" onClick={()=>setIaModal(true)}>Análise IA</Button>
        </div>}
      </div>

      {tab === 'horas' ? (
        <TempoTab/>
      ) : loading || !d ? (
        <div style={{ display:'flex', alignItems:'center', justifyContent:'center', padding:'64px 0', color:'var(--fg-muted)', fontSize:14 }}>Carregando dados…</div>
      ) : (<>
        {tab === 'geral'    && <GeralTab     d={d} onPdf={()=>setPdfModal(true)} onIa={()=>setIaModal(true)}/>}
        {tab === 'projetos' && <ProjetosTab  allProjects={allProjects}/>}
        {tab === 'tarefas'  && <TarefasTab   allTasks={allTasks}/>}
        {tab === 'clientes' && <ClientesTab  allProjects={allProjects} allClients={allClients} finances={allFinances}/>}
      </>)}

      {pdfModal && d && <ExportarPDFModal onClose={()=>setPdfModal(false)} d={d} periodoLabel={periodoLabel}/>}
      {iaModal  && d && <IaAnaliseModal  onClose={()=>setIaModal(false)}  d={d} periodoLabel={periodoLabel}/>}
    </div>
  );
}
window.Reports = Reports;
