'use client';

import { useEffect, useState, FormEvent } from 'react';
import Header from '@/components/header';
import Modal from '@/components/modal';
import api from '@/lib/api';
import { getUser, getTenants, saveAuth, saveTenants, TenantInfo } from '@/lib/auth';
import Image from 'next/image';

type Tab = 'empresa' | 'fiscal' | 'nfse' | 'smtp' | 'proposta' | 'integracoes' | 'empresas' | 'usuarios' | 'perfis' | 'senha';

const MODULE_LABELS: Record<string, string> = {
  clients: 'Clientes', products: 'Produtos', proposals: 'Propostas',
  contracts: 'Contratos', charges: 'Cobranças', invoices: 'NFS-e',
  signatures: 'Assinaturas', saas: 'Gestão SaaS', rbac: 'Controle de Acesso',
  settings: 'Configurações',
};
const ACTION_LABELS: Record<string, string> = {
  create: 'Criar', read: 'Visualizar', update: 'Editar', delete: 'Excluir',
  approve: 'Aprovar', export: 'Exportar', admin: 'Administrar',
};

interface TenantForm {
  name: string;
  document: string;
  email: string;
  phone: string;
  uf: string;
  municipalInscription: string;
  ibgeCode: string;
  taxRegime: string;
  simpleNational: boolean;
  fiscalIncentive: boolean;
  nfseUrl: string;
  nfseCertificate: string;
  nfseCertificatePass: string;
  autentiqueToken: string;
  logoUrl: string;
  letterheadPdf: string;
  smtpHost: string;
  smtpPort: string;
  smtpUser: string;
  smtpPass: string;
  smtpFrom: string;
  smtpSecure: boolean;
  // Proposal template
  proposalIntro: string;
  proposalPaymentConditions: string;
  proposalTerms: string;
  proposalFooter: string;
  proposalSignatureBlock: string;
}

const UF_OPTIONS = [
  'AC','AL','AM','AP','BA','CE','DF','ES','GO','MA',
  'MG','MS','MT','PA','PB','PE','PI','PR','RJ','RN',
  'RO','RR','RS','SC','SE','SP','TO',
];

const TAX_REGIMES = [
  { value: 1, label: '1 — Simples Nacional' },
  { value: 2, label: '2 — Simples Nacional — excesso' },
  { value: 3, label: '3 — Regime Normal' },
  { value: 4, label: '4 — Lucro Real' },
  { value: 5, label: '5 — Lucro Presumido' },
  { value: 6, label: '6 — MEI' },
];

const EMPTY: TenantForm = {
  name: '', document: '', email: '', phone: '', uf: '',
  municipalInscription: '', ibgeCode: '', taxRegime: '1',
  simpleNational: false, fiscalIncentive: false,
  nfseUrl: '', nfseCertificate: '', nfseCertificatePass: '', autentiqueToken: '',
  logoUrl: '', letterheadPdf: '',
  smtpHost: '', smtpPort: '587', smtpUser: '', smtpPass: '', smtpFrom: '', smtpSecure: false,
  proposalIntro: '', proposalPaymentConditions: '', proposalTerms: '',
  proposalFooter: '', proposalSignatureBlock: '',
};

const EMPTY_COMPANY = { name: '', document: '', email: '' };

