// ═══════════════════════════════════════════════════════════════════════════
// Módulo: Assinatura Eletrônica — cofre de documentos avulsos (qualquer PDF,
// não só os gerados pelo sistema) enviados para assinatura via Autentique.
// Organizado em pastas ("cofres"), com vínculo opcional a Cliente e/ou Caso.
//
// Complementa (não substitui) o botão "Enviar para assinatura" já existente
// em Contratos de Honorários e Procurações (views/documentos.jsx) — aquele
// fluxo é para documentos que o próprio sistema gera; este é para qualquer
// PDF avulso: contrato de terceiro, aditivo, procuração fora do padrão etc.
// ═══════════════════════════════════════════════════════════════════════════

const SIG_STATUS_LABEL = {
  sent_for_signature: ['Aguardando assinatura', '#fef3c7', '#92400e'],
  signed: ['Assinado', '#dcfce7', '#15803d'],
  rejected: ['Recusado', '#fee2e2', '#b91c1c'],
  cancelled: ['Cancelado', '#f3f4f6', '#6b7280'],
};
const SigStatusBadge = ({ status }) => {
  const [label, bg, color] = SIG_STATUS_LABEL[status] || [status, '#f3f4f6', '#6b7280'];
  return <span style={{ background: bg, color, borderRadius: 20, padding: '2px 10px', fontSize: '.75rem', fontWeight: 700, whiteSpace: 'nowrap' }}>{label}</span>;
};

const SIGNER_STATUS_LABEL = {
  pending: ['Pendente', '#9ca3af'],
  viewed: ['Visualizou', '#2563eb'],
  signed: ['Assinou', '#15803d'],
  rejected: ['Recusou', '#b91c1c'],
};
const SignerStatusDot = ({ status }) => {
  const [label, color] = SIGNER_STATUS_LABEL[status] || SIGNER_STATUS_LABEL.pending;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: '.375rem', fontSize: '.8125rem', color: '#374151' }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: color, flexShrink: 0 }} />
      {label}
    </span>
  );
};

function signerSummary(signers) {
  const total = signers?.length || 0;
  const signed = (signers || []).filter(s => s.status === 'signed').length;
  return `${signed}/${total} assinaram`;
}

