// Módulo: Documentos Jurídicos — Contrato de Honorários Advocatícios e Procuração

const FA_STATUS_LABEL = {
  draft: ['Rascunho', '#f3f4f6', '#6b7280'],
  generated: ['PDF gerado', '#dbeafe', '#1d4ed8'],
  sent_for_signature: ['Aguardando assinatura', '#fef3c7', '#92400e'],
  signed: ['Assinado', '#dcfce7', '#15803d'],
  cancelled: ['Cancelado', '#fee2e2', '#b91c1c'],
};

const StatusBadge = ({ status }) => {
  const [label, bg, color] = FA_STATUS_LABEL[status] || [status, '#f3f4f6', '#6b7280'];
  return <span style={{ background: bg, color, borderRadius: 20, padding: '2px 10px', fontSize: '.75rem', fontWeight: 700 }}>{label}</span>;
};

const Documentos = ({ currentUser }) => {
  const [tab, setTab] = React.useState('honorarios'); // 'honorarios' | 'procuracoes'

  return (
    <div style={{ padding: '1.5rem', maxWidth: 1000, margin: '0 auto' }}>
      <div style={{ marginBottom: '1.5rem' }}>
        <h1 style={{ fontSize: '1.375rem', fontWeight: 700, color: 'var(--pac-navy)' }}>Documentos Jurídicos</h1>
        <p style={{ fontSize: '.875rem', color: '#6b7280', marginTop: '.25rem' }}>Contratos de Honorários Advocatícios e Procurações.</p>
      </div>

      <div style={{ display: 'flex', gap: '.5rem', marginBottom: '1.5rem', borderBottom: '1.5px solid #e5e7eb' }}>
        {[['honorarios', 'Contratos de Honorários'], ['procuracoes', 'Procurações']].map(([key, label]) => (
          <button
            key={key}
            onClick={() => setTab(key)}
            style={{
              padding: '.625rem 1rem', border: 'none', background: 'none', cursor: 'pointer',
              fontWeight: 600, fontSize: '.875rem',
              color: tab === key ? 'var(--pac-navy)' : '#9ca3af',
              borderBottom: tab === key ? '2.5px solid var(--pac-navy)' : '2.5px solid transparent',
              marginBottom: '-1.5px',
            }}
          >
            {label}
          </button>
        ))}
      </div>

      {tab === 'honorarios' && <ContratosHonorarios currentUser={currentUser} />}
      {tab === 'procuracoes' && <Procuracoes currentUser={currentUser} />}
    </div>
  );
};

// ════════════════════════════════════════════════════════════════════════════
// CONTRATOS DE HONORÁRIOS
// ════════════════════════════════════════════════════════════════════════════

const ContratosHonorarios = ({ currentUser }) => {
  const [view, setView] = React.useState('list'); // 'list' | 'new' | 'detail'
  const [selectedId, setSelectedId] = React.useState(null);

  if (view === 'new')
    return <NovoContratoHonorarios onBack={() => setView('list')} onCreated={(id) => { setSelectedId(id); setView('detail'); }} />;
  if (view === 'detail' && selectedId)
    return <DetalheContratoHonorarios id={selectedId} onBack={() => setView('list')} />;
  return <ListaContratosHonorarios onNew={() => setView('new')} onOpen={(id) => { setSelectedId(id); setView('detail'); }} />;
};

const ListaContratosHonorarios = ({ onNew, onOpen }) => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    fetch('/api/documentos/contratos-honorarios', { credentials: 'include' })
      .then(r => r.json())
      .then(d => setItems(d.data?.fee_agreements || []))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '1rem' }}>
        <button className="pac-btn pac-btn-primary" onClick={onNew}>+ Novo contrato</button>
      </div>
      {loading && <div className="pac-loading">Carregando...</div>}
      {!loading && items.length === 0 && (
        <div style={{ textAlign: 'center', padding: '4rem 0', color: '#9ca3af' }}>
          <p style={{ fontSize: '1.125rem', marginBottom: '.5rem' }}>Nenhum contrato criado ainda.</p>
          <p style={{ fontSize: '.875rem' }}>Clique em "+ Novo contrato" para começar.</p>
        </div>
      )}
      {!loading && items.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '.75rem' }}>
          {items.map(item => (
            <div key={item.id} className="pac-card" style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '1rem' }} onClick={() => onOpen(item.id)}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, color: '#111', marginBottom: '.25rem' }}>{item.client_name || item.clients?.name || 'Contratante não informado'}</div>
                <div style={{ fontSize: '.8125rem', color: '#6b7280' }}>{item.scope_description?.slice(0, 80)}</div>
              </div>
              <StatusBadge status={item.status} />
              <div style={{ fontSize: '.75rem', color: '#9ca3af', flexShrink: 0 }}>{new Date(item.created_at).toLocaleDateString('pt-BR')}</div>
              <span style={{ color: '#9ca3af', fontSize: '1.25rem' }}>›</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// Subformulários de remuneração por tipo
const PaymentFormMonthly = ({ value, onChange }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.75rem' }}>
    <div>
      <label className="pac-label">Valor mensal *</label>
      <input className="pac-input" value={value.amount || ''} onChange={e => onChange({ ...value, amount: e.target.value })} placeholder="Ex: R$ 5.000,00" required />
    </div>
    <div>
      <label className="pac-label">Dia de vencimento</label>
      <input type="number" min="1" max="31" className="pac-input" value={value.dayOfMonth || ''} onChange={e => onChange({ ...value, dayOfMonth: e.target.value ? parseInt(e.target.value) : null })} placeholder="Ex: 10" />
    </div>
  </div>
);