export default function ConfiguracoesPage() {
  const user = getUser();
  const [tab, setTab] = useState<Tab>('empresa');
  const [form, setForm] = useState<TenantForm>(EMPTY);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [smtpTesting, setSmtpTesting] = useState(false);
  const [smtpTestResult, setSmtpTestResult] = useState<{ ok: boolean; message: string } | null>(null);
  const [success, setSuccess] = useState('');
  const [error, setError] = useState('');

  // A1 certificate upload
  const [certFileName, setCertFileName] = useState('');

  // Logo upload
  const [logoFileName, setLogoFileName] = useState('');

  // Letterhead PDF upload
  const [letterheadFileName, setLetterheadFileName] = useState('');

  // Multi-company
  const [tenants, setTenants] = useState<TenantInfo[]>([]);
  const [newCompanyOpen, setNewCompanyOpen] = useState(false);
  const [newCompanyForm, setNewCompanyForm] = useState(EMPTY_COMPANY);
  const [newCompanySaving, setNewCompanySaving] = useState(false);
  const [newCompanyError, setNewCompanyError] = useState('');

  // RBAC — usuarios e perfis
  const [rbacUsers,       setRbacUsers]       = useState<any[]>([]);
  const [rbacRoles,       setRbacRoles]       = useState<any[]>([]);
  const [rbacPermissions, setRbacPermissions] = useState<Record<string, any[]>>({});
  const [rbacLoading,     setRbacLoading]     = useState(false);

  const [userModal,   setUserModal]   = useState(false);
  const [userForm,    setUserForm]    = useState<{ name: string; email: string; password: string; roleId: string; tenantIds: string[] }>({ name: '', email: '', password: '', roleId: '', tenantIds: [] });
  const [userSaving,  setUserSaving]  = useState(false);

  const [roleModal,  setRoleModal]  = useState<{ id?: string; name: string; description: string; permissionIds: string[] } | null>(null);
  const [roleSaving, setRoleSaving] = useState(false);

  const [assignModal,    setAssignModal]    = useState<{ userId: string } | null>(null);
  const [assignRoleId,   setAssignRoleId]   = useState('');
  const [assignSaving,   setAssignSaving]   = useState(false);

  // Alterar senha
  const [pwForm,    setPwForm]    = useState({ current: '', next: '', confirm: '' });
  const [pwSaving,  setPwSaving]  = useState(false);
  const [pwSuccess, setPwSuccess] = useState('');
  const [pwError,   setPwError]   = useState('');

  useEffect(() => {
    const stored = getTenants();
    if (stored.length > 0) setTenants(stored);
    api.get('/auth/my-tenants').then((r) => {
      saveTenants(r.data);
      setTenants(r.data);
    }).catch(() => {});
  }, []);

  useEffect(() => {
    api.get('/tenant').then((r) => {
      const t = r.data;
      setForm({
        name:                 t.name ?? '',
        document:             t.document ?? '',
        email:                t.email ?? '',
        phone:                t.phone ?? '',
        uf:                   t.uf ?? '',
        municipalInscription: t.municipalInscription ?? '',
        ibgeCode:             t.ibgeCode ?? '',
        taxRegime:            String(t.taxRegime ?? 1),
        simpleNational:       t.simpleNational ?? false,
        fiscalIncentive:      t.fiscalIncentive ?? false,
        nfseUrl:              t.nfseUrl ?? '',
        nfseCertificate:      t.nfseCertificate ?? '',
        nfseCertificatePass:  t.nfseCertificatePass ?? '',
        autentiqueToken:      t.autentiqueToken ?? '',
        logoUrl:              t.logoUrl ?? '',
        letterheadPdf:        t.letterheadPdf ?? '',
        smtpHost:   t.smtpHost   ?? '',
        smtpPort:   String(t.smtpPort ?? 587),
        smtpUser:   t.smtpUser   ?? '',
        smtpPass:   t.smtpPass   ?? '',
        smtpFrom:   t.smtpFrom   ?? '',
        smtpSecure: t.smtpSecure ?? false,
        ...(() => {
          try {
            const tmpl = t.proposalTemplate ? JSON.parse(t.proposalTemplate) : {};
            return {
              proposalIntro:             tmpl.intro ?? '',
              proposalPaymentConditions: tmpl.paymentConditions ?? '',
              proposalTerms:             tmpl.terms ?? '',
              proposalFooter:            tmpl.footer ?? '',
              proposalSignatureBlock:    tmpl.signatureBlock ?? '',
            };
          } catch { return { proposalIntro: '', proposalPaymentConditions: '', proposalTerms: '', proposalFooter: '', proposalSignatureBlock: '' }; }
        })(),
      });
      if (t.nfseCertificate) setCertFileName('Certificado carregado');
      if (t.letterheadPdf) setLetterheadFileName('Timbre carregado');
      // Propagate logoUrl to localStorage so sidebar reflects it
      if (user?.tenantId && t.logoUrl) {
        const stored = getTenants();
        saveTenants(stored.map((st) =>
          st.id === user.tenantId ? { ...st, logoUrl: t.logoUrl } : st,
        ));
      }
    }).catch(() => {}).finally(() => setLoading(false));
  }, []);

  async function loadRbac() {
    setRbacLoading(true);
    try {
      const [u, r, p] = await Promise.all([
        api.get('/rbac/users'),
        api.get('/rbac/roles'),
        api.get('/rbac/permissions'),
      ]);
      setRbacUsers(u.data);
      setRbacRoles(r.data);
      setRbacPermissions(p.data);
    } catch {}
    setRbacLoading(false);
  }

  useEffect(() => {
    if (tab === 'usuarios' || tab === 'perfis') loadRbac();
  }, [tab]);

  async function handleCreateUser(e: FormEvent) {
    e.preventDefault();
    setUserSaving(true);
    try {
      const payload: any = { name: userForm.name, email: userForm.email, password: userForm.password };
      if (userForm.roleId) payload.roleId = userForm.roleId;
      if (tenants.length > 1 && userForm.tenantIds.length > 0) payload.tenantIds = userForm.tenantIds;
      await api.post('/rbac/users', payload);
      setUserModal(false);
      setUserForm({ name: '', email: '', password: '', roleId: '' });
      await loadRbac();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao criar usuário');
    } finally { setUserSaving(false); }
  }

  async function handleToggleUser(id: string) {
    try { await api.patch(`/rbac/users/${id}/toggle-status`); await loadRbac(); }
    catch (err: any) { alert(err.response?.data?.message ?? 'Erro'); }
  }

  async function handleAssignRole(e: FormEvent) {
    e.preventDefault();
    if (!assignModal) return;
    setAssignSaving(true);
    try {
      await api.patch(`/rbac/users/${assignModal.userId}/role`, { roleId: assignRoleId });
      setAssignModal(null);
      await loadRbac();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao atribuir perfil');
    } finally { setAssignSaving(false); }
  }

  async function handleSaveRole(e: FormEvent) {
    e.preventDefault();
    if (!roleModal) return;
    setRoleSaving(true);
    try {
      if (roleModal.id) {
        await api.put(`/rbac/roles/${roleModal.id}`, roleModal);
      } else {
        await api.post('/rbac/roles', roleModal);
      }
      setRoleModal(null);
      await loadRbac();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao salvar perfil');
    } finally { setRoleSaving(false); }
  }

  async function handleDeleteRole(id: string) {
    if (!confirm('Excluir este perfil de acesso?')) return;
    try { await api.delete(`/rbac/roles/${id}`); await loadRbac(); }
    catch (err: any) { alert(err.response?.data?.message ?? 'Erro ao excluir'); }
  }

  async function handleChangePassword(e: FormEvent) {
    e.preventDefault();
    setPwSuccess(''); setPwError('');
    if (pwForm.next !== pwForm.confirm) { setPwError('As senhas não coincidem'); return; }
    setPwSaving(true);
    try {
      await api.patch('/auth/change-password', { currentPassword: pwForm.current, newPassword: pwForm.next });
      setPwSuccess('Senha alterada com sucesso.');
      setPwForm({ current: '', next: '', confirm: '' });
    } catch (err: any) {
      setPwError(err.response?.data?.message ?? 'Erro ao alterar senha');
    } finally { setPwSaving(false); }
  }

  function setF(field: keyof TenantForm, value: string | boolean) {
    setForm((p) => ({ ...p, [field]: value }));
    setSuccess('');
    setError('');
  }

  function handleLogoUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setLogoFileName(file.name);
    const reader = new FileReader();
    reader.onload = () => setF('logoUrl', reader.result as string);
    reader.readAsDataURL(file);
  }

  function handleCertUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.name.match(/\.(pfx|p12)$/i)) {
      setError('Selecione um arquivo .pfx ou .p12');
      return;
    }
    setCertFileName(file.name);
    const reader = new FileReader();
    reader.onload = () => {
      const result = reader.result as string;
      // result is "data:application/octet-stream;base64,XXXX..." — extract only the base64 part
      const base64 = result.split(',')[1] ?? '';
      setF('nfseCertificate', base64);
    };
    reader.readAsDataURL(file);
  }

  function handleLetterheadUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.name.match(/\.pdf$/i)) {
      setError('Selecione um arquivo .pdf');
      return;
    }
    setLetterheadFileName(file.name);
    const reader = new FileReader();
    reader.onload = () => {
      const result = reader.result as string;
      const base64 = result.split(',')[1] ?? '';
      setF('letterheadPdf', base64);
    };
    reader.readAsDataURL(file);
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError('');
    setSuccess('');
    setSaving(true);
    try {
      const proposalTemplate = JSON.stringify({
        intro:             form.proposalIntro,
        paymentConditions: form.proposalPaymentConditions,
        terms:             form.proposalTerms,
        footer:            form.proposalFooter,
        signatureBlock:    form.proposalSignatureBlock,
      });
      const payload: any = {
        name:                form.name,
        email:               form.email,
        ...(form.phone && { phone: form.phone }),
        ...(form.uf && { uf: form.uf }),
        ...(form.municipalInscription && { municipalInscription: form.municipalInscription }),
        ...(form.ibgeCode && { ibgeCode: form.ibgeCode }),
        taxRegime:           Number(form.taxRegime),
        simpleNational:      form.simpleNational,
        fiscalIncentive:     form.fiscalIncentive,
        ...(form.nfseUrl && { nfseUrl: form.nfseUrl }),
        ...(form.nfseCertificate && { nfseCertificate: form.nfseCertificate }),
        ...(form.nfseCertificatePass && { nfseCertificatePass: form.nfseCertificatePass }),
        ...(form.autentiqueToken && { autentiqueToken: form.autentiqueToken }),
        ...(form.logoUrl && { logoUrl: form.logoUrl }),
        ...(form.letterheadPdf && { letterheadPdf: form.letterheadPdf }),
        ...(form.smtpHost && { smtpHost: form.smtpHost }),
        ...(form.smtpPort && { smtpPort: Number(form.smtpPort) }),
        ...(form.smtpUser && { smtpUser: form.smtpUser }),
        ...(form.smtpPass && { smtpPass: form.smtpPass }),
        ...(form.smtpFrom && { smtpFrom: form.smtpFrom }),
        smtpSecure: form.smtpSecure,
        proposalTemplate,
      };
      await api.put('/tenant', payload);
      // Propagate logoUrl to stored tenant list so sidebar can show it
      if (user?.tenantId) {
        const stored = getTenants();
        saveTenants(stored.map((t) =>
          t.id === user.tenantId ? { ...t, logoUrl: form.logoUrl } : t,
        ));
      }
      setSuccess('Configurações salvas com sucesso.');
    } catch (err: any) {
      setError(err.response?.data?.message ?? 'Erro ao salvar configurações');
    } finally {
      setSaving(false);
    }
  }

  async function handleSmtpTest() {
    setSmtpTesting(true);
    setSmtpTestResult(null);
    try {
      const r = await api.post('/email/test');
      setSmtpTestResult(r.data);
    } catch (err: any) {
      setSmtpTestResult({ ok: false, message: err.response?.data?.message ?? 'Erro ao testar conexão' });
    } finally {
      setSmtpTesting(false);
    }
  }

  async function handleNewCompany(e: FormEvent) {
    e.preventDefault();
    setNewCompanyError('');
    setNewCompanySaving(true);
    try {
      const { data } = await api.post('/auth/create-company', newCompanyForm);
      saveAuth(data);
      // Reload tenants list
      const r = await api.get('/auth/my-tenants');
      saveTenants(r.data);
      setTenants(r.data);
      setNewCompanyOpen(false);
      setNewCompanyForm(EMPTY_COMPANY);
      // Switch to new company context
      window.location.href = '/';
    } catch (err: any) {
      setNewCompanyError(err.response?.data?.message ?? 'Erro ao criar empresa');
    } finally {
      setNewCompanySaving(false);
    }
  }

  const tabs: { id: Tab; label: string }[] = [
    { id: 'empresa',     label: 'Dados da empresa' },
    { id: 'fiscal',      label: 'Fiscal' },
    { id: 'nfse',        label: 'NFS-e' },
    { id: 'smtp',        label: 'E-mail / SMTP' },
    { id: 'proposta',    label: 'Modelo de proposta' },
    { id: 'integracoes', label: 'Integrações' },
    { id: 'empresas',    label: `Minhas empresas (${tenants.length})` },
    { id: 'usuarios',    label: 'Usuários' },
    { id: 'perfis',      label: 'Perfis de acesso' },
    { id: 'senha',       label: 'Alterar senha' },
  ];

  const NO_SAVE_TABS: Tab[] = ['empresas', 'usuarios', 'perfis', 'senha'];

  if (loading) return (
    <>
      <Header title="Configurações" subtitle="Dados da empresa e preferências" />
      <p className="text-sm text-[#0E0F12]/50">Carregando...</p>
    </>
  );

  return (
    <>
      <Header title="Configurações" subtitle="Dados da empresa e preferências" />

      <div className="flex gap-6">
        {/* Left: user card */}
        <div className="w-64 shrink-0 space-y-4">
          <div className="bg-white rounded-xl border border-[#EAE4D9] p-5">
            <p className="text-xs text-[#0E0F12]/40 uppercase tracking-wide font-semibold mb-3">Usuário</p>
            <p className="text-sm font-medium text-[#0E0F12] truncate">{user?.name}</p>
            <p className="text-xs text-[#0E0F12]/50 truncate mt-0.5">{user?.email}</p>
            <span className="mt-2 inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-[#EAE4D9] text-[#B7895A]">
              {user?.role === 'owner' ? 'Proprietário' : 'Membro'}
            </span>
          </div>

          <nav className="bg-white rounded-xl border border-[#EAE4D9] overflow-hidden">
            {tabs.map((t) => (
              <button
                key={t.id}
                onClick={() => setTab(t.id)}
                className={`w-full text-left px-5 py-3 text-sm border-b border-[#EAE4D9] last:border-b-0 transition-colors ${
                  tab === t.id
                    ? 'bg-[#EAE4D9] text-[#B7895A] font-medium'
                    : 'text-[#0E0F12]/60 hover:bg-[#FAF7F2]'
                }`}
              >
                {t.label}
              </button>
            ))}
          </nav>
        </div>

        {/* Right: form */}
        <div className="flex-1 bg-white rounded-xl border border-[#EAE4D9] p-6">
          <form onSubmit={handleSubmit} className="space-y-5">
            {success && <div className="bg-green-50 text-green-700 text-sm px-4 py-3 rounded-lg">{success}</div>}
            {error && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{error}</div>}

            {tab === 'empresa' && (
              <>
                <h2 className="text-base font-semibold text-[#0E0F12]">Dados da empresa</h2>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Razão social / Nome <span className="text-red-500">*</span></label>
                  <input className="input" required value={form.name} onChange={(e) => setF('name', e.target.value)} placeholder="Empresa Ltda" />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">CNPJ</label>
                    <input className="input bg-[#FAF7F2]" readOnly value={form.document} title="O CNPJ não pode ser alterado" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">E-mail <span className="text-red-500">*</span></label>
                    <input className="input" type="email" required value={form.email} onChange={(e) => setF('email', e.target.value)} />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Telefone</label>
                    <input className="input" value={form.phone} onChange={(e) => setF('phone', e.target.value)} placeholder="(11) 99999-9999" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">UF</label>
                    <select className="input" value={form.uf} onChange={(e) => setF('uf', e.target.value)}>
                      <option value="">Selecione</option>
                      {UF_OPTIONS.map((uf) => (
                        <option key={uf} value={uf}>{uf}</option>
                      ))}
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Logo da empresa</label>
                  <div className="flex items-center gap-4">
                    {form.logoUrl ? (
                      <div className="relative w-16 h-16 rounded-xl border border-[#EAE4D9] overflow-hidden shrink-0">
                        <Image src={form.logoUrl} alt="Logo" fill style={{ objectFit: 'contain' }} unoptimized />
                      </div>
                    ) : (
                      <div className="w-16 h-16 rounded-xl border-2 border-dashed border-[#EAE4D9] flex items-center justify-center text-2xl shrink-0 text-[#0E0F12]/20">
                        🏢
                      </div>
                    )}
                    <div className="flex-1 space-y-1">
                      <label className="inline-flex items-center gap-2 text-sm text-[#B7895A] hover:text-[#9E7248] cursor-pointer font-medium">
                        <input
                          type="file"
                          accept="image/png,image/jpeg,image/svg+xml,image/webp"
                          className="sr-only"
                          onChange={handleLogoUpload}
                        />
                        {logoFileName || (form.logoUrl ? 'Trocar logo' : 'Selecionar imagem')}
                      </label>
                      <p className="text-xs text-[#0E0F12]/40">PNG, JPG ou SVG. Exibida no ícone da empresa.</p>
                      {form.logoUrl && (
                        <button
                          type="button"
                          className="text-xs text-red-400 hover:text-red-600"
                          onClick={() => { setF('logoUrl', ''); setLogoFileName(''); }}
                        >
                          Remover logo
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              </>
            )}

            {tab === 'fiscal' && (
              <>
                <h2 className="text-base font-semibold text-[#0E0F12]">Configuração fiscal</h2>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Inscrição municipal</label>
                    <input className="input" value={form.municipalInscription} onChange={(e) => setF('municipalInscription', e.target.value)} placeholder="00000000" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Código IBGE do município</label>
                    <input className="input" value={form.ibgeCode} onChange={(e) => setF('ibgeCode', e.target.value)} placeholder="3550308" maxLength={7} />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Regime tributário</label>
                  <select className="input" value={form.taxRegime} onChange={(e) => setF('taxRegime', e.target.value)}>
                    {TAX_REGIMES.map((r) => (
                      <option key={r.value} value={r.value}>{r.label}</option>
                    ))}
                  </select>
                </div>

                <div className="flex flex-col gap-3 pt-1">
                  <label className="flex items-center gap-3 cursor-pointer">
                    <input
                      type="checkbox"
                      className="h-4 w-4 rounded border-[#EAE4D9] accent-[#B7895A]"
                      checked={form.simpleNational}
                      onChange={(e) => setF('simpleNational', e.target.checked)}
                    />
                    <div>
                      <p className="text-sm font-medium text-[#0E0F12]">Optante do Simples Nacional</p>
                      <p className="text-xs text-[#0E0F12]/40">Campo OptanteSimplesNacional na NFS-e</p>
                    </div>
                  </label>
                  <label className="flex items-center gap-3 cursor-pointer">
                    <input
                      type="checkbox"
                      className="h-4 w-4 rounded border-[#EAE4D9] accent-[#B7895A]"
                      checked={form.fiscalIncentive}
                      onChange={(e) => setF('fiscalIncentive', e.target.checked)}
                    />
                    <div>
                      <p className="text-sm font-medium text-[#0E0F12]">Incentivo fiscal</p>
                      <p className="text-xs text-[#0E0F12]/40">Campo IncentivoFiscal na NFS-e</p>
                    </div>
                  </label>
                </div>
              </>
            )}

            {tab === 'nfse' && (
              <>
                <h2 className="text-base font-semibold text-[#0E0F12]">Integração NFS-e (ABRASF)</h2>
                <p className="text-sm text-[#0E0F12]/50">Configure o WebService da prefeitura para emissão e cancelamento de notas fiscais de serviço eletrônicas.</p>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">URL do WebService (SOAP)</label>
                  <input
                    className="input"
                    type="url"
                    value={form.nfseUrl}
                    onChange={(e) => setF('nfseUrl', e.target.value)}
                    placeholder="https://nfse.suaprefeitura.sp.gov.br/ws/nfseservice.asmx"
                  />
                  <p className="text-xs text-[#0E0F12]/40 mt-1">Consulte a prefeitura do seu município para obter o endereço do WebService ABRASF v2.03.</p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Certificado digital A1 (.pfx / .p12)</label>
                  <div className={`relative border-2 border-dashed rounded-xl p-5 text-center transition-colors ${certFileName ? 'border-green-300 bg-green-50' : 'border-[#EAE4D9] hover:border-[#B7895A]'}`}>
                    {certFileName ? (
                      <div className="space-y-2">
                        <p className="text-sm font-medium text-green-700">Certificado carregado</p>
                        <p className="text-xs text-green-600 font-mono">{certFileName}</p>
                        <button
                          type="button"
                          onClick={() => { setCertFileName(''); setF('nfseCertificate', ''); }}
                          className="text-xs text-red-400 hover:text-red-600"
                        >
                          Remover
                        </button>
                      </div>
                    ) : (
                      <div className="space-y-2">
                        <p className="text-sm text-[#0E0F12]/50">Arraste o arquivo ou clique para selecionar</p>
                        <p className="text-xs text-[#0E0F12]/40">Aceita .pfx ou .p12 — convertido automaticamente para base64</p>
                      </div>
                    )}
                    <input
                      type="file"
                      accept=".pfx,.p12"
                      onChange={handleCertUpload}
                      className={`absolute inset-0 w-full h-full opacity-0 cursor-pointer ${certFileName ? 'pointer-events-none' : ''}`}
                      style={{ position: certFileName ? 'static' : undefined }}
                    />
                  </div>
                  {!certFileName && (
                    <label className="mt-2 inline-flex items-center gap-2 text-sm text-[#B7895A] hover:text-[#9E7248] cursor-pointer font-medium">
                      <input type="file" accept=".pfx,.p12" className="sr-only" onChange={handleCertUpload} />
                      Selecionar arquivo .pfx
                    </label>
                  )}
                  <p className="text-xs text-[#0E0F12]/40 mt-1">Necessário apenas se a prefeitura exigir assinatura digital do XML.</p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Senha do certificado</label>
                  <input
                    className="input"
                    type="password"
                    value={form.nfseCertificatePass}
                    onChange={(e) => setF('nfseCertificatePass', e.target.value)}
                    placeholder="••••••••"
                    autoComplete="new-password"
                  />
                </div>
              </>
            )}

            {tab === 'smtp' && (
              <>
                <h2 className="text-base font-semibold text-[#0E0F12]">Configuração de e-mail (SMTP)</h2>
                <p className="text-sm text-[#0E0F12]/50">Configure o servidor de e-mail usado para disparar mensagens de cobrança, propostas e notificações.</p>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Servidor SMTP (host)</label>
                    <input className="input" value={form.smtpHost} onChange={(e) => setF('smtpHost', e.target.value)} placeholder="smtp.gmail.com" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Porta</label>
                    <input className="input" type="number" value={form.smtpPort} onChange={(e) => setF('smtpPort', e.target.value)} placeholder="587" />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Usuário / E-mail da conta</label>
                    <input className="input" type="email" value={form.smtpUser} onChange={(e) => setF('smtpUser', e.target.value)} placeholder="envio@suaempresa.com" autoComplete="username" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Senha</label>
                    <input className="input" type="password" value={form.smtpPass} onChange={(e) => setF('smtpPass', e.target.value)} placeholder="••••••••" autoComplete="new-password" />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Remetente (nome e e-mail)</label>
                  <input className="input" value={form.smtpFrom} onChange={(e) => setF('smtpFrom', e.target.value)} placeholder='Empresa Ltda <envio@suaempresa.com>' />
                  <p className="text-xs text-[#0E0F12]/40 mt-1">Formato: <code>Nome {'<email@dominio.com>'}</code> ou apenas o e-mail.</p>
                </div>

                <div>
                  <label className="flex items-center gap-3 cursor-pointer">
                    <input
                      type="checkbox"
                      className="h-4 w-4 rounded border-[#EAE4D9] accent-[#B7895A]"
                      checked={form.smtpSecure}
                      onChange={(e) => setF('smtpSecure', e.target.checked)}
                    />
                    <div>
                      <p className="text-sm font-medium text-[#0E0F12]">Usar SSL/TLS (porta 465)</p>
                      <p className="text-xs text-[#0E0F12]/40">Desmarcado = STARTTLS (porta 587). Marque apenas se seu servidor usar SSL direto.</p>
                    </div>
                  </label>
                </div>

                <div className="flex items-center gap-4 pt-1">
                  <button
                    type="button"
                    className="btn-secondary"
                    onClick={handleSmtpTest}
                    disabled={smtpTesting}
                  >
                    {smtpTesting ? 'Testando…' : 'Testar conexão'}
                  </button>
                  {smtpTestResult && (
                    <span className={`text-sm font-medium ${smtpTestResult.ok ? 'text-green-600' : 'text-red-600'}`}>
                      {smtpTestResult.ok ? '✓ ' : '✗ '}{smtpTestResult.message}
                    </span>
                  )}
                </div>

                <div className="bg-[#FAF7F2] border border-[#EAE4D9] rounded-xl p-4 text-xs text-[#0E0F12]/60 space-y-1">
                  <p className="font-semibold text-[#0E0F12]">Configurações rápidas</p>
                  <p><strong>Gmail:</strong> smtp.gmail.com · porta 587 · STARTTLS · use uma senha de app</p>
                  <p><strong>Outlook / Office 365:</strong> smtp.office365.com · porta 587 · STARTTLS</p>
                  <p><strong>Titan / cPanel:</strong> mail.seudominio.com.br · porta 465 · SSL</p>
                </div>
              </>
            )}

            {tab === 'proposta' && (
              <>
                <h2 className="text-base font-semibold text-[#0E0F12]">Modelo de proposta</h2>
                <p className="text-sm text-[#0E0F12]/50">Esses textos são usados para gerar o PDF de cada proposta cadastrada. Suporte a quebras de linha.</p>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Texto de introdução</label>
                  <textarea
                    className="input resize-none"
                    rows={4}
                    value={form.proposalIntro}
                    onChange={(e) => setF('proposalIntro', e.target.value)}
                    placeholder="Ex: Prezado cliente, apresentamos a seguir nossa proposta de serviços..."
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Condições de pagamento</label>
                  <textarea
                    className="input resize-none"
                    rows={3}
                    value={form.proposalPaymentConditions}
                    onChange={(e) => setF('proposalPaymentConditions', e.target.value)}
                    placeholder="Ex: Pagamento via PIX ou boleto bancário, vencimento no dia 5 de cada mês..."
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Termos e condições</label>
                  <textarea
                    className="input resize-none"
                    rows={5}
                    value={form.proposalTerms}
                    onChange={(e) => setF('proposalTerms', e.target.value)}
                    placeholder="Ex: Esta proposta é válida pelo prazo indicado acima. Após aceite, será gerado um contrato formal..."
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Bloco de assinatura</label>
                    <textarea
                      className="input resize-none"
                      rows={3}
                      value={form.proposalSignatureBlock}
                      onChange={(e) => setF('proposalSignatureBlock', e.target.value)}
                      placeholder="Ex: Assinado digitalmente via Klavo&#10;Data: {data_aceite}"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-[#0E0F12] mb-1">Rodapé</label>
                    <textarea
                      className="input resize-none"
                      rows={3}
                      value={form.proposalFooter}
                      onChange={(e) => setF('proposalFooter', e.target.value)}
                      placeholder="Ex: Dúvidas? Entre em contato: contato@suaempresa.com"
                    />
                  </div>
                </div>

                <div className="bg-[#EAE4D9]/50 border border-[#EAE4D9] rounded-xl p-4 text-xs text-[#B7895A] space-y-1">
                  <p className="font-semibold">Variáveis disponíveis nos textos:</p>
                  <p><code className="bg-[#EAE4D9] px-1 rounded">{'{numero}'}</code> — Número da proposta</p>
                  <p><code className="bg-[#EAE4D9] px-1 rounded">{'{cliente}'}</code> — Nome do cliente</p>
                  <p><code className="bg-[#EAE4D9] px-1 rounded">{'{validade}'}</code> — Data de validade</p>
                  <p><code className="bg-[#EAE4D9] px-1 rounded">{'{total}'}</code> — Valor total</p>
                  <p><code className="bg-[#EAE4D9] px-1 rounded">{'{data_aceite}'}</code> — Data do aceite digital</p>
                </div>
              </>
            )}

            {tab === 'integracoes' && (
              <>
                <h2 className="text-base font-semibold text-[#0E0F12]">Integrações</h2>

                <div className="border border-[#EAE4D9] rounded-xl p-5">
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-lg bg-[#EAE4D9] flex items-center justify-center shrink-0">
                      <span className="text-lg">✍️</span>
                    </div>
                    <div className="flex-1">
                      <h3 className="text-sm font-semibold text-[#0E0F12]">Autentique</h3>
                      <p className="text-xs text-[#0E0F12]/50 mt-0.5 mb-3">Plataforma de assinatura eletrônica. Usada para envio e coleta de assinaturas em contratos.</p>
                      <label className="block text-sm font-medium text-[#0E0F12] mb-1">Token da API</label>
                      <input
                        className="input"
                        type="password"
                        value={form.autentiqueToken}
                        onChange={(e) => setF('autentiqueToken', e.target.value)}
                        placeholder="Seu token da Autentique"
                        autoComplete="new-password"
                      />
                    </div>
                  </div>
                </div>

                <div className="border border-[#EAE4D9] rounded-xl p-5">
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-lg bg-[#EAE4D9] flex items-center justify-center shrink-0">
                      <span className="text-lg">📄</span>
                    </div>
                    <div className="flex-1">
                      <h3 className="text-sm font-semibold text-[#0E0F12]">Timbre do contrato</h3>
                      <p className="text-xs text-[#0E0F12]/50 mt-0.5 mb-3">
                        PDF de uma página com a folha timbrada da empresa. Será usado como plano de fundo ao gerar contratos.
                      </p>
                      <div className={`relative border-2 border-dashed rounded-xl p-5 text-center transition-colors ${letterheadFileName ? 'border-green-300 bg-green-50' : 'border-[#EAE4D9] hover:border-[#B7895A]'}`}>
                        {letterheadFileName ? (
                          <div className="space-y-2">
                            <p className="text-sm font-medium text-green-700">Timbre carregado</p>
                            <p className="text-xs text-green-600 font-mono">{letterheadFileName}</p>
                            <button
                              type="button"
                              onClick={() => { setLetterheadFileName(''); setF('letterheadPdf', ''); }}
                              className="text-xs text-red-400 hover:text-red-600"
                            >
                              Remover
                            </button>
                          </div>
                        ) : (
                          <div className="space-y-2">
                            <p className="text-sm text-[#0E0F12]/50">Arraste o PDF ou clique para selecionar</p>
                            <p className="text-xs text-[#0E0F12]/40">Arquivo .pdf — 1 página, tamanho A4</p>
                          </div>
                        )}
                        {!letterheadFileName && (
                          <input
                            type="file"
                            accept=".pdf"
                            onChange={handleLetterheadUpload}
                            className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                          />
                        )}
                      </div>
                      {!letterheadFileName && (
                        <label className="mt-2 inline-flex items-center gap-2 text-sm text-[#B7895A] hover:text-[#9E7248] cursor-pointer font-medium">
                          <input type="file" accept=".pdf" className="sr-only" onChange={handleLetterheadUpload} />
                          Selecionar arquivo PDF
                        </label>
                      )}
                      <p className="text-xs text-[#0E0F12]/40 mt-1">O PDF é armazenado como base64 e usado como plano de fundo na geração automática de contratos.</p>
                    </div>
                  </div>
                </div>
              </>
            )}

            {tab === 'empresas' && (
              <>
                <div className="flex items-center justify-between">
                  <h2 className="text-base font-semibold text-[#0E0F12]">Minhas empresas</h2>
                  <button type="button" className="btn-primary text-xs" onClick={() => setNewCompanyOpen(true)}>
                    + Nova empresa
                  </button>
                </div>
                <p className="text-sm text-[#0E0F12]/50">Sua conta tem acesso às empresas abaixo. Use o seletor na barra lateral para alternar entre elas.</p>

                <div className="space-y-3">
                  {tenants.map((t) => (
                    <div key={t.id} className={`flex items-center gap-4 p-4 rounded-xl border ${t.id === user?.tenantId ? 'border-[#B7895A] bg-[#EAE4D9]/30' : 'border-[#EAE4D9]'}`}>
                      <div className="w-10 h-10 rounded-lg bg-[#B7895A] flex items-center justify-center shrink-0 text-sm font-bold text-[#0E0F12] overflow-hidden">
                        {(t as TenantInfo & { logoUrl?: string }).logoUrl ? (
                          <Image
                            src={(t as TenantInfo & { logoUrl?: string }).logoUrl!}
                            alt={t.name}
                            width={40}
                            height={40}
                            style={{ objectFit: 'contain' }}
                            unoptimized
                          />
                        ) : (
                          t.name[0]?.toUpperCase()
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-semibold text-[#0E0F12] truncate">{t.name}</p>
                        <p className="text-xs text-[#0E0F12]/40">CNPJ {t.document} · {t.plan}</p>
                      </div>
                      {t.id === user?.tenantId && (
                        <span className="text-xs text-[#B7895A] font-medium shrink-0">Ativa</span>
                      )}
                    </div>
                  ))}
                </div>
              </>
            )}

            {tab === 'usuarios' && (
              <>
                <div className="flex items-center justify-between">
                  <h2 className="text-base font-semibold text-[#0E0F12]">Usuários da plataforma</h2>
                  <button type="button" className="btn-primary text-xs" onClick={() => { setUserForm({ name: '', email: '', password: '', roleId: '', tenantIds: user?.tenantId ? [user.tenantId] : [] }); setUserModal(true); }}>+ Novo usuário</button>
                </div>
                {rbacLoading ? <p className="text-sm text-[#0E0F12]/50">Carregando...</p> : (
                  <div className="space-y-2">
                    {rbacUsers.length === 0 && <p className="text-sm text-[#0E0F12]/50">Nenhum usuário cadastrado.</p>}
                    {rbacUsers.map((u: any) => (
                      <div key={u.id} className="flex items-center justify-between p-4 border border-[#EAE4D9] rounded-xl">
                        <div>
                          <p className="text-sm font-semibold text-[#0E0F12]">{u.name}</p>
                          <p className="text-xs text-[#0E0F12]/50">{u.email}</p>
                          <div className="flex flex-wrap gap-1 mt-1.5">
                            {u.isOwner && <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-[#EAE4D9] text-[#B7895A]">Proprietário</span>}
                            {u.role && <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">{u.role.name}</span>}
                            <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${u.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                              {u.status === 'active' ? 'Ativo' : 'Inativo'}
                            </span>
                          </div>
                        </div>
                        {!u.isOwner && (
                          <div className="flex gap-3 shrink-0">
                            <button
                              type="button"
                              className="text-xs font-medium text-[#B7895A] hover:text-[#9E7248]"
                              onClick={() => { setAssignModal({ userId: u.id }); setAssignRoleId(u.roleId ?? ''); }}
                            >
                              Perfil de acesso
                            </button>
                            <button
                              type="button"
                              className={`text-xs font-medium ${u.status === 'active' ? 'text-red-500 hover:text-red-700' : 'text-green-600 hover:text-green-800'}`}
                              onClick={() => handleToggleUser(u.id)}
                            >
                              {u.status === 'active' ? 'Desativar' : 'Ativar'}
                            </button>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </>
            )}

            {tab === 'perfis' && (
              <>
                <div className="flex items-center justify-between">
                  <h2 className="text-base font-semibold text-[#0E0F12]">Perfis de acesso</h2>
                  <button type="button" className="btn-primary text-xs" onClick={() => setRoleModal({ name: '', description: '', permissionIds: [] })}>
                    + Novo perfil
                  </button>
                </div>
                {rbacLoading ? <p className="text-sm text-[#0E0F12]/50">Carregando...</p> : (
                  <div className="space-y-2">
                    {rbacRoles.length === 0 && <p className="text-sm text-[#0E0F12]/50">Nenhum perfil cadastrado.</p>}
                    {rbacRoles.map((r: any) => (
                      <div key={r.id} className="flex items-center justify-between p-4 border border-[#EAE4D9] rounded-xl">
                        <div>
                          <p className="text-sm font-semibold text-[#0E0F12]">{r.name}</p>
                          {r.description && <p className="text-xs text-[#0E0F12]/50 mt-0.5">{r.description}</p>}
                          <p className="text-xs text-[#0E0F12]/40 mt-1">{r.permissions?.length ?? 0} permissão(ões)</p>
                        </div>
                        <div className="flex gap-3 shrink-0">
                          <button
                            type="button"
                            className="text-xs font-medium text-[#B7895A] hover:text-[#9E7248]"
                            onClick={() => setRoleModal({ id: r.id, name: r.name, description: r.description ?? '', permissionIds: r.permissions?.map((p: any) => p.id) ?? [] })}
                          >
                            Editar
                          </button>
                          {!r.isSystem && (
                            <button type="button" className="text-xs font-medium text-red-500 hover:text-red-700" onClick={() => handleDeleteRole(r.id)}>
                              Excluir
                            </button>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </>
            )}

            {tab === 'senha' && (
              <div className="max-w-md space-y-4">
                <h2 className="text-base font-semibold text-[#0E0F12]">Alterar senha</h2>
                {pwSuccess && <div className="bg-green-50 text-green-700 text-sm px-4 py-3 rounded-lg">{pwSuccess}</div>}
                {pwError   && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{pwError}</div>}
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Senha atual</label>
                  <input className="input" type="password" autoComplete="current-password" value={pwForm.current} onChange={(e) => setPwForm((p) => ({ ...p, current: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nova senha <span className="text-[#0E0F12]/40 font-normal text-xs">(mínimo 8 caracteres)</span></label>
                  <input className="input" type="password" autoComplete="new-password" value={pwForm.next} onChange={(e) => setPwForm((p) => ({ ...p, next: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#0E0F12] mb-1">Confirmar nova senha</label>
                  <input className="input" type="password" autoComplete="new-password" value={pwForm.confirm} onChange={(e) => setPwForm((p) => ({ ...p, confirm: e.target.value }))} />
                </div>
                <div className="flex justify-end pt-1">
                  <button type="button" className="btn-primary" disabled={pwSaving || !pwForm.current || !pwForm.next || !pwForm.confirm} onClick={handleChangePassword}>
                    {pwSaving ? 'Salvando...' : 'Alterar senha'}
                  </button>
                </div>
              </div>
            )}

            {!NO_SAVE_TABS.includes(tab) && (
              <div className="flex justify-end pt-2">
                <button type="submit" className="btn-primary" disabled={saving}>
                  {saving ? 'Salvando...' : 'Salvar configurações'}
                </button>
              </div>
            )}
          </form>
        </div>
      </div>

      {/* Modal: Novo usuário */}
      <Modal open={userModal} onClose={() => setUserModal(false)} title="Novo usuário">
        <form onSubmit={handleCreateUser} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome <span className="text-red-500">*</span></label>
            <input className="input" required minLength={2} value={userForm.name} onChange={(e) => setUserForm((p) => ({ ...p, name: e.target.value }))} placeholder="Maria Costa" />
          </div>
          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">E-mail <span className="text-red-500">*</span></label>
            <input className="input" type="email" required value={userForm.email} onChange={(e) => setUserForm((p) => ({ ...p, email: e.target.value }))} placeholder="maria@empresa.com" />
          </div>
          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Senha inicial <span className="text-red-500">*</span></label>
            <input className="input" type="password" required minLength={8} autoComplete="new-password" value={userForm.password} onChange={(e) => setUserForm((p) => ({ ...p, password: e.target.value }))} placeholder="Mínimo 8 caracteres" />
          </div>
          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Perfil de acesso</label>
            <select className="input" value={userForm.roleId} onChange={(e) => setUserForm((p) => ({ ...p, roleId: e.target.value }))}>
              <option value="">Sem perfil</option>
              {rbacRoles.map((r: any) => <option key={r.id} value={r.id}>{r.name}</option>)}
            </select>
          </div>
          {tenants.length > 1 && (
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-2">
                Acesso às empresas
                <span className="ml-1 font-normal text-[#0E0F12]/40 text-xs">(selecione ao menos uma)</span>
              </label>
              <div className="border border-[#EAE4D9] rounded-xl divide-y divide-[#EAE4D9] overflow-hidden">
                {tenants.map((t) => (
                  <label key={t.id} className="flex items-center gap-3 px-4 py-2.5 cursor-pointer hover:bg-[#FAF7F2]">
                    <input
                      type="checkbox"
                      className="h-4 w-4 rounded border-[#EAE4D9] accent-[#B7895A]"
                      checked={userForm.tenantIds.includes(t.id)}
                      onChange={(e) => setUserForm((p) => ({
                        ...p,
                        tenantIds: e.target.checked
                          ? [...p.tenantIds, t.id]
                          : p.tenantIds.filter((id) => id !== t.id),
                      }))}
                    />
                    <span className="text-sm text-[#0E0F12]">{t.name}</span>
                    {t.id === user?.tenantId && (
                      <span className="ml-auto text-xs text-[#B7895A] font-medium">atual</span>
                    )}
                  </label>
                ))}
              </div>
            </div>
          )}
          <div className="flex justify-end gap-3 pt-1">
            <button type="button" className="btn-secondary" onClick={() => setUserModal(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={userSaving || (tenants.length > 1 && userForm.tenantIds.length === 0)}>{userSaving ? '…' : 'Criar usuário'}</button>
          </div>
        </form>
      </Modal>

      {/* Modal: Atribuir perfil */}
      <Modal open={!!assignModal} onClose={() => setAssignModal(null)} title="Perfil de acesso">
        <form onSubmit={handleAssignRole} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Perfil</label>
            <select className="input" value={assignRoleId} onChange={(e) => setAssignRoleId(e.target.value)}>
              <option value="">Sem perfil</option>
              {rbacRoles.map((r: any) => <option key={r.id} value={r.id}>{r.name}</option>)}
            </select>
          </div>
          <div className="flex justify-end gap-3 pt-1">
            <button type="button" className="btn-secondary" onClick={() => setAssignModal(null)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={assignSaving}>{assignSaving ? '…' : 'Salvar'}</button>
          </div>
        </form>
      </Modal>

      {/* Modal: Criar / editar perfil */}
      <Modal open={!!roleModal} onClose={() => setRoleModal(null)} title={roleModal?.id ? 'Editar perfil' : 'Novo perfil'} wide>
        {roleModal && (
          <form onSubmit={handleSaveRole} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome do perfil <span className="text-red-500">*</span></label>
                <input className="input" required minLength={2} value={roleModal.name} onChange={(e) => setRoleModal((p) => p && ({ ...p, name: e.target.value }))} placeholder="Ex: Financeiro" />
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Descrição</label>
                <input className="input" value={roleModal.description} onChange={(e) => setRoleModal((p) => p && ({ ...p, description: e.target.value }))} placeholder="Opcional" />
              </div>
            </div>
            <div>
              <p className="text-sm font-medium text-[#0E0F12] mb-3">Permissões</p>
              <div className="border border-[#EAE4D9] rounded-xl overflow-hidden divide-y divide-[#EAE4D9]">
                {Object.entries(rbacPermissions).map(([mod, perms]) => (
                  <div key={mod} className="px-4 py-3">
                    <p className="text-xs font-semibold text-[#0E0F12]/60 uppercase tracking-wide mb-2">{MODULE_LABELS[mod] ?? mod}</p>
                    <div className="flex flex-wrap gap-x-4 gap-y-1.5">
                      {(perms as any[]).map((perm: any) => (
                        <label key={perm.id} className="flex items-center gap-1.5 cursor-pointer text-sm text-[#0E0F12]">
                          <input
                            type="checkbox"
                            className="h-3.5 w-3.5 rounded border-[#EAE4D9] accent-[#B7895A]"
                            checked={roleModal.permissionIds.includes(perm.id)}
                            onChange={(e) => setRoleModal((p) => {
                              if (!p) return p;
                              return {
                                ...p,
                                permissionIds: e.target.checked
                                  ? [...p.permissionIds, perm.id]
                                  : p.permissionIds.filter((id) => id !== perm.id),
                              };
                            })}
                          />
                          {ACTION_LABELS[perm.action] ?? perm.action}
                        </label>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className="flex justify-end gap-3 pt-1">
              <button type="button" className="btn-secondary" onClick={() => setRoleModal(null)}>Cancelar</button>
              <button type="submit" className="btn-primary" disabled={roleSaving}>{roleSaving ? '…' : 'Salvar perfil'}</button>
            </div>
          </form>
        )}
      </Modal>

      <Modal open={newCompanyOpen} onClose={() => setNewCompanyOpen(false)} title="Nova empresa">
        <form
          onSubmit={handleNewCompany}
          className="space-y-4"
        >
          {newCompanyError && (
            <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{newCompanyError}</div>
          )}
          <p className="text-sm text-[#0E0F12]/50">Crie uma nova empresa vinculada à sua conta. Você poderá alternar entre elas pela barra lateral.</p>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Razão social <span className="text-red-500">*</span></label>
            <input
              className="input"
              required
              minLength={2}
              value={newCompanyForm.name}
              onChange={(e) => setNewCompanyForm((p) => ({ ...p, name: e.target.value }))}
              placeholder="Empresa XYZ Ltda"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">CNPJ <span className="text-red-500">*</span></label>
            <input
              className="input"
              required
              minLength={14}
              maxLength={14}
              value={newCompanyForm.document}
              onChange={(e) => setNewCompanyForm((p) => ({ ...p, document: e.target.value.replace(/\D/g, '') }))}
              placeholder="00000000000000"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">E-mail <span className="text-red-500">*</span></label>
            <input
              className="input"
              type="email"
              required
              value={newCompanyForm.email}
              onChange={(e) => setNewCompanyForm((p) => ({ ...p, email: e.target.value }))}
              placeholder="contato@novaempresa.com"
            />
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setNewCompanyOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={newCompanySaving}>
              {newCompanySaving ? 'Criando...' : 'Criar empresa'}
            </button>
          </div>
        </form>
      </Modal>
    </>
  );
}
