// Caririaçu Guincho — Relatórios + Configurações Screens

const { useState: useStateR, useEffect: useEffectR } = React;

// ── RELATÓRIOS ─────────────────────────────────────────────────────────────
const RELATORIOS = [
  { id: 'assistencias', icon: 'clipboard', color: '#3B82F6', title: 'Relatório de Assistências', desc: 'Histórico completo de atendimentos, por período, motorista ou seguradora.' },
  { id: 'financeiro',   icon: 'dollar',    color: '#10B981', title: 'Relatório Financeiro',       desc: 'Entradas, saídas e saldo por período. Análise de rentabilidade.' },
  { id: 'motorista',    icon: 'users',     color: '#8B5CF6', title: 'Relatório por Motorista',    desc: 'Performance individual: assistências, valores, tempo médio.' },
  { id: 'seguradora',   icon: 'shield',    color: '#F59E0B', title: 'Relatório por Seguradora',   desc: 'Volume e faturamento por parceira. Comparativo mensal.' },
  { id: 'manutencoes',  icon: 'wrench',    color: '#EF4444', title: 'Relatório de Manutenções',   desc: 'Manutenções da frota com custos e tipos por veículo.' },
];

const RelatoriosScreen = () => {
  const [genModal, setGenModal] = useStateR(false);
  const [selRel, setSelRel] = useStateR(null);
  const [motoristas, setMotoristas] = useStateR([]);
  const [seguradoras, setSeguradoras] = useStateR([]);
  const [stats, setStats] = useStateR({ totalAss: 0, finalizadas: 0, faturamento: 0, ticket: 0, motoristasAtivos: 0, manutencoes: 0 });
  const [form, setForm] = useStateR({ dataIni: new Date(Date.now() - 30 * 86400000).toISOString().slice(0,10), dataFim: new Date().toISOString().slice(0,10), motorista: '', seguradora: '', status: '' });
  const set = (k,v) => setForm(f=>({...f,[k]:v}));

  useEffectR(() => {
    (async () => {
      const [m, s, ass, manut] = await Promise.all([
        db.list('motoristas', { order: 'nome', asc: true }),
        db.list('seguradoras', { order: 'nome', asc: true }),
        db.list('assistencias'),
        db.list('manutencoes'),
      ]);
      setMotoristas(m);
      setSeguradoras(s);
      const finalizadas = ass.filter(a => a.status === 'finalizada');
      const faturamento = finalizadas.reduce((sum, a) => sum + Number(a.valor || 0), 0);
      setStats({
        totalAss: ass.length,
        finalizadas: finalizadas.length,
        faturamento,
        ticket: finalizadas.length > 0 ? faturamento / finalizadas.length : 0,
        motoristasAtivos: m.filter(x => x.status !== 'inativo').length,
        manutencoes: manut.length,
      });
    })();
  }, []);

  const openGen = (rel) => { setSelRel(rel); setGenModal(true); };

  const handleGen = async () => {
    const dataEmissao = new Date().toLocaleDateString('pt-BR');
    const numDoc = `REL-${selRel.id.toUpperCase()}-${Date.now().toString().slice(-6)}`;
    const periodoLabel = `${new Date(form.dataIni).toLocaleDateString('pt-BR')} a ${new Date(form.dataFim).toLocaleDateString('pt-BR')}`;

    let titulo = selRel.title;
    let colunas = [];
    let linhas = [];
    let totaisHTML = '';

    if (selRel.id === 'assistencias') {
      let rows = await db.list('assistencias', { order: 'data' });
      rows = rows.filter(r => {
        const d = new Date(r.data).toISOString().slice(0,10);
        return d >= form.dataIni && d <= form.dataFim;
      });
      if (form.motorista) rows = rows.filter(r => r.motorista_id === parseInt(form.motorista));
      if (form.seguradora) rows = rows.filter(r => r.seguradora_id === parseInt(form.seguradora));
      if (form.status) rows = rows.filter(r => r.status === form.status);
      const total = rows.reduce((s, a) => s + Number(a.valor || 0), 0);
      colunas = ['Nº','Data','Placa','Veículo','Serviço','Cliente','Motorista','Valor','Status'];
      linhas = rows.map(a => [
        `<span style="font-family:'Courier New',monospace; color:#3B82F6; font-weight:600;">${a.numero || '#' + a.id}</span>`,
        new Date(a.data).toLocaleDateString('pt-BR'), a.placa || '', a.veiculo || '', a.servico, a.cliente, (a.motorista_nome || '').split(' ')[0],
        `<span style="color:#10B981; font-family:'Courier New',monospace; font-weight:600;">R$ ${Number(a.valor).toFixed(2)}</span>`,
        `<span class="badge badge-${a.status}">${a.status}</span>`
      ]);
      totaisHTML = `<div class="totals-row"><span>Total de registros</span><span style="font-weight:700;">${rows.length}</span></div><div class="totals-row liquido"><span>FATURAMENTO TOTAL</span><span style="color:#10B981; font-family:'Courier New',monospace;">R$ ${total.toFixed(2)}</span></div>`;
    } else if (selRel.id === 'financeiro') {
      let rows = await db.list('transacoes', { order: 'data' });
      rows = rows.filter(r => r.data >= form.dataIni && r.data <= form.dataFim);
      const ent = rows.filter(t => t.tipo === 'entrada').reduce((s,t) => s + Number(t.valor || 0), 0);
      const sai = rows.filter(t => t.tipo === 'saida').reduce((s,t) => s + Number(t.valor || 0), 0);
      colunas = ['Data','Descrição','Categoria','Tipo','Valor'];
      linhas = rows.map(t => [
        new Date(t.data).toLocaleDateString('pt-BR'), t.descricao, t.categoria || '—',
        `<span class="badge badge-${t.tipo}">${t.tipo}</span>`,
        `<span style="color:${t.tipo === 'entrada' ? '#10B981' : '#EF4444'}; font-family:'Courier New',monospace; font-weight:600;">${t.tipo === 'entrada' ? '+' : '−'} R$ ${Number(t.valor).toFixed(2)}</span>`
      ]);
      totaisHTML = `<div class="totals-row" style="color:#10B981;"><span>Total Entradas</span><span style="font-family:'Courier New',monospace;">R$ ${ent.toFixed(2)}</span></div><div class="totals-row" style="color:#EF4444;"><span>Total Saídas</span><span style="font-family:'Courier New',monospace;">R$ ${sai.toFixed(2)}</span></div><div class="totals-row liquido"><span>SALDO</span><span style="color:${ent-sai>=0?'#10B981':'#EF4444'}; font-family:'Courier New',monospace;">R$ ${(ent-sai).toFixed(2)}</span></div>`;
    } else if (selRel.id === 'motorista') {
      const rows = await db.list('motoristas', { order: 'nome', asc: true });
      colunas = ['Motorista','Telefone','CNH','Categoria','Guincho','Assistências','Status'];
      linhas = rows.map(m => [
        m.nome, m.telefone || '—', m.cnh || '—', m.categoria ? `Cat. ${m.categoria}` : '—', m.guincho_code || '—',
        `<span style="font-family:'Courier New',monospace; font-weight:600;">${m.assistencias || 0}</span>`,
        `<span class="badge badge-${m.status}">${m.status}</span>`
      ]);
    } else if (selRel.id === 'seguradora') {
      const rows = await db.list('seguradoras', { order: 'nome', asc: true });
      const totalFat = rows.reduce((s, r) => s + Number(r.faturamento || 0), 0);
      colunas = ['Seguradora','Contato','Telefone','Email','Assist./mês','Faturamento','Status'];
      linhas = rows.map(s => [
        s.nome, s.contato || '—', s.telefone || '—', s.email || '—',
        `<span style="font-family:'Courier New',monospace; font-weight:600;">${s.assistencias_mes || 0}</span>`,
        `<span style="color:#10B981; font-family:'Courier New',monospace; font-weight:600;">R$ ${Number(s.faturamento).toFixed(2)}</span>`,
        `<span class="badge badge-${s.status}">${s.status}</span>`
      ]);
      totaisHTML = `<div class="totals-row liquido"><span>FATURAMENTO TOTAL</span><span style="color:#10B981; font-family:'Courier New',monospace;">R$ ${totalFat.toFixed(2)}</span></div>`;
    } else if (selRel.id === 'manutencoes') {
      let rows = await db.list('manutencoes', { order: 'data' });
      rows = rows.filter(r => r.data >= form.dataIni && r.data <= form.dataFim);
      const total = rows.reduce((s, m) => s + Number(m.valor || 0), 0);
      colunas = ['Data','Guincho','Tipo','Descrição','Oficina','Valor'];
      linhas = rows.map(m => [
        new Date(m.data).toLocaleDateString('pt-BR'), m.guincho_code || '—',
        `<span class="badge badge-${m.tipo === 'Preventiva' ? 'preventiva' : 'corretiva'}">${m.tipo}</span>`,
        m.descricao, m.oficina || '—',
        `<span style="color:#EF4444; font-family:'Courier New',monospace; font-weight:600;">R$ ${Number(m.valor).toFixed(2)}</span>`
      ]);
      totaisHTML = `<div class="totals-row liquido"><span>TOTAL EM MANUTENÇÕES</span><span style="color:#EF4444; font-family:'Courier New',monospace;">R$ ${total.toFixed(2)}</span></div>`;
    }

    const linhasHTML = linhas.length === 0
      ? `<tr><td colspan="${colunas.length}" style="text-align:center; color:#94A3B8; padding:24px;">Nenhum registro encontrado para os filtros selecionados</td></tr>`
      : linhas.map(l => `<tr>${l.map(c => `<td>${c}</td>`).join('')}</tr>`).join('');

    const html = `<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><title>${titulo}</title>
<link rel="icon" type="image/png" href="${window.location.origin}/logo.png" />
<style>
  * { margin:0; padding:0; box-sizing:border-box; }
  body { font-family:'Segoe UI',Arial,sans-serif; color:#0F172A; padding:30px; background:#fff; }
  .doc { max-width:1100px; margin:0 auto; border:2px solid #0F172A; }
  .header { background:linear-gradient(135deg,#1E293B,#0F172A); color:#fff; padding:24px 28px; display:flex; justify-content:space-between; align-items:center; }
  .header h1 { font-size:22px; font-weight:700; }
  .header .logo { display:flex; align-items:center; gap:12px; }
  .header .logo img { width:56px; height:56px; border-radius:50%; object-fit:cover; transform:scale(1.08); box-shadow:0 0 0 2px rgba(245,158,11,0.6); }
  .header .logo-text { font-size:11px; opacity:0.8; letter-spacing:1px; text-transform:uppercase; }
  .meta { padding:16px 28px; background:#F8FAFC; border-bottom:1px solid #E2E8F0; display:grid; grid-template-columns:repeat(3,1fr); gap:12px; font-size:12px; }
  .meta-label { color:#64748B; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; font-size:10px; }
  .meta-value { color:#0F172A; font-weight:600; margin-top:2px; }
  .body-content { padding:18px 28px; }
  table { width:100%; border-collapse:collapse; font-size:11px; }
  th { background:#F8FAFC; padding:10px 12px; text-align:left; font-size:11px; color:#64748B; text-transform:uppercase; letter-spacing:0.5px; border-bottom:2px solid #E2E8F0; }
  td { padding:8px 12px; font-size:11px; border-bottom:1px solid #F1F5F9; color:#374151; }
  tbody tr:nth-child(even) { background:#F8FAFC; }
  .badge { display:inline-block; padding:2px 7px; border-radius:5px; font-size:10px; font-weight:700; }
  .badge-aberta { background:#EFF6FF; color:#2563EB; }
  .badge-atendimento { background:#FFFBEB; color:#B45309; }
  .badge-finalizada, .badge-ativo, .badge-disponivel { background:#ECFDF5; color:#047857; }
  .badge-cancelada { background:#FEF2F2; color:#DC2626; }
  .badge-agendada { background:#F5F3FF; color:#7C3AED; }
  .badge-inativo { background:#F1F5F9; color:#64748B; }
  .badge-entrada { background:#ECFDF5; color:#047857; }
  .badge-saida { background:#FEF2F2; color:#DC2626; }
  .badge-preventiva { background:#ECFDF5; color:#047857; }
  .badge-corretiva { background:#FEF2F2; color:#DC2626; }
  .totals { padding:18px 28px; background:#F8FAFC; }
  .totals-row { display:flex; justify-content:space-between; padding:6px 0; font-size:14px; }
  .totals-row.liquido { border-top:2px solid #0F172A; margin-top:10px; padding-top:14px; font-size:18px; font-weight:800; }
  .footer { padding:18px 28px; text-align:center; font-size:11px; color:#94A3B8; }
  .print-btn { position:fixed; top:20px; right:20px; background:#F59E0B; color:#0F172A; border:none; padding:12px 22px; border-radius:8px; font-size:14px; font-weight:700; cursor:pointer; box-shadow:0 4px 12px rgba(0,0,0,0.15); }
  @media print { body { padding:0; } .print-btn { display:none; } .doc { border:1px solid #0F172A; } @page { size: landscape; } }
</style></head><body>
<button class="print-btn" onclick="window.print()">📥 Salvar como PDF / Imprimir</button>
<div class="doc">
  <div class="header">
    <div class="logo"><img src="${window.location.origin}/logo.png" alt="Caririaçu Guincho" /><div><h1>Caririaçu Guincho</h1><div class="logo-text">${titulo}</div></div></div>
    <div style="text-align:right; font-size:12px;"><div style="opacity:0.8;">Nº ${numDoc}</div><div style="margin-top:4px; font-weight:600;">${dataEmissao}</div></div>
  </div>
  <div class="meta">
    <div><div class="meta-label">Período</div><div class="meta-value">${periodoLabel}</div></div>
    <div><div class="meta-label">Registros</div><div class="meta-value">${linhas.length}</div></div>
    <div><div class="meta-label">Emissão</div><div class="meta-value">${dataEmissao}</div></div>
  </div>
  <div class="body-content">
    <table>
      <thead><tr>${colunas.map(c => `<th>${c}</th>`).join('')}</tr></thead>
      <tbody>${linhasHTML}</tbody>
    </table>
  </div>
  ${totaisHTML ? `<div class="totals">${totaisHTML}</div>` : ''}
  <div class="footer">Relatório gerado em ${dataEmissao} · Caririaçu Guincho · Rapidez · Segurança · Confiança · ${numDoc}</div>
</div>
<script>setTimeout(() => window.print(), 400);</script>
</body></html>`;

    const win = window.open('', '_blank', 'width=1100,height=900');
    if (!win) { showToast('Habilite popups para gerar o PDF', 'warning'); return; }
    win.document.write(html); win.document.close();
    showToast(`${titulo} gerado`, 'success');
    setGenModal(false);
  };

  const fmtBRL = v => Number(v || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL', maximumFractionDigits: 0 });

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:24 }}>
      <div>
        <h1 style={{ margin:0, fontSize:22, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif' }}>Relatórios</h1>
        <span style={{ fontSize:13, color:'#64748B' }}>Exporte dados em PDF com layout profissional</span>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))', gap:16 }}>
        {RELATORIOS.map(rel => (
          <Card key={rel.id} style={{ padding:24, cursor:'pointer', transition:'all 0.2s' }}
            onClick={() => openGen(rel)}
            onMouseEnter={e=>{ e.currentTarget.style.boxShadow=`0 8px 24px ${rel.color}25`; e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.borderColor=rel.color+'50'; }}
            onMouseLeave={e=>{ e.currentTarget.style.boxShadow='0 1px 3px rgba(0,0,0,0.07)'; e.currentTarget.style.transform=''; e.currentTarget.style.borderColor='#E2E8F0'; }}>
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div style={{ width:48,height:48,borderRadius:12,background:rel.color+'18',display:'flex',alignItems:'center',justifyContent:'center' }}>
                <Icon name={rel.icon} size={22} color={rel.color}/>
              </div>
              <div>
                <div style={{ fontSize:15, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif', marginBottom:4 }}>{rel.title}</div>
                <div style={{ fontSize:13, color:'#64748B', lineHeight:1.5 }}>{rel.desc}</div>
              </div>
              <Btn variant="primary" size="sm" icon="download" onClick={(e) => { e.stopPropagation(); openGen(rel); }} style={{ alignSelf:'flex-start' }}>Gerar Relatório</Btn>
            </div>
          </Card>
        ))}
      </div>

      <Card style={{ padding:20 }}>
        <div style={{ fontSize:15, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif', marginBottom:14 }}>Resumo Geral</div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(130px,1fr))', gap:16 }}>
          {[
            { label:'Total Assistências', val: stats.totalAss, color:'#3B82F6' },
            { label:'Finalizadas', val: stats.finalizadas, color:'#10B981' },
            { label:'Faturamento', val: fmtBRL(stats.faturamento), color:'#F59E0B' },
            { label:'Ticket Médio', val: fmtBRL(stats.ticket), color:'#8B5CF6' },
            { label:'Motoristas Ativos', val: stats.motoristasAtivos, color:'#64748B' },
            { label:'Manutenções', val: stats.manutencoes, color:'#EF4444' },
          ].map(s=>(
            <div key={s.label} style={{ textAlign:'center', padding:'12px 8px', background:'#F8FAFC', borderRadius:10 }}>
              <div style={{ fontSize:18, fontWeight:700, color:s.color, fontFamily:'DM Mono, monospace' }}>{s.val}</div>
              <div style={{ fontSize:11, color:'#64748B', marginTop:4 }}>{s.label}</div>
            </div>
          ))}
        </div>
      </Card>

      <Modal open={genModal} onClose={()=>setGenModal(false)} title={selRel ? `Gerar: ${selRel.title}` : ''} width={500}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <Input label="Data Inicial" type="date" value={form.dataIni} onChange={e=>set('dataIni',e.target.value)}/>
            <Input label="Data Final" type="date" value={form.dataFim} onChange={e=>set('dataFim',e.target.value)}/>
          </div>
          {(selRel?.id === 'motorista' || selRel?.id === 'assistencias') && (
            <Select label="Motorista (opcional)" value={form.motorista} onChange={e=>set('motorista',e.target.value)}
              options={[{value:'',label:'Todos os motoristas'},...motoristas.map(m=>({value:m.id,label:m.nome}))]}/>
          )}
          {(selRel?.id === 'seguradora' || selRel?.id === 'assistencias') && (
            <Select label="Seguradora (opcional)" value={form.seguradora} onChange={e=>set('seguradora',e.target.value)}
              options={[{value:'',label:'Todas as seguradoras'},...seguradoras.map(s=>({value:s.id,label:s.nome}))]}/>
          )}
          {selRel?.id === 'assistencias' && (
            <Select label="Status (opcional)" value={form.status} onChange={e=>set('status',e.target.value)}
              options={[{value:'',label:'Todos'},{value:'finalizada',label:'Finalizadas'},{value:'cancelada',label:'Canceladas'},{value:'aberta',label:'Abertas'}]}/>
          )}
          <div style={{ background:'#EFF6FF', borderRadius:10, padding:'10px 14px', fontSize:12, color:'#1D4ED8', display:'flex', gap:8 }}>
            <Icon name="fileText" size={14} color="#3B82F6"/>
            O PDF será aberto em uma nova aba com cabeçalho, tabela de dados e rodapé profissional.
          </div>
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:8, borderTop:'1px solid #F1F5F9' }}>
            <Btn variant="secondary" onClick={()=>setGenModal(false)}>Cancelar</Btn>
            <Btn variant="primary" icon="download" onClick={handleGen}>Exportar PDF</Btn>
          </div>
        </div>
      </Modal>
    </div>
  );
};