const PaymentFormInstallments = ({ value, onChange }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '.75rem' }}>
    <div>
      <label className="pac-label">Nº de parcelas *</label>
      <input type="number" min="1" className="pac-input" value={value.installmentCount || ''} onChange={e => onChange({ ...value, installmentCount: parseInt(e.target.value) || '' })} placeholder="Ex: 12" required />
    </div>
    <div>
      <label className="pac-label">Valor de cada parcela *</label>
      <input className="pac-input" value={value.installmentAmount || ''} onChange={e => onChange({ ...value, installmentAmount: e.target.value })} placeholder="Ex: R$ 1.000,00" required />
    </div>
    <div>
      <label className="pac-label">Vencimento da 1.ª parcela</label>
      <input type="date" className="pac-input" value={value.firstDueDate || ''} onChange={e => onChange({ ...value, firstDueDate: e.target.value || null })} />
    </div>
  </div>
);

const PaymentFormResidual = ({ value, onChange }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '.75rem' }}>
    <div style={{ background: '#f8fafc', borderRadius: 6, padding: '.625rem .875rem', fontSize: '.8125rem', color: '#6b7280' }}>
      Modelo para causas em que há parcelas iniciais (ex: honorários de ingresso) + parcelas residuais mensais durante o processo.
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.75rem' }}>
      <div>
        <label className="pac-label">Nº de parcelas iniciais *</label>
        <input type="number" min="1" className="pac-input" value={value.initialCount || ''} onChange={e => onChange({ ...value, initialCount: parseInt(e.target.value) || '' })} placeholder="Ex: 3" required />
      </div>
      <div>
        <label className="pac-label">Valor de cada parcela inicial *</label>
        <input className="pac-input" value={value.initialAmount || ''} onChange={e => onChange({ ...value, initialAmount: e.target.value })} placeholder="Ex: R$ 3.000,00" required />
      </div>
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.75rem' }}>
      <div>
        <label className="pac-label">Valor das parcelas residuais *</label>
        <input className="pac-input" value={value.residualAmount || ''} onChange={e => onChange({ ...value, residualAmount: e.target.value })} placeholder="Ex: R$ 500,00/mês" required />
      </div>
      <div>
        <label className="pac-label">Início das parcelas residuais</label>
        <input type="date" className="pac-input" value={value.residualStartDate || ''} onChange={e => onChange({ ...value, residualStartDate: e.target.value || null })} />
      </div>
    </div>
  </div>
);

