// Módulo de Relatórios Gerenciais — exclusivo Admin

const { useState: relState, useMemo: relMemo } = React;

/* ─────────────────────────────────────────────
   Configurações dos 9 relatórios
───────────────────────────────────────────── */
const TERAPEUTAS_OPTS  = ['Todos', 'Dra. Ana Silva', 'Dr. Carlos Mendes'];
const UNIDADES_OPTS    = ['Todas', 'Unidade Centro', 'Unidade Jardins'];
const SALAS_OPTS       = ['Todas', 'Sala 201', 'Sala 202', 'Sala 203'];
const STATUS_CONSULTA  = ['Todos', 'Confirmado', 'Reagendado', 'Cancelado', 'Falta', 'Aguardando'];

const RELATORIOS = [
  {
    id:'atendimentos', label:'Atendimentos', icon:'agenda',
    periodoLabel:'Período',
    extra:[
      { id:'terapeuta',label:'Terapeuta',           opts: TERAPEUTAS_OPTS },
      { id:'status',   label:'Status da Consulta',  opts: STATUS_CONSULTA },
    ],
    cols:['Data','Paciente','Terapeuta','Unidade','Sala','Horário','Status','Tipo de cobrança'],
  },
  {
    id:'faltas', label:'Faltas e Cancelamentos', icon:'pacientes',
    periodoLabel:'Período',
    extra:[
      { id:'terapeuta',    label:'Terapeuta',              opts: TERAPEUTAS_OPTS },
      { id:'responsavel',  label:'Responsável pela Falta', opts:['Todos','Paciente','Terapeuta'] },
      { id:'reagendada',   label:'Reagendada',             opts:['Todos','Sim','Não'] },
    ],
    cols:['Data','Paciente','Terapeuta','Unidade','Sala','Tipo de ocorrência','Responsável','Reagendada'],
  },
  {
    id:'pacientes', label:'Pacientes', icon:'pacientes',
    periodoLabel:'Período de cadastro',
    extra:[
      { id:'terapeuta', label:'Terapeuta', opts: TERAPEUTAS_OPTS },
      { id:'situacao',  label:'Situação',  opts:['Todos','Ativo','Sem consultas recentes'] },
    ],
    cols:['Paciente','Data de cadastro','Terapeuta','Consultas totais','Última consulta','Situação'],
  },
  {
    id:'vinculos', label:'Histórico de Vínculos por Paciente', icon:'pacientes',
    periodoLabel:'Período',
    extra:[
      { id:'paciente',  label:'Paciente',             opts:['Todos','Ana Silva','Jorge Ribeiro','Amanda Viana','Carmem Lúcia'] },
      { id:'terapeuta', label:'Terapeuta',             opts: TERAPEUTAS_OPTS },
      { id:'situacao',  label:'Situação do Vínculo',  opts:['Todos','Ativo','Encerrado'] },
    ],
    cols:['Paciente','Terapeuta','Início do vínculo','Fim do vínculo','Consultas','Situação'],
  },
  {
    id:'ocupacao', label:'Ocupação de Salas', icon:'unidades',
    periodoLabel:'Período',
    extra:[
      { id:'terapeuta', label:'Terapeuta', opts: TERAPEUTAS_OPTS },
    ],
    cols:['Sala','Unidade','Terapeuta','Total de consultas','Horas ocupadas','% Ocupação','Receita gerada (R$)'],
  },
];

