// Wave 1 — Dashboard screens (4): Executivo, KPIs históricos, Churn Monitor, Relatórios
// All wrap AppShell and share atoms from this file.

// ---------- Shared page atoms ----------
const PageContainer = ({ title, subtitle, badge, actions, children, maxWidth = 1500 }) => (
  <div style={{ padding: '24px 28px 40px', maxWidth, margin: '0 auto' }}>
    <style>{`
      .pg-head { display: flex; align-items: flex-start; gap: 18px; flex-wrap: wrap; margin-bottom: 22px; }
      .pg-title { font-size: 26px; font-weight: 700; letter-spacing: -0.02em; color: var(--text-0); line-height: 1.15; }
      .pg-sub { font-size: 14px; color: var(--text-2); margin-top: 4px; max-width: 620px; }
      .pg-actions { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }
      .pg-badge {
        display: inline-flex; align-items: center; gap: 6px; padding: 3px 10px; border-radius: 999px;
        background: rgba(139,92,246,.14); color: #c4b5fd; font-size: 11px; font-weight: 600;
        border: 1px solid rgba(139,92,246,.25); text-transform: uppercase; letter-spacing: .06em;
        margin-bottom: 10px;
      }
      .tile { background: var(--bg-2); border: 1px solid var(--line-1); border-radius: var(--r-lg); padding: 18px; }
      .tile-head { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; font-size: 13px; font-weight: 600; color: var(--text-1); }
      .tile-head .grow { flex: 1; }
      .tile-kpi { font-size: 28px; font-weight: 700; letter-spacing: -0.02em; color: var(--text-0); margin: 4px 0; font-variant-numeric: tabular-nums; }
      .tile-delta { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; font-weight: 600; }
      .tile-delta.up { color: #86efac; }
      .tile-delta.down { color: #fca5a5; }
      .tile-sub { font-size: 11.5px; color: var(--text-3); margin-top: 2px; }

      .sect-title { font-size: 13px; font-weight: 600; color: var(--text-0); letter-spacing: -.005em; }
      .sect-sub { font-size: 11.5px; color: var(--text-3); }

      .table-wrap { background: var(--bg-2); border: 1px solid var(--line-1); border-radius: var(--r-lg); overflow: hidden; }
      .tbl { width: 100%; border-collapse: collapse; }
      .tbl th { padding: 12px 16px; font-size: 11px; font-weight: 600; color: var(--text-3); text-transform: uppercase; letter-spacing: .06em; text-align: left; background: var(--bg-1); border-bottom: 1px solid var(--line-1); }
      .tbl td { padding: 12px 16px; font-size: 13px; color: var(--text-1); border-bottom: 1px solid var(--line-1); }
      .tbl tr:last-child td { border-bottom: none; }
      .tbl tr:hover td { background: rgba(255,255,255,.02); }

      .row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
      .row-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
      .row-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }
      @media (max-width: 980px) {
        .row-2, .row-3, .row-4 { grid-template-columns: 1fr; }
      }

      .btn-sm { padding: 7px 12px; font-size: 12.5px; }
      .dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
    `}</style>
    <div className="pg-head">
      <div>
        {badge && <div className="pg-badge">{badge}</div>}
        <h1 className="pg-title">{title}</h1>
        {subtitle && <p className="pg-sub">{subtitle}</p>}
      </div>
      {actions && <div className="pg-actions">{actions}</div>}
    </div>
    {children}
  </div>
);

const Tile = ({ icon, label, value, delta, deltaDir = 'up', sub, accent }) => (
  <div className="tile">
    <div className="tile-head">
      {icon && <span style={{ width: 30, height: 30, borderRadius: 8, background: accent || 'rgba(139,92,246,.12)', color: accent ? 'white' : '#c4b5fd', display: 'grid', placeItems: 'center' }}>
        <Icon name={icon} size={15}/>
      </span>}
      <span className="grow">{label}</span>
    </div>
    <div className="tile-kpi">{value}</div>
    <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
      {delta && <span className={`tile-delta ${deltaDir}`}><Icon name={deltaDir === 'up' ? 'arrowUp' : 'arrowDown'} size={11}/> {delta}</span>}
      {sub && <span className="tile-sub">{sub}</span>}
    </div>
  </div>
);