const NovoContratoHonorarios = ({ onBack, onCreated }) => {
  const [clients, setClients] = React.useState([]);
  const [proposals, setProposals] = React.useState([]);
  const [clientId, setClientId] = React.useState('');
  const [proposalId, setProposalId] = React.useState('');
  // Dados do contratante editáveis diretamente no formulário
  const [clientName, setClientName] = React.useState('');
  const [clientDocument, setClientDocument] = React.useState('');
  const [clientAddress, setClientAddress] = React.useState('');
  const [updateClient, setUpdateClient] = React.useState(false);
  const [scopeDescription, setScopeDescription] = React.useState('');

  // Remuneração estruturada
  const [paymentType, setPaymentType] = React.useState('monthly');
  const [paymentData, setPaymentData] = React.useState({});
  const [hasSuccessFee, setHasSuccessFee] = React.useState(false);
  const [successFeeTerms, setSuccessFeeTerms] = React.useState('');

  const [hasMinimumTerm, setHasMinimumTerm] = React.useState(false);
  const [termText, setTermText] = React.useState('12 (doze) meses, contados da assinatura deste Contrato, renovando-se automaticamente por prazo indeterminado.');
  const [notes, setNotes] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    fetch('/api/clients', { credentials: 'include' }).then(r => r.json()).then(d => setClients(d.data?.clients || d.clients || []));
    fetch('/api/propostas', { credentials: 'include' }).then(r => r.json()).then(d => setProposals(d.data?.proposals || []));
  }, []);

  const handleClientChange = (id) => {
    setClientId(id);
    setUpdateClient(false);
    if (!id) { setClientName(''); setClientDocument(''); setClientAddress(''); return; }
    const c = clients.find(c => c.id === id);
    if (c) {
      setClientName(c.name || '');
      setClientDocument(c.cnpj || c.cpf || '');
      const parts = [
        c.street && c.address_number ? `${c.street}, ${c.address_number}` : c.street,
        c.complement, c.district,
        c.city && c.state ? `${c.city}/${c.state}` : c.city,
        c.cep,
      ].filter(Boolean);
      setClientAddress(parts.join(', '));
    }
  };

  const handlePaymentTypeChange = (type) => {
    setPaymentType(type);
    setPaymentData({});
  };

  const buildPaymentDetails = () => ({ type: paymentType, ...paymentData });

  const validatePayment = () => {
    if (paymentType === 'monthly' && !paymentData.amount) return 'Informe o valor mensal.';
    if (paymentType === 'installments') {
      if (!paymentData.installmentCount) return 'Informe o número de parcelas.';
      if (!paymentData.installmentAmount) return 'Informe o valor de cada parcela.';
    }
    if (paymentType === 'residual') {
      if (!paymentData.initialCount) return 'Informe o número de parcelas iniciais.';
      if (!paymentData.initialAmount) return 'Informe o valor das parcelas iniciais.';
      if (!paymentData.residualAmount) return 'Informe o valor das parcelas residuais.';
    }
    if (paymentType === 'custom' && !paymentData.text) return 'Descreva a forma de remuneração.';
    return null;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!clientName.trim()) { setError('Informe o nome do contratante.'); return; }
    if (!scopeDescription.trim()) { setError('Descreva o escopo dos serviços.'); return; }
    const paymentError = validatePayment();
    if (paymentError) { setError(paymentError); return; }

    setSending(true);
    try {
      const res = await fetch('/api/documentos/contratos-honorarios', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          client_id: clientId || null,
          client_name: clientName.trim(),
          client_document: clientDocument.trim() || null,
          client_address: clientAddress.trim() || null,
          update_client: clientId ? updateClient : false,
          proposal_id: proposalId || null,
          scope_description: scopeDescription.trim(),
          payment_type: paymentType,
          payment_details: buildPaymentDetails(),
          fee_amount: '',
          has_success_fee: hasSuccessFee,
          success_fee_terms: hasSuccessFee ? successFeeTerms.trim() || null : null,
          has_minimum_term: hasMinimumTerm,
          term_text: termText.trim(),
          notes: notes.trim() || null,
        }),
      });
      const json = await res.json();
      if (!res.ok) { setError(json.error || 'Erro ao criar contrato.'); return; }
      onCreated(json.data.fee_agreement.id);
    } catch (err) {
      setError('Erro de conexão.');
    } finally {
      setSending(false);
    }
  };

  const PAYMENT_TYPES = [
    { value: 'monthly', label: 'Mensal' },
    { value: 'installments', label: 'Parcelado' },
    { value: 'residual', label: 'Parcelas + Residual' },
    { value: 'custom', label: 'Personalizado' },
  ];

  return (
    <div style={{ maxWidth: 700 }}>
      <button className="pac-btn pac-btn-ghost" style={{ marginBottom: '1rem' }} onClick={onBack}>← Voltar</button>
      <h2 style={{ fontSize: '1.125rem', fontWeight: 700, color: 'var(--pac-navy)', marginBottom: '1.5rem' }}>Novo Contrato de Honorários</h2>

      <form onSubmit={handleSubmit}>
        {/* Contratante */}
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.875rem', color: '#374151' }}>Contratante</div>

          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Vincular cliente <span style={{ fontWeight: 400, color: '#9ca3af' }}>(opcional — preenche os dados automaticamente)</span></label>
            <SearchableSelect className="pac-input" value={clientId} onChange={e => handleClientChange(e.target.value)}>
              <option value="">— Sem cliente vinculado —</option>
              {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </SearchableSelect>
          </div>

          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Nome do contratante *</label>
            <input className="pac-input" value={clientName} onChange={e => setClientName(e.target.value)} placeholder="Nome completo ou razão social" required />
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.875rem', marginBottom: '.875rem' }}>
            <div>
              <label className="pac-label">CPF / CNPJ</label>
              <input className="pac-input" value={clientDocument} onChange={e => setClientDocument(e.target.value)} placeholder="000.000.000-00" />
            </div>
            <div>
              <label className="pac-label">Endereço</label>
              <input className="pac-input" value={clientAddress} onChange={e => setClientAddress(e.target.value)} placeholder="Rua, nº, cidade/UF" />
            </div>
          </div>

          {clientId && (
            <div style={{ borderTop: '1px solid #f3f4f6', paddingTop: '.75rem' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: '.5rem', fontSize: '.8125rem', cursor: 'pointer', color: '#374151' }}>
                <input type="checkbox" checked={updateClient} onChange={e => setUpdateClient(e.target.checked)} />
                Salvar nome e documento no cadastro do cliente
              </label>
            </div>
          )}

          <div style={{ marginTop: '.875rem' }}>
            <label className="pac-label">Vincular proposta <span style={{ fontWeight: 400, color: '#9ca3af' }}>(opcional — a proposta será anexada ao PDF do contrato)</span></label>
            <SearchableSelect className="pac-input" value={proposalId} onChange={e => setProposalId(e.target.value)}>
              <option value="">— Sem proposta vinculada —</option>
              {proposals.map(p => (
                <option key={p.id} value={p.id}>{p.proposal_number} · {p.client_name}</option>
              ))}
            </SearchableSelect>
          </div>

          <div style={{ marginTop: '.875rem' }}>
            <label className="pac-label">Proposta e Serviços *</label>
            <textarea className="pac-input" rows={3} value={scopeDescription} onChange={e => setScopeDescription(e.target.value)} placeholder="Descreva o escopo dos serviços contratados" required />
          </div>
        </div>

        {/* Remuneração */}
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.875rem', color: '#374151' }}>Remuneração</div>

          {/* Tipo de pagamento */}
          <div style={{ display: 'flex', gap: '.5rem', marginBottom: '.875rem', flexWrap: 'wrap' }}>
            {PAYMENT_TYPES.map(pt => (
              <button
                key={pt.value}
                type="button"
                onClick={() => handlePaymentTypeChange(pt.value)}
                style={{
                  padding: '.375rem .875rem', borderRadius: 20, border: '1.5px solid',
                  fontSize: '.8125rem', fontWeight: 600, cursor: 'pointer',
                  borderColor: paymentType === pt.value ? 'var(--pac-navy)' : '#e5e7eb',
                  background: paymentType === pt.value ? 'var(--pac-navy)' : '#fff',
                  color: paymentType === pt.value ? '#fff' : '#374151',
                }}
              >
                {pt.label}
              </button>
            ))}
          </div>

          {/* Campos dinâmicos por tipo */}
          <div style={{ marginBottom: '.875rem' }}>
            {paymentType === 'monthly' && <PaymentFormMonthly value={paymentData} onChange={setPaymentData} />}
            {paymentType === 'installments' && <PaymentFormInstallments value={paymentData} onChange={setPaymentData} />}
            {paymentType === 'residual' && <PaymentFormResidual value={paymentData} onChange={setPaymentData} />}
            {paymentType === 'custom' && (
              <div>
                <label className="pac-label">Descrição da remuneração *</label>
                <textarea className="pac-input" rows={3} value={paymentData.text || ''} onChange={e => setPaymentData({ ...paymentData, text: e.target.value })} placeholder="Descreva livremente a forma de remuneração" required />
              </div>
            )}
          </div>

          {/* Honorários de êxito */}
          <div style={{ borderTop: '1px solid #f3f4f6', paddingTop: '.875rem' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: '.5rem', fontSize: '.875rem', cursor: 'pointer', fontWeight: 600, color: '#374151' }}>
              <input type="checkbox" checked={hasSuccessFee} onChange={e => setHasSuccessFee(e.target.checked)} />
              Honorários de êxito
            </label>
            {hasSuccessFee && (
              <div style={{ marginTop: '.625rem' }}>
                <label className="pac-label">Termos do êxito</label>
                <textarea className="pac-input" rows={2} value={successFeeTerms} onChange={e => setSuccessFeeTerms(e.target.value)} placeholder="Ex: 10% sobre o proveito econômico obtido" />
              </div>
            )}
          </div>
        </div>

        {/* Vigência */}
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.875rem', color: '#374151' }}>Vigência</div>
          <div style={{ marginBottom: '.875rem' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: '.5rem', fontSize: '.875rem', cursor: 'pointer' }}>
              <input type="checkbox" checked={hasMinimumTerm} onChange={e => setHasMinimumTerm(e.target.checked)} />
              Permanência mínima
            </label>
          </div>
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Vigência e rescisão</label>
            <textarea className="pac-input" rows={2} value={termText} onChange={e => setTermText(e.target.value)} />
          </div>
          <div>
            <label className="pac-label">Observações</label>
            <textarea className="pac-input" rows={2} value={notes} onChange={e => setNotes(e.target.value)} placeholder="Opcional" />
          </div>
        </div>

        {error && <div className="pac-error" style={{ marginBottom: '.875rem' }}>{error}</div>}
        <div style={{ display: 'flex', gap: '.75rem' }}>
          <button type="button" className="pac-btn pac-btn-ghost" onClick={onBack}>Cancelar</button>
          <button type="submit" className="pac-btn pac-btn-primary" disabled={sending}>{sending ? 'Criando...' : 'Criar contrato'}</button>
        </div>
      </form>
    </div>
  );
};