// ── CONFIGURAÇÕES ──────────────────────────────────────────────────────────
const ConfigScreen = () => {
  const [activeTab, setActiveTab] = useStateR('empresa');
  const [isMobileCfg, setIsMobileCfg] = useStateR(window.innerWidth < 768);
  const [navOpen, setNavOpen] = useStateR(false);

  useEffectR(() => {
    const handler = () => setIsMobileCfg(window.innerWidth < 768);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  const [empresa, setEmpresa] = useStateR({ nome: 'Caririaçu Guincho', cnpj: '', telefone: '', email: '', endereco: '' });
  const [empresaId, setEmpresaId] = useStateR(1);
  const [users, setUsers] = useStateR([]);
  const [categorias, setCategorias] = useStateR([]);
  const [alertConfig, setAlertConfig] = useStateR({ id: 1, horas_aberta: 4, email_enabled: true, vistoria_pendente: true, manutencao_alert: false });
  const [editingCat, setEditingCat] = useStateR(null);
  const [editingCatVal, setEditingCatVal] = useStateR('');
  const [novaCat, setNovaCat] = useStateR('');
  const [showNovaCat, setShowNovaCat] = useStateR(false);
  const [userModal, setUserModal] = useStateR(false);
  const [editingUser, setEditingUser] = useStateR(null);
  const [userForm, setUserForm] = useStateR({ nome:'', email:'', cargo:'Operador', status:'ativo' });

  const setEmp = (k, v) => setEmpresa(e => ({ ...e, [k]: v }));
  const setUF = (k, v) => setUserForm(f => ({ ...f, [k]: v }));

  useEffectR(() => {
    (async () => {
      const [emp] = await db.list('empresa');
      if (emp) { setEmpresa(emp); setEmpresaId(emp.id); }
      setUsers(await db.list('usuarios', { order: 'nome', asc: true }));
      const cats = await db.list('categorias_financeiras', { order: 'nome', asc: true });
      setCategorias(cats.map(c => c.nome));
      const [conf] = await db.list('config_alertas');
      if (conf) setAlertConfig(conf);
    })();
  }, []);

  const saveEmpresa = async () => {
    const updated = await db.update('empresa', empresaId, {
      nome: empresa.nome, cnpj: empresa.cnpj, telefone: empresa.telefone,
      email: empresa.email, endereco: empresa.endereco, updated_at: new Date().toISOString()
    });
    if (updated) showToast('Dados da empresa salvos!', 'success');
  };

  const saveAlertas = async () => {
    const updated = await db.update('config_alertas', 1, {
      horas_aberta: alertConfig.horas_aberta,
      email_enabled: alertConfig.email_enabled,
      vistoria_pendente: alertConfig.vistoria_pendente,
      manutencao_alert: alertConfig.manutencao_alert,
      updated_at: new Date().toISOString()
    });
    if (updated) showToast('Alertas salvos!', 'success');
  };

  const addCategoria = async (nome) => {
    if (!nome.trim()) return;
    const created = await db.insert('categorias_financeiras', { nome: nome.trim(), tipo: 'ambos' });
    if (created) { setCategorias(c => [...c, created.nome]); showToast('Categoria adicionada!', 'success'); }
  };
  const removeCategoria = async (nome) => {
    const all = await db.list('categorias_financeiras', { eq: { nome } });
    if (all[0]) {
      const ok = await db.remove('categorias_financeiras', all[0].id);
      if (ok) { setCategorias(c => c.filter(x => x !== nome)); showToast(`"${nome}" removida`, 'warning'); }
    }
  };
  const renameCategoria = async (oldName, newName) => {
    if (!newName.trim()) return;
    const all = await db.list('categorias_financeiras', { eq: { nome: oldName } });
    if (all[0]) {
      const updated = await db.update('categorias_financeiras', all[0].id, { nome: newName.trim() });
      if (updated) { setCategorias(c => c.map(x => x === oldName ? newName.trim() : x)); showToast('Categoria atualizada!', 'success'); }
    }
  };

  const TABS = [
    { id:'empresa', label:'Empresa', icon:'building' },
    { id:'usuarios', label:'Usuários', icon:'users' },
    { id:'categorias', label:'Categorias', icon:'clipboard' },
    { id:'alertas', label:'Alertas', icon:'bell' },
    { id:'combustiveis',  label:'Combustíveis',        icon:'zap' },
    { id:'tipos-despesa', label:'Tipos de despesa',    icon:'dollar' },
    { id:'postos',        label:'Postos',              icon:'map' },
    { id:'checklists',    label:'Templates checklist', icon:'clipboard' },
    { id:'backup', label:'Backup', icon:'download' },
  ];

  // Backup
  const [backupRunning, setBackupRunning] = useStateR(false);
  const [lastBackup, setLastBackup] = useStateR(localStorage.getItem('caririacu_last_backup') || null);

  const fazerBackup = async () => {
    setBackupRunning(true);
    try {
      showToast('Gerando backup completo...', 'info');
      const tabelas = ['empresa','usuarios','motoristas','frota','seguradoras','assistencias','manutencoes','transacoes','categorias_financeiras','config_alertas','vistorias'];
      const dados = {};
      for (const t of tabelas) {
        dados[t] = await db.list(t);
      }
      const backup = {
        empresa: 'Caririaçu Guincho',
        gerado_em: new Date().toISOString(),
        gerado_em_br: new Date().toLocaleString('pt-BR'),
        versao: '1.0',
        total_registros: Object.values(dados).reduce((s, arr) => s + arr.length, 0),
        dados,
      };

      const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      const dataStr = new Date().toISOString().slice(0,10);
      a.href = url;
      a.download = `backup-caririacu-${dataStr}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      const agora = new Date().toISOString();
      localStorage.setItem('caririacu_last_backup', agora);
      setLastBackup(agora);
      showToast(`Backup gerado! ${backup.total_registros} registros salvos`, 'success');
    } catch (e) {
      showToast('Erro ao gerar backup', 'error');
      console.error(e);
    }
    setBackupRunning(false);
  };

  const diasDesdeUltimoBackup = lastBackup
    ? Math.floor((new Date() - new Date(lastBackup)) / (1000 * 60 * 60 * 24))
    : null;

  const openNewUser = () => { setEditingUser(null); setUserForm({ nome:'', email:'', cargo:'Operador', status:'ativo' }); setUserModal(true); };
  const openEditUser = (u) => { setEditingUser(u); setUserForm({ nome:u.nome, email:u.email, cargo:u.cargo, status:u.status }); setUserModal(true); };
  const saveUser = async () => {
    if (!userForm.nome || !userForm.email) { showToast('Preencha nome e e-mail', 'warning'); return; }
    if (editingUser) {
      const updated = await db.update('usuarios', editingUser.id, { nome: userForm.nome, cargo: userForm.cargo, status: userForm.status });
      if (updated) {
        setUsers(us => us.map(u => u.id === editingUser.id ? { ...u, ...userForm } : u));
        showToast(`${userForm.nome} atualizado`, 'success');
      }
    } else {
      showToast('Para convidar, peça ao novo usuário para se cadastrar via tela de login (em breve: convite por e-mail)', 'info');
    }
    setUserModal(false);
  };
  const toggleUserStatus = async (u) => {
    const novoStatus = u.status === 'inativo' ? 'ativo' : 'inativo';
    const updated = await db.update('usuarios', u.id, { status: novoStatus });
    if (updated) { setUsers(us => us.map(x => x.id === u.id ? { ...x, status: novoStatus } : x)); showToast('Status atualizado', 'success'); }
  };

  const tabAtual = TABS.find(t => t.id === activeTab) || TABS[0];
  const tabButtonStyle = (active) => ({
    display:'flex', alignItems:'center', gap:10, padding:'10px 12px',
    borderRadius:8, border:'none', cursor:'pointer', width:'100%',
    background: active ? 'rgba(245,158,11,0.1)' : 'transparent',
    color: active ? '#B45309' : '#64748B',
    fontWeight: active ? 600 : 400, fontSize:14,
    fontFamily:'Inter, sans-serif', transition:'all 0.15s', textAlign:'left'
  });

  return (
    <div style={{
      padding: isMobileCfg ? 16 : 28,
      display:'flex', flexDirection: isMobileCfg ? 'column' : 'row',
      gap: isMobileCfg ? 12 : 24
    }}>
      {isMobileCfg ? (
        <div style={{ position:'relative', zIndex: 50 }}>
          <button onClick={() => setNavOpen(o => !o)} style={{
            width:'100%', padding:'12px 14px', borderRadius:10,
            border:'1px solid #E2E8F0', background:'#fff',
            display:'flex', alignItems:'center', justifyContent:'space-between',
            fontSize:14, fontWeight:600, color:'#0F172A', cursor:'pointer',
            fontFamily:'Inter, sans-serif'
          }}>
            <span style={{ display:'flex', alignItems:'center', gap:10 }}>
              <Icon name={tabAtual.icon} size={16} color="#F59E0B"/>
              {tabAtual.label}
            </span>
            <span style={{ color:'#94A3B8', fontSize:12 }}>{navOpen ? '▲' : '▼'}</span>
          </button>
          {navOpen && (
            <>
              <div onClick={() => setNavOpen(false)} style={{
                position:'fixed', inset:0, zIndex:49, background:'transparent'
              }}/>
              <Card style={{
                position:'absolute', top:'100%', left:0, right:0, marginTop:4, zIndex:50,
                padding:8, display:'flex', flexDirection:'column', gap:2,
                boxShadow:'0 8px 24px rgba(0,0,0,0.08)'
              }}>
                {TABS.map(t => (
                  <button key={t.id}
                    onClick={() => { setActiveTab(t.id); setNavOpen(false); }}
                    style={tabButtonStyle(activeTab === t.id)}>
                    <Icon name={t.icon} size={16} color={activeTab===t.id?'#F59E0B':'#94A3B8'}/>
                    {t.label}
                  </button>
                ))}
              </Card>
            </>
          )}
        </div>
      ) : (
        <div style={{ width:200, flexShrink:0 }}>
          <Card style={{ padding:8, display:'flex', flexDirection:'column', gap:2 }}>
            {TABS.map(t=>(
              <button key={t.id} onClick={()=>setActiveTab(t.id)} style={tabButtonStyle(activeTab===t.id)}>
                <Icon name={t.icon} size={16} color={activeTab===t.id?'#F59E0B':'#94A3B8'}/>
                {t.label}
              </button>
            ))}
          </Card>
        </div>
      )}

      <div style={{ flex:1, minWidth:0 }}>
        {activeTab === 'empresa' && (
          <Card style={{ padding:24 }}>
            <h2 style={{ margin:'0 0 20px', fontSize:17, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif' }}>Dados da Empresa</h2>
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
                <Input label="Nome da Empresa" placeholder="Caririaçu Guincho Ltda." value={empresa.nome || ''} onChange={e => setEmp('nome', e.target.value)}/>
                <Input label="CNPJ" placeholder="00.000.000/0001-00" value={empresa.cnpj || ''} onChange={e => setEmp('cnpj', e.target.value)}/>
                <Input label="Telefone" placeholder="(88) 3000-0000" value={empresa.telefone || ''} onChange={e => setEmp('telefone', e.target.value)}/>
                <Input label="E-mail" placeholder="contato@empresa.com.br" value={empresa.email || ''} onChange={e => setEmp('email', e.target.value)}/>
              </div>
              <Input label="Endereço Completo" placeholder="Rua Industrial, 500 — Caririaçu, CE" value={empresa.endereco || ''} onChange={e => setEmp('endereco', e.target.value)}/>
              <div style={{ display:'flex', alignItems:'center', gap:14, padding:14, background:'#F8FAFC', borderRadius:10, border:'1px solid #E2E8F0' }}>
                <img src="logo.png" alt="Logo" style={{ width:56, height:56, borderRadius:'50%', objectFit:'cover', transform:'scale(1.08)', boxShadow:'0 0 0 2px rgba(245,158,11,0.6)', flexShrink:0 }}/>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:'#0F172A' }}>Logo da empresa</div>
                  <div style={{ fontSize:11, color:'#64748B', marginTop:2 }}>Para alterar, substitua o arquivo <code style={{ background:'#E2E8F0', padding:'1px 5px', borderRadius:3, fontSize:11 }}>logo.png</code> na pasta do projeto</div>
                </div>
              </div>
              <Btn variant="primary" icon="check" onClick={saveEmpresa} style={{ alignSelf:'flex-start' }}>Salvar Alterações</Btn>
            </div>
          </Card>
        )}

        {activeTab === 'usuarios' && (
          <Card style={{ padding:0, overflow:'hidden' }}>
            <div style={{ padding:'16px 20px', borderBottom:'1px solid #F1F5F9', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <h2 style={{ margin:0, fontSize:17, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif' }}>Usuários e Permissões</h2>
              <Btn variant="primary" size="sm" icon="plus" onClick={openNewUser}>Convidar</Btn>
            </div>
            {users.length === 0 ? (
              <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>Nenhum usuário cadastrado ainda.</div>
            ) : (
              <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13 }}>
                <thead><tr style={{ background:'#F8FAFC' }}>
                  {['Usuário','Email','Cargo','Status','Ações'].map(h=><th key={h} style={{ padding:'10px 16px', textAlign:'left', fontSize:12, fontWeight:600, color:'#64748B', borderBottom:'1px solid #E2E8F0' }}>{h}</th>)}
                </tr></thead>
                <tbody>
                  {users.map((u,i)=>(
                    <tr key={u.id} style={{ background:i%2?'#F8FAFC':'#fff' }}>
                      <td style={{ padding:'12px 16px' }}><div style={{ display:'flex',alignItems:'center',gap:10 }}><Avatar initials={u.nome.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()} size={30}/><span style={{ fontWeight:600,color:'#0F172A' }}>{u.nome}</span></div></td>
                      <td style={{ padding:'12px 16px',color:'#3B82F6',fontSize:12 }}>{u.email}</td>
                      <td style={{ padding:'12px 16px' }}><span style={{ background:'#EFF6FF',color:'#2563EB',borderRadius:6,padding:'2px 9px',fontSize:12,fontWeight:600 }}>{u.cargo}</span></td>
                      <td style={{ padding:'12px 16px' }}><StatusBadge status={u.status}/></td>
                      <td style={{ padding:'12px 16px' }}>
                        <div style={{ display:'flex', gap:4 }}>
                          <button title="Editar" onClick={() => openEditUser(u)} style={{ background:'none',border:'none',cursor:'pointer',color:'#64748B',padding:4,borderRadius:6 }} onMouseEnter={e=>e.currentTarget.style.background='#F1F5F9'} onMouseLeave={e=>e.currentTarget.style.background='none'}><Icon name="edit" size={15}/></button>
                          <button title={u.status==='inativo'?'Ativar':'Inativar'} onClick={() => toggleUserStatus(u)} style={{ background:'none',border:'none',cursor:'pointer',color:u.status==='inativo'?'#10B981':'#EF4444',padding:4,borderRadius:6 }} onMouseEnter={e=>e.currentTarget.style.background='#F8FAFC'} onMouseLeave={e=>e.currentTarget.style.background='none'}><Icon name={u.status==='inativo'?'check':'x'} size={15}/></button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </Card>
        )}

        {activeTab === 'alertas' && (
          <Card style={{ padding:24 }}>
            <h2 style={{ margin:'0 0 20px', fontSize:17, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif' }}>Configuração de Alertas</h2>
            <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
              <div style={{ padding:'18px 20px', background:'#F8FAFC', borderRadius:12, border:'1px solid #E2E8F0' }}>
                <div style={{ fontWeight:600, color:'#0F172A', marginBottom:6 }}>Alerta de Assistência Aberta</div>
                <div style={{ fontSize:13, color:'#64748B', marginBottom:16 }}>Notificar quando uma assistência ficar aberta sem atualização por:</div>
                <div style={{ display:'flex', alignItems:'center', gap:16 }}>
                  <input type="range" min="1" max="12" value={alertConfig.horas_aberta} onChange={e=>setAlertConfig(c => ({ ...c, horas_aberta: +e.target.value }))} style={{ flex:1, accentColor:'#F59E0B' }}/>
                  <span style={{ fontSize:20, fontWeight:700, color:'#F59E0B', fontFamily:'DM Mono, monospace', minWidth:60 }}>{alertConfig.horas_aberta}h</span>
                </div>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:11, color:'#94A3B8', marginTop:4 }}>
                  <span>1 hora</span><span>12 horas</span>
                </div>
              </div>
              {[
                { key: 'email_enabled', label:'Notificação por email', desc:'Enviar email para administradores quando alerta disparar' },
                { key: 'vistoria_pendente', label:'Alerta de vistoria pendente', desc:'Avisar quando assistência não tem vistoria após 30 min' },
                { key: 'manutencao_alert', label:'Alerta de manutenção', desc:'Notificar quando guincho está em manutenção há mais de 48h' },
              ].map(a=>(
                <div key={a.key} style={{ padding:'16px 20px', background:'#F8FAFC', borderRadius:12, border:'1px solid #E2E8F0', display:'flex', alignItems:'center', justifyContent:'space-between', gap:16 }}>
                  <div>
                    <div style={{ fontWeight:600, color:'#0F172A', marginBottom:2 }}>{a.label}</div>
                    <div style={{ fontSize:12, color:'#64748B' }}>{a.desc}</div>
                  </div>
                  <div onClick={() => setAlertConfig(c => ({ ...c, [a.key]: !c[a.key] }))} style={{
                    width:44, height:24, borderRadius:12, background: alertConfig[a.key] ? '#F59E0B' : '#E2E8F0',
                    cursor:'pointer', position:'relative', transition:'background 0.2s', flexShrink:0
                  }}>
                    <div style={{ position:'absolute', top:2, left: alertConfig[a.key] ? 20 : 2, width:20, height:20, borderRadius:'50%', background:'#fff', boxShadow:'0 1px 4px rgba(0,0,0,0.15)', transition:'left 0.2s' }}/>
                  </div>
                </div>
              ))}
              <Btn variant="primary" icon="check" onClick={saveAlertas} style={{ alignSelf:'flex-start' }}>Salvar Configurações</Btn>
            </div>
          </Card>
        )}

        {activeTab === 'backup' && (
          <Card style={{ padding:24 }}>
            <h2 style={{ margin:'0 0 8px', fontSize:17, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif' }}>Backup dos Dados</h2>
            <p style={{ fontSize:13, color:'#64748B', marginBottom:24 }}>Faça download de todos os dados do sistema em um único arquivo JSON.</p>

            {/* Status do último backup */}
            <div style={{
              padding:'18px 22px', borderRadius:14,
              background: lastBackup
                ? (diasDesdeUltimoBackup > 7 ? '#FEF2F2' : diasDesdeUltimoBackup > 1 ? '#FFFBEB' : '#ECFDF5')
                : '#FEF2F2',
              border: lastBackup
                ? `1px solid ${diasDesdeUltimoBackup > 7 ? '#FECACA' : diasDesdeUltimoBackup > 1 ? '#FED7AA' : '#A7F3D0'}`
                : '1px solid #FECACA',
              marginBottom:20, display:'flex', alignItems:'center', gap:14
            }}>
              <div style={{ width:48, height:48, borderRadius:12,
                background: lastBackup
                  ? (diasDesdeUltimoBackup > 7 ? '#FEE2E2' : diasDesdeUltimoBackup > 1 ? '#FFF3C4' : '#D1FAE5')
                  : '#FEE2E2',
                display:'flex', alignItems:'center', justifyContent:'center'
              }}>
                <Icon name={lastBackup ? (diasDesdeUltimoBackup > 7 ? 'alert' : 'check') : 'alert'} size={22}
                  color={lastBackup ? (diasDesdeUltimoBackup > 7 ? '#DC2626' : diasDesdeUltimoBackup > 1 ? '#D97706' : '#059669') : '#DC2626'} />
              </div>
              <div style={{ flex:1 }}>
                {lastBackup ? (
                  <>
                    <div style={{ fontSize:14, fontWeight:700, color:'#0F172A' }}>
                      {diasDesdeUltimoBackup === 0 ? 'Backup feito hoje ✓' : diasDesdeUltimoBackup === 1 ? 'Backup feito ontem' : `Último backup há ${diasDesdeUltimoBackup} dias`}
                    </div>
                    <div style={{ fontSize:12, color:'#64748B', marginTop:2 }}>
                      {new Date(lastBackup).toLocaleString('pt-BR')}
                    </div>
                  </>
                ) : (
                  <>
                    <div style={{ fontSize:14, fontWeight:700, color:'#991B1B' }}>Nenhum backup feito ainda</div>
                    <div style={{ fontSize:12, color:'#64748B', marginTop:2 }}>Recomendado fazer backup pelo menos uma vez por semana</div>
                  </>
                )}
              </div>
              <Btn variant="primary" icon="download" onClick={fazerBackup} disabled={backupRunning}>
                {backupRunning ? 'Gerando...' : 'Fazer Backup Agora'}
              </Btn>
            </div>

            {/* Frequência recomendada */}
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:20 }}>
              <div style={{ padding:16, background:'#F8FAFC', borderRadius:12, border:'1px solid #E2E8F0' }}>
                <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8 }}>
                  <div style={{ width:32, height:32, borderRadius:8, background:'#EFF6FF', display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <Icon name="calendar" size={16} color="#3B82F6"/>
                  </div>
                  <span style={{ fontSize:13, fontWeight:700, color:'#0F172A' }}>Backup Diário</span>
                </div>
                <p style={{ fontSize:12, color:'#64748B', lineHeight:1.5 }}>
                  Recomendado para empresas com muito movimento. Faça antes do final do expediente todo dia.
                </p>
              </div>
              <div style={{ padding:16, background:'#F8FAFC', borderRadius:12, border:'1px solid #E2E8F0' }}>
                <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8 }}>
                  <div style={{ width:32, height:32, borderRadius:8, background:'#FFF7ED', display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <Icon name="calendar" size={16} color="#F59E0B"/>
                  </div>
                  <span style={{ fontSize:13, fontWeight:700, color:'#0F172A' }}>Backup Semanal</span>
                </div>
                <p style={{ fontSize:12, color:'#64748B', lineHeight:1.5 }}>
                  Mínimo recomendado. Faça aos domingos ou segundas para garantir todos os dados da semana.
                </p>
              </div>
            </div>

            {/* O que está incluído */}
            <div style={{ background:'#F8FAFC', borderRadius:12, padding:18, border:'1px solid #E2E8F0' }}>
              <div style={{ fontSize:13, fontWeight:700, color:'#0F172A', marginBottom:10 }}>📦 O backup inclui:</div>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap:8, fontSize:12, color:'#374151' }}>
                {[
                  'Todas as Assistências e OS',
                  'Frota completa de guinchos',
                  'Cadastro de motoristas',
                  'Cadastro de seguradoras',
                  'Histórico de manutenções',
                  'Transações financeiras',
                  'Vistorias com checklist',
                  'Configurações da empresa',
                  'Categorias financeiras',
                  'Usuários do sistema',
                ].map(item => (
                  <div key={item} style={{ display:'flex', alignItems:'center', gap:6 }}>
                    <Icon name="check" size={12} color="#10B981" />
                    <span>{item}</span>
                  </div>
                ))}
              </div>
            </div>

            <div style={{ marginTop:16, background:'#EFF6FF', borderRadius:10, padding:'12px 16px', fontSize:12, color:'#1D4ED8', display:'flex', gap:8, alignItems:'flex-start' }}>
              <Icon name="alert" size={14} color="#3B82F6"/>
              <div>
                <strong>Backup automático na nuvem:</strong> além desse backup manual, o Supabase já faz backup automático diário do banco de dados. Esse backup em JSON é uma cópia adicional pra você guardar localmente.
              </div>
            </div>
          </Card>
        )}

        {activeTab === 'categorias' && (
          <Card style={{ padding:24 }}>
            <h2 style={{ margin:'0 0 20px', fontSize:17, fontWeight:700, color:'#0F172A', fontFamily:'DM Sans, sans-serif' }}>Categorias Financeiras</h2>
            {categorias.length === 0 && !showNovaCat && (
              <div style={{ padding: 20, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>Nenhuma categoria cadastrada.</div>
            )}
            {categorias.map((c,i)=>(
              <div key={c+i} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'10px 14px', background:i%2?'#F8FAFC':'#fff', borderRadius:8, marginBottom:4 }}>
                {editingCat === i ? (
                  <>
                    <input autoFocus value={editingCatVal} onChange={e => setEditingCatVal(e.target.value)}
                      onKeyDown={e => { if (e.key === 'Enter') { renameCategoria(c, editingCatVal); setEditingCat(null); } if (e.key === 'Escape') setEditingCat(null); }}
                      style={{ flex:1, padding:'4px 8px', borderRadius:6, border:'1px solid #3B82F6', fontSize:14, outline:'none', marginRight:8 }} />
                    <button onClick={() => { renameCategoria(c, editingCatVal); setEditingCat(null); }}
                      style={{ background:'none',border:'none',cursor:'pointer',color:'#10B981',padding:4,borderRadius:5 }}><Icon name="check" size={14}/></button>
                    <button onClick={() => setEditingCat(null)}
                      style={{ background:'none',border:'none',cursor:'pointer',color:'#94A3B8',padding:4,borderRadius:5 }}><Icon name="x" size={14}/></button>
                  </>
                ) : (
                  <>
                    <span style={{ fontSize:14, color:'#374151' }}>{c}</span>
                    <div style={{ display:'flex', gap:6 }}>
                      <button onClick={() => { setEditingCat(i); setEditingCatVal(c); }}
                        style={{ background:'none',border:'none',cursor:'pointer',color:'#64748B',padding:4,borderRadius:5 }}><Icon name="edit" size={14}/></button>
                      <button onClick={() => removeCategoria(c)}
                        style={{ background:'none',border:'none',cursor:'pointer',color:'#EF4444',padding:4,borderRadius:5 }}><Icon name="trash" size={14}/></button>
                    </div>
                  </>
                )}
              </div>
            ))}
            {showNovaCat ? (
              <div style={{ display:'flex', gap:8, alignItems:'center', marginTop:12, padding:'10px 14px', background:'#FFFBEB', borderRadius:8, border:'1px solid #FED7AA' }}>
                <input autoFocus value={novaCat} onChange={e => setNovaCat(e.target.value)} placeholder="Nome da categoria..."
                  onKeyDown={e => { if (e.key === 'Enter' && novaCat.trim()) { addCategoria(novaCat); setNovaCat(''); setShowNovaCat(false); } if (e.key === 'Escape') { setShowNovaCat(false); setNovaCat(''); } }}
                  style={{ flex:1, padding:'4px 8px', borderRadius:6, border:'1px solid #F59E0B', fontSize:14, outline:'none' }} />
                <button onClick={() => { if (novaCat.trim()) { addCategoria(novaCat); setNovaCat(''); setShowNovaCat(false); } }}
                  style={{ background:'#F59E0B',border:'none',cursor:'pointer',color:'#0F172A',padding:'6px 10px',borderRadius:6, fontWeight:700, fontSize:13 }}>Adicionar</button>
                <button onClick={() => { setShowNovaCat(false); setNovaCat(''); }}
                  style={{ background:'none',border:'none',cursor:'pointer',color:'#94A3B8',padding:4,borderRadius:5 }}><Icon name="x" size={14}/></button>
              </div>
            ) : (
              <Btn variant="secondary" size="sm" icon="plus" onClick={() => setShowNovaCat(true)} style={{ marginTop:12 }}>Nova Categoria</Btn>
            )}
          </Card>
        )}

        {activeTab === 'combustiveis'  && <ConfigCombustiveisScreen />}
        {activeTab === 'tipos-despesa' && <ConfigTiposDespesaScreen />}
        {activeTab === 'postos'        && <ConfigPostosScreen />}
        {activeTab === 'checklists'    && <ConfigChecklistsScreen />}
      </div>

      <Modal open={userModal} onClose={() => setUserModal(false)} title={editingUser ? `Editar ${editingUser.nome}` : 'Convidar Usuário'} width={480}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Input label="Nome Completo" placeholder="João Silva" value={userForm.nome} onChange={e => setUF('nome', e.target.value)}/>
          <Input label="E-mail" type="email" placeholder="email@empresa.com" value={userForm.email} onChange={e => setUF('email', e.target.value)} disabled={!!editingUser}/>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <Select label="Cargo" value={userForm.cargo} onChange={e => setUF('cargo', e.target.value)}
              options={[{value:'Administrador',label:'Administrador'},{value:'Operador',label:'Operador'},{value:'Motorista',label:'Motorista'}]}/>
            <Select label="Status" value={userForm.status} onChange={e => setUF('status', e.target.value)}
              options={[{value:'ativo',label:'Ativo'},{value:'inativo',label:'Inativo'}]}/>
          </div>
          {!editingUser && (
            <div style={{ background:'#FFFBEB', borderRadius:8, padding:'10px 14px', fontSize:12, color:'#92400E', display:'flex', gap:8, alignItems:'center', border:'1px solid #FED7AA' }}>
              <Icon name="alert" size={14} color="#F59E0B"/>
              Por enquanto, novos usuários precisam se cadastrar diretamente no Supabase Authentication. Aqui você pode editar permissões dos já cadastrados.
            </div>
          )}
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:8, borderTop:'1px solid #F1F5F9' }}>
            <Btn variant="secondary" onClick={() => setUserModal(false)}>Cancelar</Btn>
            <Btn variant="primary" icon="check" onClick={saveUser}>{editingUser ? 'Salvar' : 'OK'}</Btn>
          </div>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { RelatoriosScreen, ConfigScreen });