// Mini sparkline
const Spark = ({ data, stroke = '#a78bfa', fill = 'rgba(139,92,246,.15)', height = 40 }) => {
  const max = Math.max(...data), min = Math.min(...data);
  const w = 120, h = height;
  const pts = data.map((v, i) => [i * (w / (data.length - 1)), h - ((v - min) / (max - min || 1)) * (h - 4) - 2]);
  const path = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const area = path + ` L${w},${h} L0,${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height }}>
      <path d={area} fill={fill} stroke="none"/>
      <path d={path} fill="none" stroke={stroke} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

// Donut chart
const Donut = ({ segments, size = 140, thickness = 18 }) => {
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  const total = segments.reduce((s, x) => s + x.value, 0);
  let offset = 0;
  return (
    <svg viewBox={`0 0 ${size} ${size}`} style={{ width: size, height: size }}>
      <circle cx={size/2} cy={size/2} r={r} stroke="var(--bg-3)" strokeWidth={thickness} fill="none"/>
      {segments.map((s, i) => {
        const len = (s.value / total) * c;
        const dash = `${len} ${c - len}`;
        const el = <circle key={i} cx={size/2} cy={size/2} r={r} stroke={s.color} strokeWidth={thickness} fill="none" strokeDasharray={dash} strokeDashoffset={-offset} transform={`rotate(-90 ${size/2} ${size/2})`} strokeLinecap="butt"/>;
        offset += len;
        return el;
      })}
    </svg>
  );
};

// Bar chart
const Bars = ({ series, labels, height = 200 }) => {
  const max = Math.max(...series.flatMap(s => s.data));
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 18, height, padding: '0 4px' }}>
        {labels.map((lbl, i) => (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, height: '100%' }}>
            <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', gap: 3, width: '100%', justifyContent: 'center' }}>
              {series.map((s, si) => (
                <div key={si} title={`${s.name}: ${s.data[i]}`} style={{
                  width: 10,
                  height: `${(s.data[i] / max) * 100}%`,
                  background: s.color,
                  borderRadius: '3px 3px 0 0',
                  transition: 'height .5s',
                  opacity: 0.9,
                }}/>
              ))}
            </div>
            <div style={{ fontSize: 10.5, color: 'var(--text-3)' }}>{lbl}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 14, marginTop: 10, fontSize: 11.5, color: 'var(--text-2)', justifyContent: 'center' }}>
        {series.map((s, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span className="dot" style={{ background: s.color }}/>{s.name}
          </div>
        ))}
      </div>
    </div>
  );
};

// ==================== 1. Dashboard Executivo ====================
const DashExecutivo = ({ onNavigate }) => (
  <AppShell current="executivo" onNavigate={onNavigate}>
    <PageContainer
      badge={<><Icon name="sparkle" size={10}/> Consolidado pela IA · atualizado há 12 min</>}
      title="Dashboard Executivo"
      subtitle="Visão estratégica consolidada de todas as áreas — use para reuniões de diretoria e tomada de decisão semanal."
      actions={<>
        <button className="btn btn-outline btn-sm"><Icon name="calendar" size={13}/> Abril/2026</button>
        <button className="btn btn-outline btn-sm"><Icon name="download" size={13}/> Exportar PDF</button>
        <button className="btn btn-primary btn-sm"><Icon name="refresh" size={13}/> Atualizar agora</button>
      </>}
    >
      {/* Top KPIs */}
      <div className="row-4" style={{ marginBottom: 18 }}>
        <Tile icon="wallet" label="Receita recorrente (MRR)" value="R$ 87.340,00" delta="+12,3%" sub="vs. mês anterior"/>
        <Tile icon="trending-up" label="Caixa líquido" value="R$ 142.890,00" delta="+8,1%"/>
        <Tile icon="users" label="Base ativa de clientes" value="284" delta="+7" deltaDir="up" sub="3 novos esta semana"/>
        <Tile icon="alert" label="Risco de churn" value="3" delta="-2" deltaDir="down" sub="alto risco esta semana"/>
      </div>

      {/* Revenue trend + breakdown */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, marginBottom: 18 }} className="gridA">
        <style>{`@media (max-width: 980px) { .gridA, .gridB { grid-template-columns: 1fr !important; } }`}</style>
        <div className="tile">
          <div className="tile-head">
            <div className="sect-title">Receita × Despesa · últimos 6 meses</div>
            <span className="grow"/>
            <span className="chip">Mensal</span>
          </div>
          <Bars
            labels={['Nov', 'Dez', 'Jan', 'Fev', 'Mar', 'Abr']}
            series={[
              { name: 'Receita', color: '#8b5cf6', data: [64200, 71800, 68400, 78900, 82100, 87340] },
              { name: 'Despesa', color: '#60a5fa', data: [41200, 44100, 46700, 48900, 51200, 52900] },
            ]}
            height={220}
          />
        </div>
        <div className="tile">
          <div className="tile-head"><div className="sect-title">Receita por módulo</div></div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <Donut segments={[
              { name: 'CRM & Vendas', value: 42, color: '#8b5cf6' },
              { name: 'PDV Fiscal', value: 28, color: '#3b82f6' },
              { name: 'Assinaturas', value: 18, color: '#06b6d4' },
              { name: 'Serviços', value: 12, color: '#22c55e' },
            ]}/>
            <div style={{ fontSize: 12.5, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { lbl: 'CRM & Vendas', v: '42%', c: '#8b5cf6' },
                { lbl: 'PDV Fiscal', v: '28%', c: '#3b82f6' },
                { lbl: 'Assinaturas', v: '18%', c: '#06b6d4' },
                { lbl: 'Serviços', v: '12%', c: '#22c55e' },
              ].map(x => (
                <div key={x.lbl} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span className="dot" style={{ background: x.c }}/>
                  <span style={{ flex: 1, color: 'var(--text-2)' }}>{x.lbl}</span>
                  <b style={{ color: 'var(--text-0)' }}>{x.v}</b>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* AI insights */}
      <div className="tile" style={{ background: 'linear-gradient(135deg, rgba(139,92,246,.08), rgba(59,130,246,.08))', border: '1px solid rgba(139,92,246,.25)', marginBottom: 18 }}>
        <div className="tile-head">
          <span style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--brand-gradient)', display: 'grid', placeItems: 'center' }}>
            <Icon name="sparkle" size={15} color="white"/>
          </span>
          <div className="sect-title">Insights da IA · 4 sugestões para esta semana</div>
          <span className="grow"/>
          <button className="btn btn-outline btn-sm">Ver todos</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }} className="gridB">
          {[
            { icon: 'trending-up', title: 'Oportunidade de upsell em 12 clientes', sub: 'Usuários no plano Essencial já usam 80% dos recursos — sugira upgrade para Profissional. Potencial +R$ 14.880 MRR.' },
            { icon: 'alert', title: '3 clientes com alto risco de churn', sub: 'Distribuidora RC parou de emitir NF-e há 22 dias. Agende follow-up imediato.' },
            { icon: 'dollar', title: '8 faturas em atraso somam R$ 5.850', sub: 'Enviar lembrete automático por WhatsApp poderia recuperar ~60% em 72h.' },
            { icon: 'users', title: 'Contratação acima da média no setor', sub: 'Você contratou 4 CLTs este trimestre (média do setor: 1,2). FGTS provisionado OK.' },
          ].map((x, i) => (
            <div key={i} style={{ padding: 14, background: 'rgba(0,0,0,.2)', borderRadius: 10, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <span style={{ width: 28, height: 28, borderRadius: 7, background: 'rgba(139,92,246,.2)', color: '#c4b5fd', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <Icon name={x.icon} size={13}/>
              </span>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-0)', marginBottom: 2 }}>{x.title}</div>
                <div style={{ fontSize: 12, color: 'var(--text-2)', lineHeight: 1.5 }}>{x.sub}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Per-module quick strip */}
      <div className="row-4">
        {[
          { label: 'CRM · pipeline', value: 'R$ 148.900', sub: '28 negócios em aberto · conversão 32,4%', spark: [20,22,28,34,40,44,48], color: '#8b5cf6', to: 'crm' },
          { label: 'Financeiro · MRR', value: 'R$ 87.340', sub: 'Próximos 30d: R$ 91.200 previsto', spark: [60,64,68,72,75,82,87], color: '#3b82f6', to: 'fluxo' },
          { label: 'RH · folha abril', value: 'R$ 68.420', sub: '17 CLTs · eSocial OK · fechamento dia 25', spark: [58,60,63,66,67,68,68], color: '#22c55e', to: 'folha' },
          { label: 'Suporte · SLA', value: '96,4%', sub: '12 tickets abertos · 4,8/5 CSAT', spark: [92,94,93,95,96,96,97], color: '#06b6d4', to: 'tickets' },
        ].map(m => (
          <button key={m.label} className="tile" onClick={() => onNavigate(m.to)} style={{ cursor: 'pointer', textAlign: 'left' }}>
            <div className="tile-head"><span className="grow">{m.label}</span><Icon name="arrowRight" size={13} color="var(--text-3)"/></div>
            <div className="tile-kpi" style={{ fontSize: 22 }}>{m.value}</div>
            <div className="tile-sub" style={{ marginBottom: 8 }}>{m.sub}</div>
            <Spark data={m.spark} stroke={m.color} fill={m.color + '22'} height={30}/>
          </button>
        ))}
      </div>
    </PageContainer>
  </AppShell>
);

// ==================== 2. KPIs Históricos ====================
const DashKPIs = ({ onNavigate }) => {
  const [range, setRange] = React.useState('12m');
  const [kpi, setKpi] = React.useState('mrr');
  const kpis = {
    mrr: { label: 'MRR (Receita recorrente)', unit: 'R$', data: [42,46,51,55,58,62,64,68,71,75,82,87], goal: 85 },
    cac: { label: 'CAC (Custo por aquisição)', unit: 'R$', data: [420,410,395,388,372,360,355,348,340,335,328,322], goal: 350 },
    ltv: { label: 'LTV (Lifetime Value)', unit: 'R$', data: [2800,2850,2920,2980,3040,3110,3180,3250,3320,3410,3480,3570], goal: 3500 },
    nps: { label: 'NPS', unit: '', data: [42,44,48,51,53,55,58,62,64,66,68,71], goal: 70 },
    churn: { label: 'Churn mensal', unit: '%', data: [4.2,4.0,3.8,3.5,3.4,3.1,2.9,2.8,2.6,2.4,2.2,2.1], goal: 3.0 },
  };
  const labels12 = ['Mai/25','Jun','Jul','Ago','Set','Out','Nov','Dez','Jan/26','Fev','Mar','Abr'];
  const cur = kpis[kpi];
  const last = cur.data[cur.data.length - 1];
  const first = cur.data[0];
  const delta = (((last - first) / first) * 100).toFixed(1);

  return (
    <AppShell current="kpis" onNavigate={onNavigate}>
      <PageContainer
        title="KPIs históricos"
        subtitle="Evolução dos indicadores-chave. Compare com metas, identifique tendências e exporte para reuniões de board."
        actions={<>
          <div style={{ display: 'inline-flex', background: 'var(--bg-2)', border: '1px solid var(--line-2)', borderRadius: 8, padding: 3 }}>
            {['3m','6m','12m','24m'].map(r => (
              <button key={r} onClick={() => setRange(r)} style={{
                padding: '6px 12px', fontSize: 12, borderRadius: 6, fontWeight: 500,
                background: range === r ? 'var(--bg-3)' : 'transparent',
                color: range === r ? 'var(--text-0)' : 'var(--text-3)',
              }}>{r}</button>
            ))}
          </div>
          <button className="btn btn-outline btn-sm"><Icon name="download" size={13}/> CSV</button>
        </>}
      >
        {/* KPI selector chips */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
          {Object.entries(kpis).map(([id, k]) => (
            <button key={id} onClick={() => setKpi(id)} style={{
              padding: '10px 16px', borderRadius: 10, fontSize: 12.5, fontWeight: 500,
              background: kpi === id ? 'var(--brand-gradient)' : 'var(--bg-2)',
              border: `1px solid ${kpi === id ? 'transparent' : 'var(--line-2)'}`,
              color: kpi === id ? 'white' : 'var(--text-1)',
            }}>{k.label}</button>
          ))}
        </div>

        {/* Main chart */}
        <div className="tile" style={{ marginBottom: 16 }}>
          <div className="tile-head">
            <div>
              <div className="sect-title">{cur.label}</div>
              <div className="sect-sub">Últimos 12 meses · atualizado em 17/abr</div>
            </div>
            <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
              <div className="tile-kpi" style={{ margin: 0 }}>
                {cur.unit === 'R$' ? BRLShort(last * 1000) : last + cur.unit}
              </div>
              <div className={`tile-delta ${delta >= 0 ? 'up' : 'down'}`}>
                <Icon name={delta >= 0 ? 'arrowUp' : 'arrowDown'} size={11}/> {delta > 0 ? '+' : ''}{delta}% vs. 12m atrás
              </div>
            </div>
          </div>
          <div style={{ position: 'relative', height: 280, padding: '20px 0' }}>
            <KPILineChart data={cur.data} labels={labels12} goal={cur.goal} unit={cur.unit}/>
          </div>
        </div>

        {/* Secondary strip */}
        <div className="row-4">
          <Tile icon="trending-up" label="Crescimento médio mensal" value="+6,2%" delta="acima da meta"/>
          <Tile icon="target" label="% da meta atual" value="102%" sub={`Meta: ${cur.unit === '%' ? cur.goal + '%' : 'R$ ' + cur.goal + 'k'}`}/>
          <Tile icon="calendar" label="Melhor mês" value="Abr/26" sub={`${cur.unit === 'R$' ? BRLShort(last * 1000) : last + cur.unit}`}/>
          <Tile icon="bell" label="Próxima revisão" value="30/abr" sub="Reunião de board"/>
        </div>
      </PageContainer>
    </AppShell>
  );
};

const KPILineChart = ({ data, labels, goal, unit }) => {
  const max = Math.max(...data, goal) * 1.1;
  const min = Math.min(...data, goal) * 0.9;
  const w = 1000, h = 240;
  const pad = 30;
  const pts = data.map((v, i) => [pad + i * ((w - pad * 2) / (data.length - 1)), h - pad - ((v - min) / (max - min)) * (h - pad * 2)]);
  const path = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const area = path + ` L${pts[pts.length-1][0]},${h-pad} L${pts[0][0]},${h-pad} Z`;
  const goalY = h - pad - ((goal - min) / (max - min)) * (h - pad * 2);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: '100%' }} preserveAspectRatio="none">
      <defs>
        <linearGradient id="kpiGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#a78bfa" stopOpacity=".35"/>
          <stop offset="1" stopColor="#a78bfa" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[0,1,2,3].map(i => {
        const y = pad + i * ((h - pad*2) / 3);
        return <line key={i} x1={pad} x2={w-pad} y1={y} y2={y} stroke="rgba(255,255,255,.06)"/>;
      })}
      <line x1={pad} x2={w-pad} y1={goalY} y2={goalY} stroke="#22c55e" strokeWidth="1.5" strokeDasharray="5 4" opacity=".6"/>
      <text x={w-pad-4} y={goalY-6} fill="#86efac" fontSize="11" textAnchor="end" fontWeight="600">meta</text>
      <path d={area} fill="url(#kpiGrad)"/>
      <path d={path} fill="none" stroke="#a78bfa" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
      {pts.map((p, i) => (
        <g key={i}>
          <circle cx={p[0]} cy={p[1]} r="4" fill="#0c0b1a" stroke="#a78bfa" strokeWidth="2"/>
          <text x={p[0]} y={h-8} fill="rgba(255,255,255,.5)" fontSize="10" textAnchor="middle">{labels[i]}</text>
        </g>
      ))}
    </svg>
  );
};

// ==================== 3. Churn Monitor ====================
const DashChurn = ({ onNavigate }) => {
  const risks = [
    { id: 1, client: 'Distribuidora RC Ltda', score: 87, level: 'alto', mrr: 3200, days: 22, reason: 'Parou de emitir NF-e · Último login há 22 dias · Contrato vence em 18 dias', owner: 'Bruno Tavares', actions: ['Ligar', 'WhatsApp'] },
    { id: 2, client: 'Construtora AV', score: 74, level: 'alto', mrr: 2400, days: 15, reason: 'Uso do PDV caiu 68% · Abriu 3 tickets de suporte esta semana', owner: 'Camila Rocha', actions: ['Ligar'] },
    { id: 3, client: 'Mecânica Rápida', score: 71, level: 'alto', mrr: 540, days: 18, reason: 'Boleto atrasado em 14 dias · Não responde mensagens', owner: 'João Pedro', actions: ['Cobrar'] },
    { id: 4, client: 'Pet Shop Amigo Fiel', score: 58, level: 'medio', mrr: 680, days: 8, reason: 'Downgrade solicitado no último contato', owner: 'Camila Rocha', actions: ['Retenção'] },
    { id: 5, client: 'Hamburgueria 22', score: 52, level: 'medio', mrr: 1240, days: 5, reason: 'Baixa adoção de funcionalidades novas (IA Marketing)', owner: 'João Pedro', actions: [] },
    { id: 6, client: 'Farmácia Bem Estar', score: 48, level: 'medio', mrr: 960, days: 3, reason: 'Pediu integração com sistema legado', owner: 'Bruno Tavares', actions: [] },
  ];
  const levelColor = (l) => l === 'alto' ? '#ef4444' : l === 'medio' ? '#f59e0b' : '#22c55e';

  return (
    <AppShell current="churn" onNavigate={onNavigate}>
      <PageContainer
        badge={<><Icon name="cpu" size={10}/> ML atualizado há 6h · 284 clientes analisados</>}
        title="Churn Monitor"
        subtitle="Clientes em risco de cancelamento identificados pelo modelo de machine learning. Aja nos últimos 30 dias para reverter."
        actions={<>
          <button className="btn btn-outline btn-sm"><Icon name="filter" size={13}/> Filtros</button>
          <button className="btn btn-outline btn-sm"><Icon name="sync" size={13}/> Recalcular</button>
          <button className="btn btn-primary btn-sm"><Icon name="sparkle" size={13}/> Campanha de retenção</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 18 }}>
          <Tile icon="alert" label="Alto risco (≥70)" value="3" sub="R$ 6.140 em MRR" accent="rgba(239,68,68,.2)"/>
          <Tile icon="circleAlert" label="Médio risco (40–70)" value="14" sub="R$ 12.880 em MRR" accent="rgba(245,158,11,.2)"/>
          <Tile icon="shield" label="Baixo risco" value="267" sub="94,0% da base" accent="rgba(34,197,94,.2)"/>
          <Tile icon="trending-up" label="Retenção últimos 30d" value="96,2%" delta="+1,4pp" sub="meta: 97%"/>
        </div>

        <div className="table-wrap">
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div className="sect-title">Clientes em risco</div>
            <span className="sect-sub">Ordenado por score de churn</span>
            <span style={{ flex: 1 }}/>
            <div style={{ position: 'relative' }}>
              <Icon name="search" size={13} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }}/>
              <input placeholder="Buscar cliente..." style={{
                padding: '7px 10px 7px 32px', borderRadius: 8, fontSize: 12.5,
                background: 'var(--bg-1)', border: '1px solid var(--line-2)', color: 'var(--text-1)', width: 220,
              }}/>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Cliente</th>
                <th>Score</th>
                <th>MRR</th>
                <th>Inatividade</th>
                <th>Motivo principal</th>
                <th>Responsável</th>
                <th style={{ textAlign: 'right' }}>Ações</th>
              </tr>
            </thead>
            <tbody>
              {risks.map(r => (
                <tr key={r.id}>
                  <td><b style={{ color: 'var(--text-0)' }}>{r.client}</b></td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ width: 40, height: 6, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{ width: `${r.score}%`, height: '100%', background: levelColor(r.level) }}/>
                      </div>
                      <b style={{ color: levelColor(r.level), fontVariantNumeric: 'tabular-nums' }}>{r.score}</b>
                    </div>
                  </td>
                  <td style={{ fontVariantNumeric: 'tabular-nums' }}>{BRL(r.mrr)}</td>
                  <td style={{ color: 'var(--text-2)' }}>{r.days} dias</td>
                  <td style={{ color: 'var(--text-2)', maxWidth: 360 }}>{r.reason}</td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <Avatar name={r.owner} size={22}/>
                      <span style={{ fontSize: 12 }}>{r.owner.split(' ')[0]}</span>
                    </div>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <button className="btn btn-outline btn-sm" style={{ padding: '5px 10px' }}><Icon name="whatsapp" size={12}/></button>
                    <button className="btn btn-outline btn-sm" style={{ padding: '5px 10px', marginLeft: 4 }}><Icon name="phone" size={12}/></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="tile" style={{ marginTop: 16 }}>
          <div className="tile-head">
            <span style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--brand-gradient)', display: 'grid', placeItems: 'center' }}>
              <Icon name="sparkle" size={15} color="white"/>
            </span>
            <div className="sect-title">Principais fatores no modelo de churn</div>
            <span className="grow"/>
            <span className="chip">Importância relativa</span>
          </div>
          {[
            { f: 'Dias sem login', w: 92 },
            { f: 'Queda de uso de módulos', w: 78 },
            { f: 'Tickets de suporte abertos', w: 64 },
            { f: 'Atraso em pagamentos', w: 56 },
            { f: 'NPS da última pesquisa', w: 44 },
            { f: 'Tempo de contrato restante', w: 31 },
          ].map((f, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '200px 1fr 40px', gap: 14, alignItems: 'center', padding: '7px 0', borderBottom: i < 5 ? '1px solid var(--line-1)' : 'none' }}>
              <div style={{ fontSize: 13, color: 'var(--text-1)' }}>{f.f}</div>
              <div style={{ height: 8, background: 'var(--bg-3)', borderRadius: 4, overflow: 'hidden' }}>
                <div style={{ width: `${f.w}%`, height: '100%', background: 'var(--brand-gradient)', borderRadius: 4 }}/>
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-2)', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{f.w}%</div>
            </div>
          ))}
        </div>
      </PageContainer>
    </AppShell>
  );
};

// ==================== 4. Relatórios ====================
const DashRelatorios = ({ onNavigate }) => {
  const categories = [
    { id: 'fin', label: 'Financeiro', icon: 'wallet', count: 12, color: '#8b5cf6' },
    { id: 'crm', label: 'Comercial', icon: 'target', count: 9, color: '#3b82f6' },
    { id: 'rh', label: 'RH & Folha', icon: 'briefcase', count: 8, color: '#22c55e' },
    { id: 'fis', label: 'Fiscal', icon: 'shield', count: 6, color: '#f59e0b' },
    { id: 'op', label: 'Operacional', icon: 'grid', count: 5, color: '#06b6d4' },
  ];
  const [active, setActive] = React.useState('fin');

  const reportsByCategory = {
    fin: [
      { name: 'DRE Gerencial', desc: 'Demonstrativo de resultados consolidado por centro de custo', freq: 'Mensal', last: '01/04/26' },
      { name: 'Fluxo de Caixa Realizado vs Projetado', desc: 'Comparação de entradas e saídas', freq: 'Semanal', last: '15/04/26' },
      { name: 'Inadimplência por Cliente', desc: 'Faturas em atraso agrupadas', freq: 'Diário', last: '18/04/26' },
      { name: 'Conciliação OFX', desc: 'Divergências entre extrato e sistema', freq: 'Semanal', last: '15/04/26' },
      { name: 'Margem por Produto/Serviço', desc: 'Rentabilidade por SKU', freq: 'Mensal', last: '01/04/26' },
    ],
    crm: [
      { name: 'Funil de Vendas', desc: 'Conversão por etapa do pipeline', freq: 'Semanal', last: '15/04/26' },
      { name: 'Performance por Vendedor', desc: 'Metas, comissões, taxa de fechamento', freq: 'Mensal', last: '01/04/26' },
      { name: 'Análise de Perdas', desc: 'Motivos de perda de oportunidades', freq: 'Mensal', last: '01/04/26' },
    ],
    rh: [
      { name: 'Folha de Pagamento CLT', desc: 'Fechamento mensal com encargos', freq: 'Mensal', last: '25/03/26' },
      { name: 'eSocial — Eventos do Mês', desc: 'Eventos enviados e pendentes', freq: 'Mensal', last: '10/04/26' },
      { name: 'Banco de Horas', desc: 'Saldo por funcionário', freq: 'Mensal', last: '01/04/26' },
    ],
    fis: [
      { name: 'NF-e Emitidas vs Canceladas', desc: 'Relatório fiscal mensal', freq: 'Mensal', last: '01/04/26' },
      { name: 'SPED Fiscal', desc: 'Arquivos EFD ICMS/IPI', freq: 'Mensal', last: '01/04/26' },
    ],
    op: [
      { name: 'Projetos em Andamento', desc: 'Status de entrega e saúde', freq: 'Semanal', last: '15/04/26' },
      { name: 'Tickets de Suporte', desc: 'Volume, SLA, CSAT', freq: 'Semanal', last: '15/04/26' },
    ],
  };

  return (
    <AppShell current="relatorios" onNavigate={onNavigate}>
      <PageContainer
        title="Central de Relatórios"
        subtitle="40+ relatórios pré-configurados e exportáveis em PDF, XLSX ou CSV. Agende para recebê-los por e-mail."
        actions={<>
          <button className="btn btn-outline btn-sm"><Icon name="plus" size={13}/> Criar relatório customizado</button>
        </>}
      >
        {/* Favoritos + recentes */}
        <div className="row-2" style={{ marginBottom: 22 }}>
          <div className="tile">
            <div className="tile-head"><Icon name="star" size={14} color="#f59e0b"/><div className="sect-title">Favoritos</div></div>
            {[
              { name: 'DRE Gerencial · Abril/26', date: 'Executado há 3h' },
              { name: 'Funil de Vendas · Semanal', date: 'Executado hoje' },
              { name: 'Folha CLT · Março/26', date: 'Executado em 25/03' },
            ].map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: i < 2 ? '1px solid var(--line-1)' : 'none' }}>
                <Icon name="file" size={16} color="var(--text-3)"/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-0)' }}>{r.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{r.date}</div>
                </div>
                <button className="btn btn-outline btn-sm" style={{ padding: '5px 10px' }}><Icon name="download" size={12}/></button>
              </div>
            ))}
          </div>
          <div className="tile">
            <div className="tile-head"><Icon name="clock" size={14} color="var(--text-3)"/><div className="sect-title">Agendados</div></div>
            {[
              { name: 'DRE mensal', sched: 'Todo dia 1º · envio para financeiro@padaria...', next: 'Próximo: 01/mai' },
              { name: 'Fluxo de caixa semanal', sched: 'Todas as segundas 08h', next: 'Próximo: 21/abr' },
              { name: 'NPS mensal', sched: 'Último dia útil · CEO + diretoria', next: 'Próximo: 30/abr' },
            ].map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: i < 2 ? '1px solid var(--line-1)' : 'none' }}>
                <span style={{ width: 30, height: 30, borderRadius: 7, background: 'rgba(59,130,246,.14)', color: '#93c5fd', display: 'grid', placeItems: 'center' }}><Icon name="calendar" size={13}/></span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-0)' }}>{r.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{r.sched}</div>
                </div>
                <span className="chip chip-brand" style={{ fontSize: 10.5 }}>{r.next.replace('Próximo: ', '')}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Category tabs + grid */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
          {categories.map(c => (
            <button key={c.id} onClick={() => setActive(c.id)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 8, padding: '10px 14px',
              borderRadius: 10, fontSize: 13, fontWeight: 500,
              background: active === c.id ? 'var(--brand-gradient)' : 'var(--bg-2)',
              border: `1px solid ${active === c.id ? 'transparent' : 'var(--line-2)'}`,
              color: active === c.id ? 'white' : 'var(--text-1)',
            }}>
              <Icon name={c.icon} size={14}/>
              {c.label}
              <span style={{
                background: active === c.id ? 'rgba(255,255,255,.2)' : 'var(--bg-3)',
                color: active === c.id ? 'white' : 'var(--text-3)',
                fontSize: 10, padding: '1px 7px', borderRadius: 999,
              }}>{c.count}</span>
            </button>
          ))}
        </div>

        <div className="row-2">
          {(reportsByCategory[active] || []).map((r, i) => (
            <div key={i} className="tile" style={{ display: 'flex', gap: 14, padding: 16 }}>
              <span style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(139,92,246,.14)', color: '#c4b5fd', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <Icon name="file" size={18}/>
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-0)', marginBottom: 2 }}>{r.name}</div>
                <div style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 8, lineHeight: 1.5 }}>{r.desc}</div>
                <div style={{ display: 'flex', gap: 10, fontSize: 11, color: 'var(--text-3)', alignItems: 'center' }}>
                  <span><Icon name="refresh" size={10}/> {r.freq}</span>
                  <span>·</span>
                  <span>Última exec: {r.last}</span>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <button className="btn btn-primary btn-sm" style={{ padding: '6px 10px', fontSize: 11.5 }}><Icon name="download" size={11}/> Gerar</button>
                <button className="btn btn-outline btn-sm" style={{ padding: '6px 10px', fontSize: 11.5 }}><Icon name="calendar" size={11}/> Agendar</button>
              </div>
            </div>
          ))}
        </div>
      </PageContainer>
    </AppShell>
  );
};

Object.assign(window, {
  DashExecutivo, DashKPIs, DashChurn, DashRelatorios,
  PageContainer, Tile, Spark, Donut, Bars,
});