const PAYMENT_TYPE_LABEL = { monthly: 'Mensal', installments: 'Parcelado', residual: 'Parcelas + Residual', custom: 'Personalizado' };

const RemuneracaoResumo = ({ agreement }) => {
  const pd = agreement.payment_details;
  if (!pd) {
    return (
      <span>
        {agreement.fee_amount}
        {agreement.has_success_fee && <><br /><span style={{ color: '#6b7280' }}>Êxito: {agreement.success_fee_terms || 'a definir'}</span></>}
      </span>
    );
  }

  const tag = (
    <span style={{ fontSize: '.7rem', fontWeight: 700, background: '#eff6ff', color: '#1d4ed8', borderRadius: 10, padding: '1px 7px', marginRight: '.5rem' }}>
      {PAYMENT_TYPE_LABEL[pd.type] || pd.type}
    </span>
  );

  let detail = null;
  if (pd.type === 'monthly') {
    detail = `${pd.amount}${pd.dayOfMonth ? ` · todo dia ${pd.dayOfMonth}` : ''}`;
  } else if (pd.type === 'installments') {
    const first = pd.firstDueDate ? ` · 1.ª: ${new Date(pd.firstDueDate).toLocaleDateString('pt-BR')}` : '';
    detail = `${pd.installmentCount}× ${pd.installmentAmount}${first}`;
  } else if (pd.type === 'residual') {
    const start = pd.residualStartDate ? ` a partir de ${new Date(pd.residualStartDate).toLocaleDateString('pt-BR')}` : '';
    detail = `${pd.initialCount}× ${pd.initialAmount} (iniciais) + ${pd.residualAmount} residual${start}`;
  } else if (pd.type === 'custom') {
    detail = pd.text;
  }

  return (
    <span>
      {tag}{detail}
      {agreement.has_success_fee && <><br /><span style={{ color: '#6b7280' }}>Êxito: {agreement.success_fee_terms || 'a definir'}</span></>}
    </span>
  );
};