const MODAL_OVERLAY_STYLE = { position: 'fixed', inset: 0, background: 'rgba(23,23,15,.5)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 };
const MODAL_CARD_STYLE = { background: '#fff', borderRadius: 14, padding: '1.75rem', width: '100%', maxWidth: 560, maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 20px 60px rgba(0,0,0,.25)' };

// ═══════════════════════════════════════════════════════════════════════════
// PÁGINA PRINCIPAL
// ═══════════════════════════════════════════════════════════════════════════

const Assinaturas = ({ currentUser }) => {
  const [folders, setFolders] = React.useState([]);
  const [selectedFolder, setSelectedFolder] = React.useState('');
  const [documents, setDocuments] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [statusFilter, setStatusFilter] = React.useState('');
  const [search, setSearch] = React.useState('');
  const [showNewFolder, setShowNewFolder] = React.useState(false);
  const [showNewDocument, setShowNewDocument] = React.useState(false);
  const [selectedDocId, setSelectedDocId] = React.useState(null);
  const [toast, setToast] = React.useState('');

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

  const loadFolders = () => {
    fetch('/api/assinaturas/pastas', { credentials: 'include' })
      .then(r => r.json())
      .then(d => setFolders(d.data?.folders || []));
  };

  const loadDocuments = () => {
    setLoading(true);
    const params = new URLSearchParams();
    if (selectedFolder) params.set('folder_id', selectedFolder);
    if (statusFilter) params.set('status', statusFilter);
    if (search.trim()) params.set('search', search.trim());
    fetch(`/api/assinaturas/documentos?${params.toString()}`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => setDocuments(d.data?.documents || []))
      .finally(() => setLoading(false));
  };

  React.useEffect(loadFolders, []);
  React.useEffect(() => { const t = setTimeout(loadDocuments, 250); return () => clearTimeout(t); }, [selectedFolder, statusFilter, search]);

  const handleDeleteFolder = async (folder) => {
    if (!window.confirm(`Excluir a pasta "${folder.name}"? Os documentos dentro dela não são apagados — só ficam sem pasta.`)) return;
    const res = await fetch(`/api/assinaturas/pastas/${folder.id}`, { method: 'DELETE', credentials: 'include' });
    if (res.ok || res.status === 204) {
      if (selectedFolder === folder.id) setSelectedFolder('');
      loadFolders();
      showToast('Pasta excluída.');
    } else {
      const j = await res.json().catch(() => ({}));
      showToast(j.error || 'Erro ao excluir pasta.');
    }
  };

  return (
    <div style={{ padding: '1.5rem', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '.75rem' }}>
        <div>
          <h1 style={{ fontSize: '1.375rem', fontWeight: 700, color: 'var(--octale-navy)' }}>Assinatura Eletrônica</h1>
          <p style={{ fontSize: '.875rem', color: '#6b7280', marginTop: '.25rem' }}>
            Envie qualquer PDF para assinatura via Autentique, organizado em pastas por caso ou cliente.
          </p>
        </div>
        <button className="pac-btn pac-btn-primary" onClick={() => setShowNewDocument(true)}>
          <Icon name="upload" size={15} style={{ marginRight: 6, verticalAlign: -2 }} />
          Enviar documento
        </button>
      </div>

      <div style={{ display: 'flex', gap: '1.5rem', alignItems: 'flex-start' }}>
        {/* ── Sidebar de pastas ── */}
        <div style={{ width: 220, flexShrink: 0 }}>
          <div className="pac-card" style={{ padding: '.75rem' }}>
            <div
              onClick={() => setSelectedFolder('')}
              style={{
                padding: '.5rem .625rem', borderRadius: 8, cursor: 'pointer', fontSize: '.8125rem', fontWeight: 600,
                background: selectedFolder === '' ? 'rgba(23,23,15,.06)' : 'transparent',
                color: selectedFolder === '' ? 'var(--octale-navy)' : '#4b5563',
                display: 'flex', alignItems: 'center', gap: '.5rem', marginBottom: '.25rem',
              }}
            >
              <Icon name="fileText" size={14} /> Todos os documentos
            </div>
            {folders.map(f => (
              <div
                key={f.id}
                onClick={() => setSelectedFolder(f.id)}
                style={{
                  padding: '.5rem .625rem', borderRadius: 8, cursor: 'pointer', fontSize: '.8125rem', fontWeight: 600,
                  background: selectedFolder === f.id ? 'rgba(23,23,15,.06)' : 'transparent',
                  color: selectedFolder === f.id ? 'var(--octale-navy)' : '#4b5563',
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '.5rem', marginBottom: '.25rem',
                }}
              >
                <span style={{ display: 'flex', alignItems: 'center', gap: '.5rem', overflow: 'hidden' }}>
                  <Icon name="folder" size={14} style={{ flexShrink: 0 }} />
                  <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</span>
                </span>
                <span
                  onClick={(e) => { e.stopPropagation(); handleDeleteFolder(f); }}
                  style={{ opacity: .5, fontSize: '.75rem' }}
                  title="Excluir pasta"
                >
                  ✕
                </span>
              </div>
            ))}
            <button
              className="pac-btn pac-btn-ghost"
              style={{ width: '100%', marginTop: '.5rem', fontSize: '.8125rem', justifyContent: 'flex-start' }}
              onClick={() => setShowNewFolder(true)}
            >
              <Icon name="plus" size={13} style={{ marginRight: 6 }} /> Nova pasta
            </button>
          </div>
        </div>

        {/* ── Lista de documentos ── */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', gap: '.625rem', marginBottom: '1rem', flexWrap: 'wrap' }}>
            <input
              className="pac-input" placeholder="Buscar por nome…" value={search}
              onChange={e => setSearch(e.target.value)} style={{ flex: 1, minWidth: 200 }}
            />
            <select className="pac-input" value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ width: 200 }}>
              <option value="">Todos os status</option>
              <option value="sent_for_signature">Aguardando assinatura</option>
              <option value="signed">Assinado</option>
              <option value="rejected">Recusado</option>
              <option value="cancelled">Cancelado</option>
            </select>
          </div>

          {loading ? (
            <div className="pac-loading" style={{ padding: '2rem' }}>Carregando...</div>
          ) : documents.length === 0 ? (
            <div className="pac-card" style={{ padding: '2.5rem', textAlign: 'center', color: '#9ca3af' }}>
              <p style={{ fontSize: '1.0625rem', marginBottom: '.5rem' }}>Nenhum documento por aqui.</p>
              <p style={{ fontSize: '.875rem' }}>Clique em "Enviar documento" para mandar um PDF para assinatura.</p>
            </div>
          ) : (
            <div className="pac-card" style={{ padding: 0, overflow: 'hidden' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '.875rem' }}>
                <thead>
                  <tr style={{ background: '#fafaf8', textAlign: 'left' }}>
                    <th style={{ padding: '.75rem 1rem', color: '#6b7280', fontWeight: 600, fontSize: '.75rem' }}>Documento</th>
                    <th style={{ padding: '.75rem 1rem', color: '#6b7280', fontWeight: 600, fontSize: '.75rem' }}>Vínculo</th>
                    <th style={{ padding: '.75rem 1rem', color: '#6b7280', fontWeight: 600, fontSize: '.75rem' }}>Signatários</th>
                    <th style={{ padding: '.75rem 1rem', color: '#6b7280', fontWeight: 600, fontSize: '.75rem' }}>Status</th>
                    <th style={{ padding: '.75rem 1rem', color: '#6b7280', fontWeight: 600, fontSize: '.75rem' }}>Enviado em</th>
                  </tr>
                </thead>
                <tbody>
                  {documents.map(doc => (
                    <tr
                      key={doc.id}
                      onClick={() => setSelectedDocId(doc.id)}
                      style={{ borderTop: '1px solid #f3f4f6', cursor: 'pointer' }}
                      onMouseEnter={e => e.currentTarget.style.background = '#fafaf8'}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                    >
                      <td style={{ padding: '.75rem 1rem', fontWeight: 600, color: 'var(--octale-navy)' }}>{doc.name}</td>
                      <td style={{ padding: '.75rem 1rem', color: '#6b7280' }}>
                        {doc.clients?.name || (doc.cases ? `${doc.cases.number} — ${doc.cases.title}` : '—')}
                      </td>
                      <td style={{ padding: '.75rem 1rem', color: '#6b7280' }}>{signerSummary(doc.signature_document_signers)}</td>
                      <td style={{ padding: '.75rem 1rem' }}><SigStatusBadge status={doc.status} /></td>
                      <td style={{ padding: '.75rem 1rem', color: '#9ca3af' }}>{new Date(doc.created_at).toLocaleDateString('pt-BR')}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {showNewFolder && (
        <NovaPastaModal
          onClose={() => setShowNewFolder(false)}
          onCreated={() => { setShowNewFolder(false); loadFolders(); showToast('Pasta criada.'); }}
        />
      )}
      {showNewDocument && (
        <NovoDocumentoModal
          folders={folders}
          defaultFolderId={selectedFolder}
          onClose={() => setShowNewDocument(false)}
          onCreated={() => { setShowNewDocument(false); loadDocuments(); showToast('Documento enviado para assinatura.'); }}
        />
      )}
      {selectedDocId && (
        <DetalheDocumentoModal
          id={selectedDocId}
          onClose={() => setSelectedDocId(null)}
          onChanged={() => { loadDocuments(); }}
          showToast={showToast}
        />
      )}

      {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: 10000, whiteSpace: 'nowrap' }}>
          {toast}
        </div>
      )}
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════
// NOVA PASTA
// ═══════════════════════════════════════════════════════════════════════════

const NovaPastaModal = ({ onClose, onCreated }) => {
  const [name, setName] = React.useState('');
  const [clients, setClients] = React.useState([]);
  const [cases, setCases] = React.useState([]);
  const [clientId, setClientId] = React.useState('');
  const [caseId, setCaseId] = React.useState('');
  const [saving, setSaving] = 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 || []));
  }, []);
  React.useEffect(() => {
    if (!clientId) { setCases([]); setCaseId(''); return; }
    fetch(`/api/cases?client_id=${clientId}`, { credentials: 'include' }).then(r => r.json()).then(d => setCases(d.data?.cases || d.cases || []));
  }, [clientId]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) { setError('Informe o nome da pasta.'); return; }
    setSaving(true);
    setError('');
    try {
      const res = await fetch('/api/assinaturas/pastas', {
        method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), client_id: clientId || null, case_id: caseId || null }),
      });
      const json = await res.json();
      if (!res.ok) { setError(json.error || 'Erro ao criar pasta.'); return; }
      onCreated();
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={MODAL_OVERLAY_STYLE} onClick={onClose}>
      <form className="pac-card" style={MODAL_CARD_STYLE} onClick={e => e.stopPropagation()} onSubmit={handleSubmit}>
        <h2 style={{ fontSize: '1.0625rem', fontWeight: 700, color: 'var(--octale-navy)', marginBottom: '1.25rem' }}>Nova pasta</h2>

        <div style={{ marginBottom: '.875rem' }}>
          <label className="pac-label">Nome *</label>
          <input className="pac-input" value={name} onChange={e => setName(e.target.value)} placeholder="Ex.: Caso Silva x Empresa X" autoFocus />
        </div>

        <div style={{ marginBottom: '.875rem' }}>
          <label className="pac-label">Cliente (opcional)</label>
          <SearchableSelect value={clientId} onChange={setClientId} className="pac-input">
            <option value="">— Nenhum —</option>
            {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </SearchableSelect>
        </div>

        {clientId && (
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Caso (opcional)</label>
            <SearchableSelect value={caseId} onChange={setCaseId} className="pac-input">
              <option value="">— Nenhum —</option>
              {cases.map(c => <option key={c.id} value={c.id}>{c.number} — {c.title}</option>)}
            </SearchableSelect>
          </div>
        )}

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

// ═══════════════════════════════════════════════════════════════════════════
// NOVO DOCUMENTO (upload + envio para assinatura)
// ═══════════════════════════════════════════════════════════════════════════

const NovoDocumentoModal = ({ folders, defaultFolderId, onClose, onCreated }) => {
  const [file, setFile] = React.useState(null);
  const [name, setName] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [folderId, setFolderId] = React.useState(defaultFolderId || '');
  const [clients, setClients] = React.useState([]);
  const [cases, setCases] = React.useState([]);
  const [clientId, setClientId] = React.useState('');
  const [caseId, setCaseId] = React.useState('');
  const [signers, setSigners] = React.useState([{ name: '', email: '' }]);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const [dragOver, setDragOver] = React.useState(false);

  React.useEffect(() => {
    fetch('/api/clients', { credentials: 'include' }).then(r => r.json()).then(d => setClients(d.data?.clients || d.clients || []));
  }, []);
  React.useEffect(() => {
    if (!clientId) { setCases([]); setCaseId(''); return; }
    fetch(`/api/cases?client_id=${clientId}`, { credentials: 'include' }).then(r => r.json()).then(d => setCases(d.data?.cases || d.cases || []));
  }, [clientId]);

  const pickFile = (f) => {
    if (!f) return;
    if (f.type !== 'application/pdf') { setError('Apenas arquivos PDF são aceitos.'); return; }
    setError('');
    setFile(f);
    if (!name) setName(f.name.replace(/\.pdf$/i, ''));
  };

  const updateSigner = (i, field, value) => {
    setSigners(prev => prev.map((s, idx) => idx === i ? { ...s, [field]: value } : s));
  };
  const addSigner = () => setSigners(prev => [...prev, { name: '', email: '' }]);
  const removeSigner = (i) => setSigners(prev => prev.filter((_, idx) => idx !== i));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!file) { setError('Selecione um arquivo PDF.'); return; }
    if (!name.trim()) { setError('Informe o nome do documento.'); return; }
    const validSigners = signers.filter(s => s.email.trim());
    if (!validSigners.length) { setError('Informe ao menos um signatário com e-mail.'); return; }

    setSending(true);
    setError('');
    try {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('name', name.trim());
      if (message.trim()) fd.append('message', message.trim());
      if (folderId) fd.append('folder_id', folderId);
      if (clientId) fd.append('client_id', clientId);
      if (caseId) fd.append('case_id', caseId);
      fd.append('signers', JSON.stringify(validSigners.map(s => ({ name: s.name.trim() || undefined, email: s.email.trim() }))));

      const res = await fetch('/api/assinaturas/documentos', { method: 'POST', credentials: 'include', body: fd });
      const json = await res.json();
      if (!res.ok) { setError(json.error || 'Erro ao enviar documento.'); return; }
      onCreated();
    } finally {
      setSending(false);
    }
  };

  return (
    <div style={MODAL_OVERLAY_STYLE} onClick={onClose}>
      <form className="pac-card" style={MODAL_CARD_STYLE} onClick={e => e.stopPropagation()} onSubmit={handleSubmit}>
        <h2 style={{ fontSize: '1.0625rem', fontWeight: 700, color: 'var(--octale-navy)', marginBottom: '1.25rem' }}>Enviar documento para assinatura</h2>

        <div
          onDragOver={e => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={e => { e.preventDefault(); setDragOver(false); pickFile(e.dataTransfer.files?.[0]); }}
          onClick={() => document.getElementById('assinatura-file-input').click()}
          style={{
            border: `2px dashed ${dragOver ? 'var(--accent)' : '#d1d5db'}`, borderRadius: 10, padding: '1.5rem',
            textAlign: 'center', cursor: 'pointer', marginBottom: '1rem',
            background: dragOver ? 'rgba(92,102,64,.05)' : '#fafaf8',
          }}
        >
          <input id="assinatura-file-input" type="file" accept="application/pdf" hidden onChange={e => pickFile(e.target.files?.[0])} />
          {file ? (
            <span style={{ fontWeight: 600, color: 'var(--octale-navy)' }}><Icon name="fileText" size={15} style={{ marginRight: 6, verticalAlign: -2 }} />{file.name}</span>
          ) : (
            <span style={{ color: '#9ca3af', fontSize: '.875rem' }}>Arraste um PDF aqui ou clique para escolher</span>
          )}
        </div>

        <div style={{ marginBottom: '.875rem' }}>
          <label className="pac-label">Nome do documento *</label>
          <input className="pac-input" value={name} onChange={e => setName(e.target.value)} placeholder="Ex.: Aditivo contratual — Cliente X" />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '.875rem', marginBottom: '.875rem' }}>
          <div>
            <label className="pac-label">Pasta (opcional)</label>
            <SearchableSelect value={folderId} onChange={setFolderId} className="pac-input">
              <option value="">— Sem pasta —</option>
              {folders.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
            </SearchableSelect>
          </div>
          <div>
            <label className="pac-label">Cliente (opcional)</label>
            <SearchableSelect value={clientId} onChange={setClientId} className="pac-input">
              <option value="">— Nenhum —</option>
              {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </SearchableSelect>
          </div>
        </div>

        {clientId && (
          <div style={{ marginBottom: '.875rem' }}>
            <label className="pac-label">Caso (opcional)</label>
            <SearchableSelect value={caseId} onChange={setCaseId} className="pac-input">
              <option value="">— Nenhum —</option>
              {cases.map(c => <option key={c.id} value={c.id}>{c.number} — {c.title}</option>)}
            </SearchableSelect>
          </div>
        )}

        <div style={{ marginBottom: '.875rem' }}>
          <label className="pac-label">Mensagem para os signatários (opcional)</label>
          <textarea className="pac-input" rows={2} value={message} onChange={e => setMessage(e.target.value)} placeholder="Aparece no e-mail de convite para assinatura" />
        </div>

        <div style={{ marginBottom: '.875rem' }}>
          <label className="pac-label">Signatários *</label>
          {signers.map((s, i) => (
            <div key={i} style={{ display: 'flex', gap: '.5rem', marginBottom: '.5rem' }}>
              <input className="pac-input" placeholder="Nome (opcional)" value={s.name} onChange={e => updateSigner(i, 'name', e.target.value)} style={{ flex: 1 }} />
              <input className="pac-input" placeholder="E-mail *" type="email" value={s.email} onChange={e => updateSigner(i, 'email', e.target.value)} style={{ flex: 1 }} />
              {signers.length > 1 && (
                <button type="button" className="pac-btn pac-btn-ghost" onClick={() => removeSigner(i)} style={{ padding: '0 .625rem', color: '#b91c1c' }}>✕</button>
              )}
            </div>
          ))}
          <button type="button" className="pac-btn pac-btn-ghost" onClick={addSigner} style={{ fontSize: '.8125rem' }}>
            <Icon name="plus" size={13} style={{ marginRight: 4 }} /> Adicionar signatário
          </button>
        </div>

        {error && <div className="pac-error" style={{ marginBottom: '.875rem' }}>{error}</div>}
        <div style={{ display: 'flex', gap: '.75rem', justifyContent: 'flex-end' }}>
          <button type="button" className="pac-btn pac-btn-ghost" onClick={onClose}>Cancelar</button>
          <button type="submit" className="pac-btn pac-btn-primary" disabled={sending}>{sending ? 'Enviando...' : 'Enviar para assinatura'}</button>
        </div>
      </form>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════════════
// DETALHE DO DOCUMENTO
// ═══════════════════════════════════════════════════════════════════════════

const DetalheDocumentoModal = ({ id, onClose, onChanged, showToast }) => {
  const [doc, setDoc] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [busy, setBusy] = React.useState(false);

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

  const runAction = async (fn) => {
    setBusy(true);
    try { await fn(); } finally { setBusy(false); }
  };

  const handleSync = () => runAction(async () => {
    const res = await fetch(`/api/assinaturas/documentos/${id}/sincronizar`, { method: 'POST', credentials: 'include' });
    const json = await res.json();
    if (!res.ok) { showToast(json.error || 'Erro ao sincronizar.'); return; }
    setDoc(json.data.document);
    onChanged();
    showToast('Status atualizado.');
  });

  const handleResend = () => runAction(async () => {
    const res = await fetch(`/api/assinaturas/documentos/${id}/reenviar`, { method: 'POST', credentials: 'include' });
    const json = await res.json();
    showToast(res.ok ? 'Lembrete reenviado.' : (json.error || 'Erro ao reenviar.'));
  });

  const handleCancel = () => runAction(async () => {
    if (!window.confirm('Cancelar este documento? Os signatários que ainda não assinaram não conseguirão mais assinar.')) return;
    const res = await fetch(`/api/assinaturas/documentos/${id}/cancelar`, { method: 'PATCH', credentials: 'include' });
    const json = await res.json();
    if (!res.ok) { showToast(json.error || 'Erro ao cancelar.'); return; }
    setDoc(json.data.document);
    onChanged();
    showToast('Documento cancelado.');
  });

  const handleDelete = () => runAction(async () => {
    if (!window.confirm('Excluir permanentemente este documento? Esta ação não pode ser desfeita.')) return;
    const res = await fetch(`/api/assinaturas/documentos/${id}`, { method: 'DELETE', credentials: 'include' });
    if (res.ok || res.status === 204) { onChanged(); onClose(); } else { const j = await res.json().catch(() => ({})); showToast(j.error || 'Erro ao excluir.'); }
  });

  const copyLink = (link) => {
    navigator.clipboard?.writeText(link);
    showToast('Link copiado.');
  };

  return (
    <div style={MODAL_OVERLAY_STYLE} onClick={onClose}>
      <div className="pac-card" style={MODAL_CARD_STYLE} onClick={e => e.stopPropagation()}>
        {loading || !doc ? (
          <div className="pac-loading" style={{ padding: '2rem' }}>Carregando...</div>
        ) : (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1.25rem', gap: '.75rem' }}>
              <div>
                <h2 style={{ fontSize: '1.0625rem', fontWeight: 700, color: 'var(--octale-navy)' }}>{doc.name}</h2>
                <div style={{ marginTop: '.375rem' }}><SigStatusBadge status={doc.status} /></div>
              </div>
              <button type="button" className="pac-btn pac-btn-ghost" onClick={onClose} style={{ padding: '.25rem .5rem' }}>✕</button>
            </div>

            {(doc.clients?.name || doc.cases || doc.signature_folders) && (
              <div style={{ fontSize: '.8125rem', color: '#6b7280', marginBottom: '1rem', display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
                {doc.clients?.name && <span><Icon name="user" size={12} style={{ marginRight: 4, verticalAlign: -1 }} />{doc.clients.name}</span>}
                {doc.cases && <span><Icon name="briefcase" size={12} style={{ marginRight: 4, verticalAlign: -1 }} />{doc.cases.number} — {doc.cases.title}</span>}
                {doc.signature_folders && <span><Icon name="folder" size={12} style={{ marginRight: 4, verticalAlign: -1 }} />{doc.signature_folders.name}</span>}
              </div>
            )}

            <div style={{ marginBottom: '1.25rem' }}>
              <div style={{ fontWeight: 700, fontSize: '.8125rem', color: '#374151', marginBottom: '.5rem' }}>Signatários</div>
              {(doc.signature_document_signers || []).map(s => (
                <div key={s.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '.5rem 0', borderBottom: '1px solid #f3f4f6', fontSize: '.8125rem' }}>
                  <div>
                    <div style={{ fontWeight: 600 }}>{s.name || s.email}</div>
                    {s.name && <div style={{ color: '#9ca3af' }}>{s.email}</div>}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '.75rem' }}>
                    <SignerStatusDot status={s.status} />
                    {s.signature_link && s.status !== 'signed' && (
                      <button type="button" className="pac-btn pac-btn-ghost" style={{ padding: '.125rem .5rem', fontSize: '.75rem' }} onClick={() => copyLink(s.signature_link)}>
                        Copiar link
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>

            <div style={{ display: 'flex', gap: '.5rem', flexWrap: 'wrap' }}>
              <a className="pac-btn pac-btn-secondary" href={`/api/assinaturas/documentos/${id}/pdf`} target="_blank" rel="noreferrer">
                <Icon name="download" size={14} style={{ marginRight: 6, verticalAlign: -2 }} />PDF original
              </a>
              {doc.signed_pdf_storage_path && (
                <a className="pac-btn pac-btn-secondary" href={`/api/assinaturas/documentos/${id}/pdf?signed=1`} target="_blank" rel="noreferrer">
                  <Icon name="download" size={14} style={{ marginRight: 6, verticalAlign: -2 }} />PDF assinado
                </a>
              )}
              {doc.status === 'sent_for_signature' && (
                <>
                  <button type="button" className="pac-btn pac-btn-secondary" onClick={handleSync} disabled={busy}>Sincronizar status</button>
                  <button type="button" className="pac-btn pac-btn-secondary" onClick={handleResend} disabled={busy}>Reenviar pendentes</button>
                  <button type="button" className="pac-btn pac-btn-ghost" onClick={handleCancel} disabled={busy} style={{ color: '#b91c1c' }}>Cancelar</button>
                </>
              )}
              <button type="button" className="pac-btn pac-btn-ghost" onClick={handleDelete} disabled={busy} style={{ color: '#b91c1c', marginLeft: 'auto' }}>Excluir</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

window.Assinaturas = Assinaturas;