/* ─────────────────────────────────────────────
   Dados mock por relatório
───────────────────────────────────────────── */
const MOCK_ROWS = {
  comissoes:[
    ['Dra. Ana Silva',  'Jan–Jun 2026','48','R$ 5.760','30%','R$ 1.728','Pago'],
    ['Dr. Carlos Mendes','Jan–Jun 2026','32','R$ 3.840','30%','R$ 1.152','Pendente'],
  ],
  fluxo:[
    ['02/06/2026','Consulta – Ana Silva',      'Consultas','Entrada','R$ 120,00','R$ 12.340,00'],
    ['03/06/2026','Aluguel Unidade Centro',    'Aluguel',  'Saída',  'R$ 3.500,00','R$ 8.840,00'],
    ['04/06/2026','Consulta – Jorge Ribeiro',  'Consultas','Entrada','R$ 120,00','R$ 8.960,00'],
    ['05/06/2026','Salário – Ana Silva',       'Salários', 'Saída',  'R$ 2.800,00','R$ 6.160,00'],
  ],
  contas:[
    ['Aluguel Unidade Centro','Aluguel',   '17/06/2026','R$ 3.500,00','Pendente','—'],
    ['Fornecedor – Mat. escritório','Material','14/06/2026','R$ 850,00','Em atraso','—'],
    ['Salários – Equipe admin','Salários', '30/06/2026','R$ 12.000,00','Pendente','—'],
  ],
  atendimentos:[
    ['02/06/2026','Ana Silva',    'Dra. Ana Silva',  'Unidade Centro', 'Sala 201','09:00','Confirmado','Avulso'],
    ['02/06/2026','Jorge Ribeiro','Dr. Carlos Mendes','Unidade Centro','Sala 202','10:00','Falta','Pacote'],
    ['03/06/2026','Amanda Viana','Dra. Ana Silva',  'Unidade Jardins','Sala 201','14:00','Confirmado','Avulso'],
  ],
  faltas:[
    ['02/06/2026','Jorge Ribeiro','Dr. Carlos Mendes','Unidade Centro','Sala 202','Falta','Paciente','Sim'],
    ['28/05/2026','Carmem Lúcia','Dra. Ana Silva',  'Unidade Jardins','Sala 201','Cancelamento','Terapeuta','Não'],
  ],
  pacientes:[
    ['Ana Silva',    '10/01/2026','Dra. Ana Silva',  '24','02/06/2026','Ativo'],
    ['Jorge Ribeiro','15/02/2026','Dr. Carlos Mendes','16','02/06/2026','Ativo'],
    ['Amanda Viana', '01/03/2026','Dra. Ana Silva',   '8', '03/06/2026','Ativo'],
    ['Carmem Lúcia', '20/03/2026','Dra. Ana Silva',  '12','20/05/2026','Sem consultas recentes'],
  ],
  vinculos:[
    ['Ana Silva',    'Dra. Ana Silva',  '10/01/2026','—',  '24','Ativo'],
    ['Jorge Ribeiro','Dr. Carlos Mendes','15/02/2026','—', '16','Ativo'],
    ['Carmem Lúcia', 'Dra. Ana Silva',  '20/03/2026','—', '12','Ativo'],
  ],
  receita:[
    ['02/06/2026','Ana Silva',    'Dra. Ana Silva',  'Avulso','—',       '1','R$ 120,00','R$ 0,00', 'R$ 120,00'],
    ['02/06/2026','Jorge Ribeiro','Dr. Carlos Mendes','Pacote','—',       '4','R$ 480,00','R$ 20,00','R$ 460,00'],
    ['03/06/2026','Amanda Viana', 'Dra. Ana Silva',  'Avulso','Conv. XYZ','1','R$ 120,00','R$ 30,00','R$ 90,00'],
  ],
  ocupacao:[
    ['Sala 201','Unidade Centro', 'Dra. Ana Silva',  '32','26,6h','66%','R$ 3.840,00'],
    ['Sala 202','Unidade Centro', 'Dr. Carlos Mendes','20','16,7h','42%','R$ 2.400,00'],
    ['Sala 201','Unidade Jardins','Dra. Ana Silva',  '18','15,0h','38%','R$ 2.160,00'],
  ],
};

/* ─────────────────────────────────────────────
   Exportar CSV (abre no Excel)
───────────────────────────────────────────── */
function exportCSV(relatorio, filters) {
  const cfg  = RELATORIOS.find(r => r.id === relatorio);
  const rows = MOCK_ROWS[relatorio] || [];
  const lines = [cfg.cols.join(';'), ...rows.map(r => r.join(';'))];
  const blob = new Blob([lines.join('\n')], { type:'text/csv;charset=utf-8;' });
  const url  = URL.createObjectURL(blob);
  const a    = document.createElement('a');
  a.href = url; a.download = `${cfg.label}.csv`; a.click();
  URL.revokeObjectURL(url);
}