const DetalheContratoHonorarios = ({ id, onBack }) => {
  const [agreement, setAgreement] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const [toast, setToast] = React.useState('');
  const [signerEmail, setSignerEmail] = React.useState('');

  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(''), 3000); };

  const load = () => {
    setLoading(true);
    fetch(`/api/documentos/contratos-honorarios/${id}`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => setAgreement(d.data?.fee_agreement || null))
      .finally(() => setLoading(false));
  };
  React.useEffect(load, [id]);

  const handlePdf = () => window.open(`/api/documentos/contratos-honorarios/${id}/pdf`, '_blank');

  const handleSendSignature = async () => {
    if (!signerEmail.trim()) { showToast('Informe o e-mail do signatário.'); return; }
    setBusy(true);
    try {
      const res = await fetch(`/api/documentos/contratos-honorarios/${id}/send-signature`, {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ signerEmail: signerEmail.trim() }),
      });
      const json = await res.json();
      if (!res.ok) { showToast(json.error || 'Erro ao enviar para assinatura.'); return; }
      showToast('Enviado para assinatura via D4Sign.');
      load();
    } finally {
      setBusy(false);
    }
  };

  const handleCancel = async () => {
    if (!window.confirm('Cancelar este contrato?')) return;
    setBusy(true);
    try {
      const res = await fetch(`/api/documentos/contratos-honorarios/${id}/cancel`, { method: 'PATCH', credentials: 'include' });
      if (res.ok) load(); else showToast('Erro ao cancelar.');
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async () => {
    if (!window.confirm('Excluir permanentemente este contrato? Esta ação não pode ser desfeita.')) return;
    setBusy(true);
    try {
      const res = await fetch(`/api/documentos/contratos-honorarios/${id}`, { method: 'DELETE', credentials: 'include' });
      if (res.ok || res.status === 204) { onBack(); } else { const j = await res.json(); showToast(j.error || 'Erro ao excluir.'); }
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <div className="pac-loading" style={{ padding: '2rem' }}>Carregando...</div>;
  if (!agreement) return <div style={{ padding: '2rem' }}>Contrato não encontrado.</div>;

  return (
    <div style={{ maxWidth: 760 }}>
      <button className="pac-btn pac-btn-ghost" style={{ marginBottom: '1rem' }} onClick={onBack}>← Voltar</button>

      <div style={{ display: 'flex', alignItems: 'center', gap: '.75rem', marginBottom: '1.25rem' }}>
        <h2 style={{ fontSize: '1.125rem', fontWeight: 700, color: 'var(--pac-navy)' }}>{agreement.client_name || agreement.clients?.name}</h2>
        <StatusBadge status={agreement.status} />
      </div>

      <div className="pac-card" style={{ marginBottom: '1rem' }}>
        <table style={{ width: '100%', fontSize: '.875rem' }}>
          <tbody>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', width: 180, verticalAlign: 'top' }}>Proposta e Serviços</td><td style={{ padding: '.5rem 0' }}>{agreement.scope_description}</td></tr>
            <tr>
              <td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Remuneração</td>
              <td style={{ padding: '.5rem 0' }}>
                <RemuneracaoResumo agreement={agreement} />
              </td>
            </tr>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Permanência mínima</td><td style={{ padding: '.5rem 0' }}>{agreement.has_minimum_term ? 'Sim' : 'Não'}</td></tr>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Vigência e rescisão</td><td style={{ padding: '.5rem 0' }}>{agreement.term_text}</td></tr>
            {agreement.notes && <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Observações</td><td style={{ padding: '.5rem 0' }}>{agreement.notes}</td></tr>}
            {agreement.proposal_id && (
              <tr>
                <td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Proposta anexada</td>
                <td style={{ padding: '.5rem 0' }}>
                  <span style={{ fontSize: '.8125rem', background: '#eff6ff', color: '#1d4ed8', borderRadius: 10, padding: '2px 8px', fontWeight: 600 }}>Incluída no PDF</span>
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="pac-card" style={{ marginBottom: '1rem', display: 'flex', gap: '.75rem', flexWrap: 'wrap' }}>
        <button className="pac-btn pac-btn-secondary" onClick={handlePdf}>Visualizar / baixar PDF</button>
        {agreement.status !== 'cancelled' && agreement.status !== 'signed' && (
          <button className="pac-btn pac-btn-ghost" onClick={handleCancel} disabled={busy} style={{ color: '#b91c1c' }}>Cancelar contrato</button>
        )}
        <button className="pac-btn pac-btn-ghost" onClick={handleDelete} disabled={busy} style={{ color: '#b91c1c', marginLeft: 'auto' }}>Excluir</button>
      </div>

      {agreement.status !== 'cancelled' && agreement.status !== 'signed' && agreement.status !== 'sent_for_signature' && (
        <div className="pac-card">
          <div style={{ fontWeight: 700, marginBottom: '.75rem', color: '#374151' }}>Enviar para assinatura (D4Sign)</div>
          <div style={{ display: 'flex', gap: '.5rem' }}>
            <input className="pac-input" placeholder="E-mail do contratante" value={signerEmail} onChange={e => setSignerEmail(e.target.value)} style={{ flex: 1 }} />
            <button className="pac-btn pac-btn-primary" onClick={handleSendSignature} disabled={busy}>Enviar</button>
          </div>
        </div>
      )}

      {toast && (
        <div style={{ position: 'fixed', bottom: '1.5rem', left: '50%', transform: 'translateX(-50%)', background: '#1f2937', color: '#fff', padding: '.625rem 1.25rem', borderRadius: 8, fontSize: '.875rem', fontWeight: 500, zIndex: 200, whiteSpace: 'nowrap' }}>
          {toast}
        </div>
      )}
    </div>
  );
};

// ════════════════════════════════════════════════════════════════════════════
// PROCURAÇÕES
// ════════════════════════════════════════════════════════════════════════════

const Procuracoes = ({ currentUser }) => {
  const [view, setView] = React.useState('list');
  const [selectedId, setSelectedId] = React.useState(null);

  if (view === 'new')
    return <NovaProcuracao onBack={() => setView('list')} onCreated={(id) => { setSelectedId(id); setView('detail'); }} />;
  if (view === 'detail' && selectedId)
    return <DetalheProcuracao id={selectedId} onBack={() => setView('list')} />;
  return <ListaProcuracoes onNew={() => setView('new')} onOpen={(id) => { setSelectedId(id); setView('detail'); }} />;
};

const ListaProcuracoes = ({ onNew, onOpen }) => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    fetch('/api/documentos/procuracoes', { credentials: 'include' })
      .then(r => r.json())
      .then(d => setItems(d.data?.powers_of_attorney || []))
      .finally(() => setLoading(false));
  }, []);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '1rem' }}>
        <button className="pac-btn pac-btn-primary" onClick={onNew}>+ Nova procuração</button>
      </div>
      {loading && <div className="pac-loading">Carregando...</div>}
      {!loading && items.length === 0 && (
        <div style={{ textAlign: 'center', padding: '4rem 0', color: '#9ca3af' }}>
          <p style={{ fontSize: '1.125rem', marginBottom: '.5rem' }}>Nenhuma procuração criada ainda.</p>
          <p style={{ fontSize: '.875rem' }}>Clique em "+ Nova procuração" para começar.</p>
        </div>
      )}
      {!loading && items.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '.75rem' }}>
          {items.map(item => (
            <div key={item.id} className="pac-card" style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '1rem' }} onClick={() => onOpen(item.id)}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, color: '#111', marginBottom: '.25rem' }}>{item.grantor_name}</div>
                <div style={{ fontSize: '.8125rem', color: '#6b7280' }}>
                  {item.clients?.name || 'Avulsa (sem cliente vinculado)'} · {item.matter_description?.slice(0, 60)}
                </div>
              </div>
              <StatusBadge status={item.status} />
              <div style={{ fontSize: '.75rem', color: '#9ca3af', flexShrink: 0 }}>{new Date(item.created_at).toLocaleDateString('pt-BR')}</div>
              <span style={{ color: '#9ca3af', fontSize: '1.25rem' }}>›</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const NovaProcuracao = ({ onBack, onCreated }) => {
  const [clients, setClients] = React.useState([]);
  const [defaultAttorneys, setDefaultAttorneys] = React.useState([]);
  const [clientId, setClientId] = React.useState('');
  const [grantorName, setGrantorName] = React.useState('');
  const [grantorQualification, setGrantorQualification] = React.useState('');
  const [grantorDocument, setGrantorDocument] = React.useState('');
  const [addressStreet, setAddressStreet] = React.useState('');
  const [addressNumber, setAddressNumber] = React.useState('');
  const [addressComplement, setAddressComplement] = React.useState('');
  const [addressDistrict, setAddressDistrict] = React.useState('');
  const [addressCity, setAddressCity] = React.useState('');
  const [addressCep, setAddressCep] = React.useState('');
  const [matterDescription, setMatterDescription] = React.useState('');
  const [place, setPlace] = React.useState('Ribeirão Preto/SP');
  const [signatureMethod, setSignatureMethod] = React.useState('external');
  const [lawyers, setLawyers] = React.useState([]);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    fetch('/api/clients', { credentials: 'include' }).then(r => r.json()).then(d => setClients(d.data?.clients || d.clients || []));
    fetch('/api/documentos/procuracoes/default-attorneys', { credentials: 'include' })
      .then(r => r.json())
      .then(d => setLawyers((d.data?.attorneys || []).map(a => ({ name: a.name, oab: a.oab, qualification: a.qualification, included: true }))));
  }, []);

  const applyClient = (id) => {
    setClientId(id);
    const c = clients.find(c => c.id === id);
    if (c) {
      setGrantorName(c.name);
      setGrantorDocument(c.cnpj || c.cpf || '');
    }
  };

  const toggleLawyer = (i) => setLawyers(prev => prev.map((l, idx) => idx === i ? { ...l, included: !l.included } : l));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!grantorName.trim()) { setError('Informe o nome do outorgante.'); return; }
    if (!grantorQualification.trim()) { setError('Informe a qualificação do outorgante.'); return; }
    if (!grantorDocument.trim()) { setError('Informe o CPF/CNPJ do outorgante.'); return; }
    if (!addressStreet.trim()) { setError('Informe a rua do endereço.'); return; }
    if (!addressNumber.trim()) { setError('Informe o número do endereço.'); return; }
    if (!addressCity.trim()) { setError('Informe a cidade do endereço.'); return; }
    if (!matterDescription.trim()) { setError('Descreva o objeto da procuração.'); return; }
    if (!lawyers.some(l => l.included)) { setError('Selecione ao menos um advogado outorgado.'); return; }

    setSending(true);
    try {
      const res = await fetch('/api/documentos/procuracoes', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          client_id: clientId || null,
          grantor_name: grantorName.trim(),
          grantor_qualification: grantorQualification.trim(),
          grantor_document: grantorDocument.trim(),
          grantor_address: [
            `${addressStreet.trim()}, nº ${addressNumber.trim()}`,
            addressComplement.trim(),
            addressDistrict.trim(),
            addressCity.trim(),
            addressCep.trim() ? `CEP: ${addressCep.trim()}` : '',
          ].filter(Boolean).join(', '),
          matter_description: matterDescription.trim(),
          place: place.trim(),
          signature_method: signatureMethod,
          lawyers,
        }),
      });
      const json = await res.json();
      if (!res.ok) { setError(json.error || 'Erro ao criar procuração.'); return; }
      onCreated(json.data.power_of_attorney.id);
    } catch (err) {
      setError('Erro de conexão.');
    } finally {
      setSending(false);
    }
  };

  return (
    <div style={{ maxWidth: 700 }}>
      <button className="pac-btn pac-btn-ghost" style={{ marginBottom: '1rem' }} onClick={onBack}>← Voltar</button>
      <h2 style={{ fontSize: '1.125rem', fontWeight: 700, color: 'var(--pac-navy)', marginBottom: '1.5rem' }}>Nova Procuração</h2>

      <form onSubmit={handleSubmit}>
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.875rem', color: '#374151' }}>Outorgante</div>
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Cliente vinculado <span style={{ fontWeight: 400, color: '#9ca3af' }}>(opcional — preenche os dados automaticamente)</span></label>
            <SearchableSelect className="pac-input" value={clientId} onChange={e => applyClient(e.target.value)}>
              <option value="">— Procuração avulsa, sem cliente —</option>
              {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </SearchableSelect>
          </div>
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Nome *</label>
            <input className="pac-input" value={grantorName} onChange={e => setGrantorName(e.target.value)} required />
          </div>
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Qualificação *</label>
            <input className="pac-input" value={grantorQualification} onChange={e => setGrantorQualification(e.target.value)} placeholder="Ex: brasileiro, casado, empresário" required />
          </div>
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">CPF/CNPJ *</label>
            <input className="pac-input" value={grantorDocument} onChange={e => setGrantorDocument(e.target.value)} required />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '.875rem', marginBottom: '.875rem' }}>
            <div>
              <label className="pac-label">Rua *</label>
              <input className="pac-input" value={addressStreet} onChange={e => setAddressStreet(e.target.value)} placeholder="Nome da rua / avenida" />
            </div>
            <div style={{ width: 100 }}>
              <label className="pac-label">Nº *</label>
              <input className="pac-input" value={addressNumber} onChange={e => setAddressNumber(e.target.value)} placeholder="Ex: 123" />
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.875rem', marginBottom: '.875rem' }}>
            <div>
              <label className="pac-label">Complemento</label>
              <input className="pac-input" value={addressComplement} onChange={e => setAddressComplement(e.target.value)} placeholder="Apto, sala, bloco..." />
            </div>
            <div>
              <label className="pac-label">Bairro</label>
              <input className="pac-input" value={addressDistrict} onChange={e => setAddressDistrict(e.target.value)} placeholder="Opcional" />
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.875rem' }}>
            <div>
              <label className="pac-label">Cidade *</label>
              <input className="pac-input" value={addressCity} onChange={e => setAddressCity(e.target.value)} placeholder="Ex: Ribeirão Preto" />
            </div>
            <div>
              <label className="pac-label">CEP</label>
              <input className="pac-input" value={addressCep} onChange={e => setAddressCep(e.target.value)} placeholder="Opcional" />
            </div>
          </div>
        </div>

        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.875rem', color: '#374151' }}>Poderes</div>
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Objeto / matéria *</label>
            <textarea className="pac-input" rows={3} value={matterDescription} onChange={e => setMatterDescription(e.target.value)} placeholder="Descreva o objeto da procuração" required />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.875rem' }}>
            <div>
              <label className="pac-label">Local</label>
              <input className="pac-input" value={place} onChange={e => setPlace(e.target.value)} />
            </div>
            <div>
              <label className="pac-label">Método de assinatura *</label>
              <select className="pac-input" value={signatureMethod} onChange={e => setSignatureMethod(e.target.value)}>
                <option value="external">Externa (upload manual — ex: gov.br)</option>
                <option value="d4sign">D4Sign</option>
              </select>
            </div>
          </div>
        </div>

        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.875rem', color: '#374151' }}>Advogados outorgados</div>
          {lawyers.map((l, i) => (
            <label key={i} style={{ display: 'flex', alignItems: 'center', gap: '.625rem', padding: '.5rem 0', fontSize: '.875rem', cursor: 'pointer' }}>
              <input type="checkbox" checked={l.included} onChange={() => toggleLawyer(i)} />
              <div>
                <div style={{ fontWeight: 600 }}>{l.name}</div>
                <div style={{ fontSize: '.75rem', color: '#9ca3af' }}>{l.oab} · {l.qualification}</div>
              </div>
            </label>
          ))}
        </div>

        {error && <div className="pac-error" style={{ marginBottom: '.875rem' }}>{error}</div>}
        <div style={{ display: 'flex', gap: '.75rem' }}>
          <button type="button" className="pac-btn pac-btn-ghost" onClick={onBack}>Cancelar</button>
          <button type="submit" className="pac-btn pac-btn-primary" disabled={sending}>{sending ? 'Criando...' : 'Criar procuração'}</button>
        </div>
      </form>
    </div>
  );
};

const DetalheProcuracao = ({ id, onBack }) => {
  const [poa, setPoa] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const [toast, setToast] = React.useState('');
  const [signerEmail, setSignerEmail] = React.useState('');
  const [signedFile, setSignedFile] = React.useState(null);

  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(''), 3000); };

  const load = () => {
    setLoading(true);
    fetch(`/api/documentos/procuracoes/${id}`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => setPoa(d.data?.power_of_attorney || null))
      .finally(() => setLoading(false));
  };
  React.useEffect(load, [id]);

  const handlePdf = () => window.open(`/api/documentos/procuracoes/${id}/pdf`, '_blank');

  const handleSendSignature = async () => {
    if (!signerEmail.trim()) { showToast('Informe o e-mail do signatário.'); return; }
    setBusy(true);
    try {
      const res = await fetch(`/api/documentos/procuracoes/${id}/send-signature`, {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ signerEmail: signerEmail.trim() }),
      });
      const json = await res.json();
      if (!res.ok) { showToast(json.error || 'Erro ao enviar para assinatura.'); return; }
      showToast('Enviado para assinatura via D4Sign.');
      load();
    } finally {
      setBusy(false);
    }
  };

  const handleUploadSigned = async () => {
    if (!signedFile) { showToast('Selecione o PDF assinado.'); return; }
    setBusy(true);
    try {
      const fd = new FormData();
      fd.append('file', signedFile);
      const res = await fetch(`/api/documentos/procuracoes/${id}/upload-signed`, { method: 'POST', credentials: 'include', body: fd });
      const json = await res.json();
      if (!res.ok) { showToast(json.error || 'Erro ao enviar PDF assinado.'); return; }
      showToast('PDF assinado registrado.');
      setSignedFile(null);
      load();
    } finally {
      setBusy(false);
    }
  };

  const handleCancel = async () => {
    if (!window.confirm('Cancelar esta procuração?')) return;
    setBusy(true);
    try {
      const res = await fetch(`/api/documentos/procuracoes/${id}/cancel`, { method: 'PATCH', credentials: 'include' });
      if (res.ok) load(); else showToast('Erro ao cancelar.');
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async () => {
    if (!window.confirm('Excluir permanentemente esta procuração? Esta ação não pode ser desfeita.')) return;
    setBusy(true);
    try {
      const res = await fetch(`/api/documentos/procuracoes/${id}`, { method: 'DELETE', credentials: 'include' });
      if (res.ok || res.status === 204) { onBack(); } else { const j = await res.json(); showToast(j.error || 'Erro ao excluir.'); }
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <div className="pac-loading" style={{ padding: '2rem' }}>Carregando...</div>;
  if (!poa) return <div style={{ padding: '2rem' }}>Procuração não encontrada.</div>;

  const includedLawyers = (poa.power_of_attorney_lawyers || []).filter(l => l.included);

  return (
    <div style={{ maxWidth: 760 }}>
      <button className="pac-btn pac-btn-ghost" style={{ marginBottom: '1rem' }} onClick={onBack}>← Voltar</button>

      <div style={{ display: 'flex', alignItems: 'center', gap: '.75rem', marginBottom: '1.25rem' }}>
        <h2 style={{ fontSize: '1.125rem', fontWeight: 700, color: 'var(--pac-navy)' }}>{poa.grantor_name}</h2>
        <StatusBadge status={poa.status} />
      </div>

      <div className="pac-card" style={{ marginBottom: '1rem' }}>
        <table style={{ width: '100%', fontSize: '.875rem' }}>
          <tbody>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', width: 180, verticalAlign: 'top' }}>Cliente vinculado</td><td style={{ padding: '.5rem 0' }}>{poa.clients?.name || 'Avulsa (sem vínculo)'}</td></tr>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>CPF/CNPJ</td><td style={{ padding: '.5rem 0' }}>{poa.grantor_document}</td></tr>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Qualificação</td><td style={{ padding: '.5rem 0' }}>{poa.grantor_qualification}</td></tr>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Objeto</td><td style={{ padding: '.5rem 0' }}>{poa.matter_description}</td></tr>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Assinatura</td><td style={{ padding: '.5rem 0' }}>{poa.signature_method === 'd4sign' ? 'D4Sign' : 'Externa (upload manual)'}</td></tr>
            <tr><td style={{ padding: '.5rem 0', color: '#6b7280', verticalAlign: 'top' }}>Advogados outorgados</td><td style={{ padding: '.5rem 0' }}>{includedLawyers.map(l => l.name).join('; ')}</td></tr>
          </tbody>
        </table>
      </div>

      <div className="pac-card" style={{ marginBottom: '1rem', display: 'flex', gap: '.75rem', flexWrap: 'wrap' }}>
        <button className="pac-btn pac-btn-secondary" onClick={handlePdf}>Visualizar / baixar PDF</button>
        {poa.status !== 'cancelled' && poa.status !== 'signed' && (
          <button className="pac-btn pac-btn-ghost" onClick={handleCancel} disabled={busy} style={{ color: '#b91c1c' }}>Cancelar procuração</button>
        )}
        <button className="pac-btn pac-btn-ghost" onClick={handleDelete} disabled={busy} style={{ color: '#b91c1c', marginLeft: 'auto' }}>Excluir</button>
      </div>

      {poa.status !== 'cancelled' && poa.status !== 'signed' && poa.signature_method === 'd4sign' && poa.status !== 'sent_for_signature' && (
        <div className="pac-card" style={{ marginBottom: '1rem' }}>
          <div style={{ fontWeight: 700, marginBottom: '.75rem', color: '#374151' }}>Enviar para assinatura (D4Sign)</div>
          <div style={{ display: 'flex', gap: '.5rem' }}>
            <input className="pac-input" placeholder="E-mail do outorgante" value={signerEmail} onChange={e => setSignerEmail(e.target.value)} style={{ flex: 1 }} />
            <button className="pac-btn pac-btn-primary" onClick={handleSendSignature} disabled={busy}>Enviar</button>
          </div>
        </div>
      )}

      {poa.status !== 'cancelled' && poa.status !== 'signed' && poa.signature_method === 'external' && (
        <div className="pac-card">
          <div style={{ fontWeight: 700, marginBottom: '.75rem', color: '#374151' }}>Upload do PDF assinado (ex.: gov.br)</div>
          <div style={{ display: 'flex', gap: '.5rem' }}>
            <input type="file" accept="application/pdf" className="pac-input" onChange={e => setSignedFile(e.target.files?.[0] || null)} style={{ flex: 1 }} />
            <button className="pac-btn pac-btn-primary" onClick={handleUploadSigned} disabled={busy}>Enviar</button>
          </div>
        </div>
      )}

      {toast && (
        <div style={{ position: 'fixed', bottom: '1.5rem', left: '50%', transform: 'translateX(-50%)', background: '#1f2937', color: '#fff', padding: '.625rem 1.25rem', borderRadius: 8, fontSize: '.875rem', fontWeight: 500, zIndex: 200, whiteSpace: 'nowrap' }}>
          {toast}
        </div>
      )}
    </div>
  );
};

window.Documentos = Documentos;