/* ─────────────────────────────────────────────
   FilterBar — reutilizável
───────────────────────────────────────────── */
function RelFilterBar({ cfg, filters, onChange, onAplicar, onExport }) {
  const sel = { padding:'8px 12px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, background:'white', color:'#374151', cursor:'pointer', outline:'none' };
  const inp = { ...sel, cursor:'default' };

  return (
    <div style={{ background:'white', border:'1px solid #e5e7eb', borderRadius:8, padding:'14px 16px', display:'flex', flexWrap:'wrap', gap:10, alignItems:'flex-end' }}>

      {/* Período */}
      <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
        <label style={{ fontSize:11, fontWeight:600, color:'#6b7280', textTransform:'uppercase', letterSpacing:'.05em' }}>{cfg.periodoLabel}</label>
        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
          <input type="date" value={filters.de||''} onChange={e => onChange('de', e.target.value)} style={inp} />
          <span style={{ fontSize:12, color:'#9ca3af' }}>até</span>
          <input type="date" value={filters.ate||''} onChange={e => onChange('ate', e.target.value)} style={inp} />
        </div>
      </div>

      {/* Unidade */}
      <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
        <label style={{ fontSize:11, fontWeight:600, color:'#6b7280', textTransform:'uppercase', letterSpacing:'.05em' }}>Unidade</label>
        <select value={filters.unidade||'Todas'} onChange={e => onChange('unidade', e.target.value)} style={sel}>
          {UNIDADES_OPTS.map(o => <option key={o}>{o}</option>)}
        </select>
      </div>

      {/* Sala */}
      <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
        <label style={{ fontSize:11, fontWeight:600, color:'#6b7280', textTransform:'uppercase', letterSpacing:'.05em' }}>Sala</label>
        <select value={filters.sala||'Todas'} onChange={e => onChange('sala', e.target.value)} style={sel}>
          {SALAS_OPTS.map(o => <option key={o}>{o}</option>)}
        </select>
      </div>

      {/* Filtros específicos */}
      {cfg.extra.map(f => (
        <div key={f.id} style={{ display:'flex', flexDirection:'column', gap:4 }}>
          <label style={{ fontSize:11, fontWeight:600, color:'#6b7280', textTransform:'uppercase', letterSpacing:'.05em' }}>{f.label}</label>
          <select value={filters[f.id]||f.opts[0]} onChange={e => onChange(f.id, e.target.value)} style={sel}>
            {f.opts.map(o => <option key={o}>{o}</option>)}
          </select>
        </div>
      ))}

      {/* Botões */}
      <div style={{ display:'flex', gap:8, marginLeft:'auto', alignItems:'flex-end' }}>
        <button onClick={onAplicar}
          style={{ padding:'8px 18px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
          Aplicar
        </button>
        <button onClick={onExport}
          style={{ display:'flex', alignItems:'center', gap:6, padding:'8px 14px', background:'white', color:'#374151', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, fontWeight:500, cursor:'pointer' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3"/>
          </svg>
          Exportar Excel (.xlsx)
        </button>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────
   Tabela de resultados
───────────────────────────────────────────── */
function RelTable({ cfg }) {
  const rows = MOCK_ROWS[cfg.id] || [];
  return (
    <div style={{ overflowX:'auto', borderRadius:8, border:'1px solid #e5e7eb' }}>
      <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13 }}>
        <thead>
          <tr style={{ background:'#f8fafc' }}>
            {cfg.cols.map(col => (
              <th key={col} style={{ padding:'10px 14px', textAlign:'left', fontSize:11, fontWeight:700, color:'#6b7280', textTransform:'uppercase', letterSpacing:'.05em', borderBottom:'1px solid #e5e7eb', whiteSpace:'nowrap' }}>
                {col}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.length === 0 ? (
            <tr>
              <td colSpan={cfg.cols.length} style={{ padding:'32px', textAlign:'center', color:'#9ca3af', fontSize:14 }}>
                Nenhum resultado encontrado para os filtros selecionados.
              </td>
            </tr>
          ) : rows.map((row, ri) => (
            <tr key={ri} style={{ borderBottom:'1px solid #f3f4f6', background: ri%2===0 ? 'white' : '#fafafa' }}
              onMouseEnter={e => e.currentTarget.style.background='#f0f7ff'}
              onMouseLeave={e => e.currentTarget.style.background= ri%2===0 ? 'white' : '#fafafa'}>
              {row.map((cell, ci) => (
                <td key={ci} style={{ padding:'10px 14px', color:'#374151', whiteSpace:'nowrap' }}>{cell}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ─────────────────────────────────────────────
   Componentes de gráfico SVG — compactos
───────────────────────────────────────────── */
function BarChart({ data, color = '#3b82f6', title }) {
  const max = Math.max(...data.map(d => d.value), 1);
  const W = 320, H = 120, pL = 28, pB = 22, pT = 8, pR = 8;
  const cW = W - pL - pR, cH = H - pB - pT;
  const step = cW / data.length;
  const bW = step * 0.5;
  return (
    <div>
      {title && <div style={{ fontSize:11, fontWeight:600, color:'#6b7280', marginBottom:4, letterSpacing:'.03em' }}>{title}</div>}
      <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ overflow:'visible' }}>
        {[0,.5,1].map(t => {
          const y = pT + cH*(1-t);
          return <line key={t} x1={pL} y1={y} x2={W-pR} y2={y} stroke="#f0f2f5" strokeWidth="1"/>;
        })}
        {data.map((d, i) => {
          const bH = Math.max((d.value/max)*cH, 2);
          const x  = pL + i*step + (step-bW)/2;
          const y  = pT + cH - bH;
          return (
            <g key={i}>
              <rect x={x} y={y} width={bW} height={bH} fill={color} rx={2} opacity="0.82"/>
              <text x={x+bW/2} y={y-3} textAnchor="middle" fontSize="8" fill="#374151" fontWeight="600">{d.value}</text>
              <text x={x+bW/2} y={H-4} textAnchor="middle" fontSize="8" fill="#9ca3af">{d.label}</text>
            </g>
          );
        })}
        <line x1={pL} y1={pT+cH} x2={W-pR} y2={pT+cH} stroke="#e5e7eb" strokeWidth="1"/>
      </svg>
    </div>
  );
}

function LineChart({ data, color = '#3b82f6', title }) {
  const vals = data.map(d => d.value);
  const max = Math.max(...vals, 1), min = Math.min(...vals, 0);
  const W = 320, H = 120, pL = 32, pB = 22, pT = 8, pR = 8;
  const cW = W-pL-pR, cH = H-pB-pT;
  const xs = data.map((_,i) => pL + (i/(data.length-1||1))*cW);
  const ys = vals.map(v => pT + cH - ((v-min)/(max-min||1))*cH);
  const points = xs.map((x,i) => `${x},${ys[i]}`).join(' ');
  const area = `M${xs[0]},${pT+cH} ` + xs.map((x,i)=>`L${x},${ys[i]}`).join(' ') + ` L${xs[xs.length-1]},${pT+cH} Z`;
  return (
    <div>
      {title && <div style={{ fontSize:11, fontWeight:600, color:'#6b7280', marginBottom:4 }}>{title}</div>}
      <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ overflow:'visible' }}>
        <defs>
          <linearGradient id="lg2" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.15"/>
            <stop offset="100%" stopColor={color} stopOpacity="0"/>
          </linearGradient>
        </defs>
        {[0,.5,1].map(t => <line key={t} x1={pL} y1={pT+cH*(1-t)} x2={W-pR} y2={pT+cH*(1-t)} stroke="#f0f2f5" strokeWidth="1"/>)}
        <path d={area} fill="url(#lg2)"/>
        <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/>
        {xs.map((x,i) => <circle key={i} cx={x} cy={ys[i]} r="2.5" fill={color}/>)}
        {data.map((d,i) => <text key={i} x={xs[i]} y={H-4} textAnchor="middle" fontSize="8" fill="#9ca3af">{d.label}</text>)}
        <line x1={pL} y1={pT+cH} x2={W-pR} y2={pT+cH} stroke="#e5e7eb" strokeWidth="1"/>
      </svg>
    </div>
  );
}

function DonutChart({ data, title }) {
  const total = data.reduce((s,d) => s+d.value, 0) || 1;
  const R=38, cx=46, cy=50, ri=R*0.58;
  let angle = -Math.PI/2;
  const slices = data.map(d => {
    const a = (d.value/total)*2*Math.PI;
    const x1=cx+R*Math.cos(angle), y1=cy+R*Math.sin(angle);
    angle += a;
    const x2=cx+R*Math.cos(angle), y2=cy+R*Math.sin(angle);
    const xi1=cx+ri*Math.cos(angle-a), yi1=cy+ri*Math.sin(angle-a);
    const xi2=cx+ri*Math.cos(angle),   yi2=cy+ri*Math.sin(angle);
    const large = a > Math.PI ? 1 : 0;
    return { ...d, path:`M${x1},${y1} A${R},${R},0,${large},1,${x2},${y2} L${xi2},${yi2} A${ri},${ri},0,${large},0,${xi1},${yi1} Z` };
  });
  return (
    <div>
      {title && <div style={{ fontSize:11, fontWeight:600, color:'#6b7280', marginBottom:4 }}>{title}</div>}
      <svg width="100%" viewBox="0 0 200 100">
        {slices.map((s,i) => <path key={i} d={s.path} fill={s.color} opacity="0.88"/>)}
        <text x={cx} y={cy+4} textAnchor="middle" fontSize="12" fontWeight="700" fill="#111">{total}</text>
        {data.map((d,i) => (
          <g key={i} transform={`translate(100, ${14+i*20})`}>
            <rect x="0" y="-7" width="9" height="9" rx="2" fill={d.color}/>
            <text x="14" y="1" fontSize="10" fill="#374151">{d.label}</text>
            <text x="95" y="1" textAnchor="end" fontSize="10" fontWeight="600" fill="#111">{d.value}</text>
          </g>
        ))}
      </svg>
    </div>
  );
}

function HBarChart({ data, color = '#3b82f6', title, suffix = '' }) {
  const max = Math.max(...data.map(d => d.value), 1);
  return (
    <div>
      {title && <div style={{ fontSize:11, fontWeight:600, color:'#6b7280', marginBottom:6 }}>{title}</div>}
      <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
        {data.map((d,i) => (
          <div key={i} style={{ display:'flex', alignItems:'center', gap:8 }}>
            <div style={{ fontSize:11, color:'#374151', width:110, flexShrink:0, textAlign:'right', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{d.label}</div>
            <div style={{ flex:1, height:16, background:'#f3f4f6', borderRadius:3, overflow:'hidden' }}>
              <div style={{ width:`${(d.value/max)*100}%`, height:'100%', background:color, borderRadius:3, display:'flex', alignItems:'center', paddingLeft:5, transition:'width .4s' }}>
                <span style={{ fontSize:9, color:'white', fontWeight:700, whiteSpace:'nowrap' }}>{d.value}{suffix}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* KPIs e gráficos por relatório */
const REL_VISUALS = {
  comissoes: {
    kpis: [
      { label:'Total pago', value:'R$ 1.728', color:'#16a34a' },
      { label:'Total pendente', value:'R$ 1.152', color:'#d97706' },
      { label:'Consultas realizadas', value:'80', color:'#2563a8' },
    ],
    chart: () => <BarChart title="Comissões por terapeuta (R$)" color="#2563a8"
      data={[{label:'Dra. Ana Silva',value:1728},{label:'Dr. Carlos Mendes',value:1152}]}/>,
  },
  fluxo: {
    kpis: [
      { label:'Total entradas', value:'R$ 240,00', color:'#16a34a' },
      { label:'Total saídas', value:'R$ 6.300,00', color:'#dc2626' },
      { label:'Saldo do período', value:'R$ 6.160,00', color:'#2563a8' },
    ],
    chart: () => <LineChart title="Saldo acumulado" color="#2563a8"
      data={[{label:'02/06',value:12340},{label:'03/06',value:8840},{label:'04/06',value:8960},{label:'05/06',value:6160}]}/>,
  },
  contas: {
    kpis: [
      { label:'Total a pagar', value:'R$ 16.350,00', color:'#d97706' },
      { label:'Em atraso', value:'R$ 850,00', color:'#dc2626' },
      { label:'Contas listadas', value:'3', color:'#2563a8' },
    ],
    chart: () => <DonutChart title="Status das contas" data={[
      { label:'Pendente',  value:2, color:'#f59e0b' },
      { label:'Em atraso', value:1, color:'#ef4444' },
      { label:'Pago',      value:0, color:'#22c55e' },
    ]}/>,
  },
  atendimentos: {
    kpis: [
      { label:'Total de consultas', value:'3', color:'#2563a8' },
      { label:'Confirmadas', value:'2', color:'#16a34a' },
      { label:'Faltas', value:'1', color:'#f97316' },
    ],
    chart: () => <DonutChart title="Consultas por status" data={[
      { label:'Confirmado', value:2, color:'#22c55e' },
      { label:'Falta',      value:1, color:'#f97316' },
    ]}/>,
  },
  faltas: {
    kpis: [
      { label:'Total de ocorrências', value:'2', color:'#dc2626' },
      { label:'Reagendadas', value:'1', color:'#16a34a' },
      { label:'Não reagendadas', value:'1', color:'#d97706' },
    ],
    chart: () => <DonutChart title="Responsável pela falta" data={[
      { label:'Paciente',   value:1, color:'#3b82f6' },
      { label:'Terapeuta',  value:1, color:'#f97316' },
    ]}/>,
  },
  pacientes: {
    kpis: [
      { label:'Total de pacientes', value:'4', color:'#2563a8' },
      { label:'Ativos', value:'3', color:'#16a34a' },
      { label:'Sem consultas recentes', value:'1', color:'#d97706' },
    ],
    chart: () => <BarChart title="Consultas por paciente" color="#22c55e"
      data={[{label:'Ana Silva',value:24},{label:'Jorge Ribeiro',value:16},{label:'Amanda Viana',value:8},{label:'Carmem L.',value:12}]}/>,
  },
  vinculos: {
    kpis: [
      { label:'Vínculos ativos', value:'3', color:'#16a34a' },
      { label:'Encerrados', value:'0', color:'#6b7280' },
      { label:'Consultas totais', value:'52', color:'#2563a8' },
    ],
    chart: () => <HBarChart title="Consultas por paciente" color="#3b82f6"
      data={[{label:'Ana Silva',value:24},{label:'Jorge Ribeiro',value:16},{label:'Carmem Lúcia',value:12}]}/>,
  },
  receita: {
    kpis: [
      { label:'Receita bruta', value:'R$ 720,00', color:'#16a34a' },
      { label:'Descontos', value:'R$ 50,00', color:'#dc2626' },
      { label:'Receita líquida', value:'R$ 670,00', color:'#2563a8' },
    ],
    chart: () => <DonutChart title="Receita por tipo" data={[
      { label:'Avulso', value:2, color:'#3b82f6' },
      { label:'Pacote', value:1, color:'#8b5cf6' },
    ]}/>,
  },
  ocupacao: {
    kpis: [
      { label:'Média de ocupação', value:'49%', color:'#2563a8' },
      { label:'Sala mais ocupada', value:'Sala 201', color:'#16a34a' },
      { label:'Receita total gerada', value:'R$ 8.160,00', color:'#d97706' },
    ],
    chart: () => <HBarChart title="Taxa de ocupação (%)" color="#2563a8" suffix="%"
      data={[{label:'Sala 201 – Centro',value:66},{label:'Sala 202 – Centro',value:42},{label:'Sala 201 – Jardins',value:38}]}/>,
  },
};

/* ─────────────────────────────────────────────
   Página principal
───────────────────────────────────────────── */
function Relatorios() {
  const [selected, setSelected] = relState(null);
  const [filters,  setFilters]  = relState({});
  const [applied,  setApplied]  = relState(false);

  const cfg = RELATORIOS.find(r => r.id === selected);

  const changeFilter = (key, val) => setFilters(f => ({ ...f, [key]: val }));

  const handleSelect = id => {
    setSelected(id);
    setFilters({});
    setApplied(false);
  };

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, background:C.pageBg }}>
      <Topbar title="Relatórios Gerenciais" />
      <div style={{ flex:1, overflowY:'auto', padding:'20px 24px', display:'flex', flexDirection:'column', gap:16 }}>

        {/* Grade de seleção */}
        <div>
          <p style={{ margin:'0 0 12px', fontSize:13, color:'#6b7280' }}>Selecione um relatório para visualizar os filtros e resultados:</p>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:10 }}>
            {RELATORIOS.map(r => (
              <button key={r.id} onClick={() => handleSelect(r.id)}
                style={{
                  display:'flex', alignItems:'center', gap:12, padding:'14px 16px',
                  background: selected===r.id ? '#eff6ff' : 'white',
                  border: `1.5px solid ${selected===r.id ? C.primary : '#e5e7eb'}`,
                  borderRadius:8, cursor:'pointer', textAlign:'left', transition:'all .15s',
                }}>
                <div style={{ width:36, height:36, borderRadius:8, background: selected===r.id ? C.primary : '#f3f4f6', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, transition:'background .15s' }}>
                  <Icon name={r.icon} size={17} color={selected===r.id ? 'white' : '#6b7280'} />
                </div>
                <span style={{ fontSize:13, fontWeight: selected===r.id ? 600 : 400, color: selected===r.id ? C.primary : '#374151', lineHeight:1.3 }}>
                  {r.label}
                </span>
              </button>
            ))}
          </div>
        </div>

        {/* Filtros + Resultados */}
        {cfg && (
          <>
            {/* Separador com título */}
            <div style={{ display:'flex', alignItems:'center', gap:12 }}>
              <h2 style={{ margin:0, fontSize:15, fontWeight:700, color:'#111' }}>{cfg.label}</h2>
              <div style={{ flex:1, height:1, background:'#e5e7eb' }} />
            </div>

            {/* Barra de filtros */}
            <RelFilterBar
              cfg={cfg}
              filters={filters}
              onChange={changeFilter}
              onAplicar={() => setApplied(true)}
              onExport={() => exportCSV(selected, filters)}
            />

            {/* Resultados */}
            {applied ? (
              <>
                <Card style={{ padding:'16px 20px' }}>
                  {/* KPIs + Gráfico lado a lado */}
                  {REL_VISUALS[selected] && (
                    <div style={{ display:'flex', gap:24, marginBottom:16, paddingBottom:16, borderBottom:'1px solid #f0f2f5' }}>
                      {/* KPIs em coluna */}
                      <div style={{ display:'flex', flexDirection:'column', gap:12, flexShrink:0, justifyContent:'center' }}>
                        {REL_VISUALS[selected].kpis.map((k,i) => (
                          <div key={i}>
                            <div style={{ fontSize:10, fontWeight:600, color:'#9ca3af', textTransform:'uppercase', letterSpacing:'.06em' }}>{k.label}</div>
                            <div style={{ fontSize:18, fontWeight:700, color:k.color, marginTop:1 }}>{k.value}</div>
                          </div>
                        ))}
                      </div>
                      {/* Gráfico */}
                      <div style={{ flex:1, minWidth:0 }}>
                        {REL_VISUALS[selected].chart()}
                      </div>
                    </div>
                  )}
                  {/* Tabela */}
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10 }}>
                    <span style={{ fontSize:12, color:'#6b7280' }}>
                      {(MOCK_ROWS[selected]||[]).length} resultado(s)
                      {filters.de && filters.ate && ` · ${filters.de} a ${filters.ate}`}
                    </span>
                    <span style={{ fontSize:11, color:'#d1d5db' }}>Dados de demonstração</span>
                  </div>
                  <RelTable cfg={cfg} />
                </Card>
              </>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'40px', background:'white', borderRadius:8, border:'1px dashed #d1d5db', color:'#9ca3af', gap:8 }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/>
                </svg>
                <span style={{ fontSize:14 }}>Configure os filtros e clique em <strong>Aplicar</strong> para ver os resultados.</span>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Relatorios });
